{"version":3,"file":"common-cc96d03b.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/sorted_map.ts","../src/util/sorted_set.ts","../src/model/field_mask.ts","../src/util/obj.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/remote/number_serializer.ts","../src/model/transform_operation.ts","../src/model/mutation.ts","../src/core/bound.ts","../src/core/filter.ts","../src/core/order_by.ts","../src/model/document.ts","../src/core/target.ts","../src/core/query.ts","../src/remote/existence_filter.ts","../src/remote/rpc_error.ts","../src/util/obj_map.ts","../src/model/collections.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/platform/node/serializer.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/api/long_polling_options.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/remote/backoff.ts","../src/remote/persistent_stream.ts","../src/remote/datastore.ts","../src/lite-api/components.ts","../src/local/lru_garbage_collector.ts","../src/local/lru_garbage_collector_impl.ts","../src/lite-api/settings.ts","../src/lite-api/database.ts","../src/lite-api/reference.ts","../src/util/array.ts","../src/lite-api/vector_value.ts","../src/lite-api/user_data_reader.ts","../src/core/options_util.ts","../src/util/proto.ts","../src/lite-api/field_value_impl.ts","../src/lite-api/expressions.ts","../src/lite-api/stage.ts","../src/core/pipeline.ts","../src/core/expressions.ts","../src/core/pipeline-util.ts","../src/model/mutation_batch.ts","../src/model/overlay.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/indexeddb_lru_delegate_impl.ts","../src/core/pipeline_run.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/local/local_store_impl.ts","../src/model/document_comparator.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/platform/node/dom.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/api/realtime_pipeline.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/util/async_queue_impl.ts","../src/api/bundle.ts","../src/api/database.ts","../src/core/aggregate.ts","../src/lite-api/user_data_writer.ts","../src/api/user_data_writer.ts","../src/core/structured_pipeline.ts","../src/remote/internal_serializer.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 *   <ul>\n *     <li>`debug` for the most verbose logging level, primarily for\n *     debugging.</li>\n *     <li>`error` to log errors only.</li>\n *     <li><code>`silent` to turn off logging.</li>\n *   </ul>\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n  logClient.setLogLevel(logLevel);\n}\n\nexport function logDebug(msg: string, ...obj: unknown[]): void {\n  if (logClient.logLevel <= LogLevel.DEBUG) {\n    const args = obj.map(argToString);\n    logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n  }\n}\n\nexport function logError(msg: string, ...obj: unknown[]): void {\n  if (logClient.logLevel <= LogLevel.ERROR) {\n    const args = obj.map(argToString);\n    logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n  }\n}\n\n/**\n * @internal\n */\nexport function logWarn(msg: string, ...obj: unknown[]): void {\n  if (logClient.logLevel <= LogLevel.WARN) {\n    const args = obj.map(argToString);\n    logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n  }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n  if (typeof obj === 'string') {\n    return obj;\n  } else {\n    try {\n      return formatJSON(obj);\n    } catch (e) {\n      // Converting to JSON failed, just log the object directly\n      return obj;\n    }\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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<string, unknown>\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<string, unknown>): never;\n\nexport function fail(\n  id: number,\n  messageOrContext?: string | Record<string, unknown>,\n  context?: Record<string, unknown>\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<string, unknown>\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<string, unknown>\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<string, unknown>\n): asserts assertion;\n\nexport function hardAssert(\n  assertion: boolean,\n  id: number,\n  messageOrContext?: string | Record<string, unknown>,\n  context?: Record<string, unknown>\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<T>(\n  obj: object,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  constructor: { new (...args: any[]): T }\n): T | never {\n  debugAssert(\n    obj instanceof constructor,\n    `Expected type '${constructor.name}', but was '${obj.constructor.name}'`\n  );\n  return obj as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * The set of Firestore status codes. The codes are the same at the ones\n * exposed by gRPC here:\n * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * Possible values:\n * - 'cancelled': The operation was cancelled (typically by the caller).\n * - 'unknown': Unknown error or an error from a different error domain.\n * - 'invalid-argument': Client specified an invalid argument. Note that this\n *   differs from 'failed-precondition'. 'invalid-argument' indicates\n *   arguments that are problematic regardless of the state of the system\n *   (e.g. an invalid field name).\n * - 'deadline-exceeded': Deadline expired before operation could complete.\n *   For operations that change the state of the system, this error may be\n *   returned even if the operation has completed successfully. For example,\n *   a successful response from a server could have been delayed long enough\n *   for the deadline to expire.\n * - 'not-found': Some requested document was not found.\n * - 'already-exists': Some document that we attempted to create already\n *   exists.\n * - 'permission-denied': The caller does not have permission to execute the\n *   specified operation.\n * - 'resource-exhausted': Some resource has been exhausted, perhaps a\n *   per-user quota, or perhaps the entire file system is out of space.\n * - 'failed-precondition': Operation was rejected because the system is not\n *   in a state required for the operation's execution.\n * - 'aborted': The operation was aborted, typically due to a concurrency\n *   issue like transaction aborts, etc.\n * - 'out-of-range': Operation was attempted past the valid range.\n * - 'unimplemented': Operation is not implemented or not supported/enabled.\n * - 'internal': Internal errors. Means some invariants expected by\n *   underlying system has been broken. If you see one of these errors,\n *   something is very broken.\n * - 'unavailable': The service is currently unavailable. This is most likely\n *   a transient condition and may be corrected by retrying with a backoff.\n * - 'data-loss': Unrecoverable data loss or corruption.\n * - 'unauthenticated': The request does not have valid authentication\n *   credentials for the operation.\n */\nexport type FirestoreErrorCode =\n  | 'cancelled'\n  | 'unknown'\n  | 'invalid-argument'\n  | 'deadline-exceeded'\n  | 'not-found'\n  | 'already-exists'\n  | 'permission-denied'\n  | 'resource-exhausted'\n  | 'failed-precondition'\n  | 'aborted'\n  | 'out-of-range'\n  | 'unimplemented'\n  | 'internal'\n  | 'unavailable'\n  | 'data-loss'\n  | 'unauthenticated';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = FirestoreErrorCode;\n\nexport const Code = {\n  // Causes are copied from:\n  // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n  /** Not an error; returned on success. */\n  OK: 'ok' as FirestoreErrorCode,\n\n  /** The operation was cancelled (typically by the caller). */\n  CANCELLED: 'cancelled' as FirestoreErrorCode,\n\n  /** Unknown error or an error from a different error domain. */\n  UNKNOWN: 'unknown' as FirestoreErrorCode,\n\n  /**\n   * Client specified an invalid argument. Note that this differs from\n   * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n   * problematic regardless of the state of the system (e.g., a malformed file\n   * name).\n   */\n  INVALID_ARGUMENT: 'invalid-argument' as FirestoreErrorCode,\n\n  /**\n   * Deadline expired before operation could complete. For operations that\n   * change the state of the system, this error may be returned even if the\n   * operation has completed successfully. For example, a successful response\n   * from a server could have been delayed long enough for the deadline to\n   * expire.\n   */\n  DEADLINE_EXCEEDED: 'deadline-exceeded' as FirestoreErrorCode,\n\n  /** Some requested entity (e.g., file or directory) was not found. */\n  NOT_FOUND: 'not-found' as FirestoreErrorCode,\n\n  /**\n   * Some entity that we attempted to create (e.g., file or directory) already\n   * exists.\n   */\n  ALREADY_EXISTS: 'already-exists' as FirestoreErrorCode,\n\n  /**\n   * The caller does not have permission to execute the specified operation.\n   * PERMISSION_DENIED must not be used for rejections caused by exhausting\n   * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n   * PERMISSION_DENIED must not be used if the caller 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<R> {\n  (value: R | Promise<R>): void;\n}\n\nexport interface Rejecter {\n  (reason?: Error): void;\n}\n\nexport class Deferred<R = void> {\n  promise: Promise<R>;\n  // Assigned synchronously in constructor by Promise constructor callback.\n  resolve!: Resolver<R>;\n  reject!: Rejecter;\n\n  constructor() {\n    this.promise = new Promise((resolve: Resolver<R>, reject: Rejecter) => {\n      this.resolve = resolve;\n      this.reject = reject;\n    });\n  }\n}\n\n/**\n * Takes an array of values and a function from a value to a Promise. The function is run on each\n * value sequentially, waiting for the previous promise to resolve before starting the next one.\n * The returned promise resolves once the function has been run on all values.\n */\nexport function sequence<T>(\n  values: T[],\n  fn: (value: T) => Promise<void>\n): Promise<void> {\n  let p = Promise.resolve();\n  for (const value of values) {\n    p = p.then(() => fn(value));\n  }\n  return p;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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<User>;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n  | FirstPartyCredentialsSettings\n  | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';\nexport interface Token {\n  /** Type of token. */\n  type: TokenType;\n\n  /**\n   * The user with which the token is associated (used for persisting user\n   * state on disk, etc.).\n   * This will be null for Tokens of the type 'AppCheck'.\n   */\n  user?: User;\n\n  /** Header values to set for this token */\n  headers: Map<string, string>;\n}\n\nexport class OAuthToken implements Token {\n  type = 'OAuth' as TokenType;\n  headers = new Map();\n\n  constructor(value: string, public user: User) {\n    this.headers.set('Authorization', `Bearer ${value}`);\n  }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener<T> = (credential: T) => Promise<void>;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider<T> {\n  /**\n   * Starts the credentials provider and specifies a listener to be notified of\n   * credential changes (sign-in / sign-out, token changes). It is immediately\n   * called once with the initial user.\n   *\n   * The change listener is invoked on the provided AsyncQueue.\n   */\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<T>\n  ): void;\n\n  /** Requests a token for the current user. */\n  getToken(): Promise<Token | null>;\n\n  /**\n   * Marks the last retrieved token as invalid, making the next GetToken request\n   * force-refresh the token.\n   */\n  invalidateToken(): void;\n\n  shutdown(): void;\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */\nexport class EmptyAuthCredentialsProvider implements CredentialsProvider<User> {\n  getToken(): Promise<Token | null> {\n    return Promise.resolve<Token | null>(null);\n  }\n\n  invalidateToken(): void {}\n\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<User>\n  ): void {\n    // Fire with initial user.\n    asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));\n  }\n\n  shutdown(): void {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */\nexport class EmulatorAuthCredentialsProvider\n  implements CredentialsProvider<User>\n{\n  constructor(private token: Token) {}\n\n  /**\n   * Stores the listener registered with setChangeListener()\n   * This isn't actually necessary since the UID never changes, but we use this\n   * to verify the listen contract is adhered to in tests.\n   */\n  private changeListener: CredentialChangeListener<User> | null = null;\n\n  getToken(): Promise<Token | null> {\n    return Promise.resolve(this.token);\n  }\n\n  invalidateToken(): void {}\n\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<User>\n  ): void {\n    debugAssert(\n      !this.changeListener,\n      'Can only call setChangeListener() once.'\n    );\n    this.changeListener = changeListener;\n    // Fire with initial user.\n    asyncQueue.enqueueRetryable(() => changeListener(this.token.user!));\n  }\n\n  shutdown(): void {\n    this.changeListener = null;\n  }\n}\n\n/** Credential provider for the Lite SDK. */\nexport class LiteAuthCredentialsProvider implements CredentialsProvider<User> {\n  private auth: FirebaseAuthInternal | null = null;\n\n  constructor(authProvider: Provider<FirebaseAuthInternalName>) {\n    authProvider.onInit(auth => {\n      this.auth = auth;\n    });\n  }\n\n  getToken(): Promise<Token | null> {\n    if (!this.auth) {\n      return Promise.resolve(null);\n    }\n\n    return this.auth.getToken().then(tokenData => {\n      if (tokenData) {\n        hardAssert(\n          typeof tokenData.accessToken === 'string',\n          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<User>\n  ): void {}\n\n  shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n  implements CredentialsProvider<User>\n{\n  /**\n   * The auth token listener registered with FirebaseApp, retained here so we\n   * can unregister it.\n   */\n  private tokenListener: (() => void) | 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<FirebaseAuthInternalName>) {}\n\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<User>\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<void> = user => {\n      if (this.tokenCounter !== lastTokenId) {\n        lastTokenId = this.tokenCounter;\n        return changeListener(user);\n      } else {\n        return Promise.resolve();\n      }\n    };\n\n    // A promise that can be waited on to block on the next token change.\n    // This promise is re-created after each change.\n    let nextToken = new Deferred<void>();\n\n    this.tokenListener = () => {\n      this.tokenCounter++;\n      this.currentUser = this.getUser();\n      nextToken.resolve();\n      nextToken = new Deferred<void>();\n      asyncQueue.enqueueRetryable(() =>\n        guardedChangeListener(this.currentUser)\n      );\n    };\n\n    const awaitNextToken: () => void = () => {\n      const currentTokenAttempt = nextToken;\n      asyncQueue.enqueueRetryable(async () => {\n        await currentTokenAttempt.promise;\n        await guardedChangeListener(this.currentUser);\n      });\n    };\n\n    const registerAuth = (auth: FirebaseAuthInternal): void => {\n      logDebug('FirebaseAuthCredentialsProvider', 'Auth detected');\n      this.auth = auth;\n      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<void>();\n        }\n      }\n    }, 0);\n\n    awaitNextToken();\n  }\n\n  getToken(): Promise<Token | null> {\n    debugAssert(\n      this.tokenListener != null,\n      'FirebaseAuthCredentialsProvider not started.'\n    );\n\n    // Take note of the current value of the tokenCounter so that this method\n    // can fail (with an ABORTED error) if there is a token change while the\n    // request is outstanding.\n    const initialTokenCounter = this.tokenCounter;\n    const forceRefresh = this.forceRefresh;\n    this.forceRefresh = false;\n\n    if (!this.auth) {\n      return Promise.resolve(null);\n    }\n\n    return this.auth.getToken(forceRefresh).then(tokenData => {\n      // Cancel the request since the token changed while the request was\n      // outstanding so the response is potentially for a previous user (which\n      // user, we can't be sure).\n      if (this.tokenCounter !== initialTokenCounter) {\n        logDebug(\n          'FirebaseAuthCredentialsProvider',\n          'getToken aborted due to token change.'\n        );\n        return this.getToken();\n      } else {\n        if (tokenData) {\n          hardAssert(\n            typeof tokenData.accessToken === 'string',\n            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<string, string> {\n    this._headers.set('X-Goog-AuthUser', this.sessionIndex);\n    // Use array notation to prevent minification\n    const authHeaderTokenValue = this.getAuthToken();\n    if (authHeaderTokenValue) {\n      this._headers.set('Authorization', authHeaderTokenValue);\n    }\n    if (this.iamToken) {\n      this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);\n    }\n\n    return this._headers;\n  }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nexport class FirstPartyAuthCredentialsProvider\n  implements CredentialsProvider<User>\n{\n  constructor(\n    private sessionIndex: string,\n    private iamToken: string | null,\n    private authTokenFactory: AuthTokenFactory | null\n  ) {}\n\n  getToken(): Promise<Token | null> {\n    return Promise.resolve(\n      new FirstPartyToken(\n        this.sessionIndex,\n        this.iamToken,\n        this.authTokenFactory\n      )\n    );\n  }\n\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<User>\n  ): void {\n    // Fire with initial uid.\n    asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));\n  }\n\n  shutdown(): void {}\n\n  invalidateToken(): void {}\n}\n\nexport class AppCheckToken implements Token {\n  type = 'AppCheck' as TokenType;\n  headers = new Map();\n\n  constructor(private value: string) {\n    if (value && value.length > 0) {\n      this.headers.set('x-firebase-appcheck', this.value);\n    }\n  }\n}\n\nexport class FirebaseAppCheckTokenProvider\n  implements CredentialsProvider<string>\n{\n  /**\n   * The AppCheck token listener registered with FirebaseApp, retained here so\n   * we can unregister it.\n   */\n  private tokenListener: AppCheckTokenListener | 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<AppCheckInternalComponentName>\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<string>\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<void> = tokenResult => {\n      if (tokenResult.error != null) {\n        logDebug(\n          'FirebaseAppCheckTokenProvider',\n          `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`\n        );\n      }\n      const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;\n      this.latestAppCheckToken = tokenResult.token;\n      logDebug(\n        'FirebaseAppCheckTokenProvider',\n        `Received ${tokenUpdated ? 'new' : 'existing'} token.`\n      );\n      return tokenUpdated\n        ? changeListener(tokenResult.token)\n        : Promise.resolve();\n    };\n\n    this.tokenListener = (tokenResult: AppCheckTokenResult) => {\n      asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));\n    };\n\n    const registerAppCheck = (appCheck: FirebaseAppCheckInternal): void => {\n      logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected');\n      this.appCheck = appCheck;\n      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<Token | null> {\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<string> {\n  getToken(): Promise<Token | null> {\n    return Promise.resolve<Token | null>(new AppCheckToken(''));\n  }\n\n  invalidateToken(): void {}\n\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<string>\n  ): void {}\n\n  shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider<string> {\n  private appCheck: FirebaseAppCheckInternal | null = null;\n  private serverAppAppCheckToken: string | null = null;\n\n  constructor(\n    app: FirebaseApp,\n    private appCheckProvider: Provider<AppCheckInternalComponentName>\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<Token | null> {\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<string>\n  ): void {}\n\n  shutdown(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeAuthCredentialsProvider(\n  credentials?: CredentialsSettings\n): CredentialsProvider<User> {\n  if (!credentials) {\n    return new EmptyAuthCredentialsProvider();\n  }\n  switch (credentials['type']) {\n    case 'firstParty':\n      return new FirstPartyAuthCredentialsProvider(\n        credentials['sessionIndex'] || '0',\n        credentials['iamToken'] || null,\n        credentials['authTokenFactory'] || null\n      );\n\n    case 'provider':\n      return credentials['client'];\n\n    default:\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'makeAuthCredentialsProvider failed due to invalid credential type'\n      );\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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<E> = (value: E) => void;\nexport interface Indexable {\n  [k: string]: unknown;\n}\n\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */\nexport class AutoId {\n  static newId(): string {\n    // Alphanumeric characters\n    const chars =\n      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n    // The largest byte value that is a multiple of `char.length`.\n    const maxMultiple = Math.floor(256 / chars.length) * chars.length;\n    debugAssert(\n      0 < maxMultiple && maxMultiple < 256,\n      `Expect maxMultiple to be (0, 256), but got ${maxMultiple}`\n    );\n\n    let autoId = '';\n    const targetLength = 20;\n    while (autoId.length < targetLength) {\n      const bytes = randomBytes(40);\n      for (let i = 0; i < bytes.length; ++i) {\n        // Only accept values that are [0, maxMultiple), this ensures they can\n        // be evenly mapped to indices of `chars` via a modulo operation.\n        if (autoId.length < targetLength && bytes[i] < maxMultiple) {\n          autoId += chars.charAt(bytes[i] % chars.length);\n        }\n      }\n    }\n    debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);\n\n    return autoId;\n  }\n}\n\nexport function primitiveComparator<T>(left: T, right: T): number {\n  if (left < right) {\n    return -1;\n  }\n  if (left > right) {\n    return 1;\n  }\n  return 0;\n}\n\nexport interface Equatable<T> {\n  isEqual(other: T): boolean;\n}\n\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<V> {\n  forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals<T>(\n  left: T[],\n  right: T[],\n  comparator: (l: T, r: T) => boolean\n): boolean {\n  if (left.length !== right.length) {\n    return false;\n  }\n  return left.every((value, index) => comparator(value, right[index]));\n}\n\n/**\n * Verifies equality for an optional value.\n */\nexport function isOptionalEqual<T>(\n  left: T | undefined,\n  right: T | undefined,\n  equalityTest: (left: T, right: T) => boolean\n): boolean {\n  if (left === undefined && right === undefined) {\n    return true;\n  }\n\n  if (left === undefined || right === undefined) {\n    return false;\n  }\n\n  return equalityTest(left, right);\n}\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__';\nexport const UPDATE_TIME_NAME = '__update_time__';\nexport const CREATE_TIME_NAME = '__create_time__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath<B extends BasePath<B>> {\n  private segments: string[];\n  private offset: number;\n  private len: number;\n\n  constructor(segments: string[], offset?: number, length?: number) {\n    if (offset === undefined) {\n      offset = 0;\n    } else if (offset > segments.length) {\n      fail(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<T extends BasePath<T>>(\n    p1: BasePath<T>,\n    p2: BasePath<T>\n  ): number {\n    const len = Math.min(p1.length, p2.length);\n    for (let i = 0; i < len; i++) {\n      const 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<ResourcePath> {\n  protected construct(\n    segments: string[],\n    offset?: number,\n    length?: number\n  ): ResourcePath {\n    return new ResourcePath(segments, offset, length);\n  }\n\n  canonicalString(): string {\n    // NOTE: The client is ignorant of any path segments containing escape\n    // sequences (e.g. __id123__) and just passes them through raw (they exist\n    // for legacy reasons and should not be used frequently).\n\n    return this.toArray().join('/');\n  }\n\n  toString(): string {\n    return this.canonicalString();\n  }\n\n  toStringWithLeadingSlash(): 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<FieldPath> {\n  protected construct(\n    segments: string[],\n    offset?: number,\n    length?: number\n  ): FieldPath {\n    return new FieldPath(segments, offset, length);\n  }\n\n  /**\n   * Returns true if the string could be used as a segment in a field path\n   * without escaping.\n   */\n  private static isValidIdentifier(segment: string): boolean {\n    return identifierRegExp.test(segment);\n  }\n\n  canonicalString(): string {\n    return this.toArray()\n      .map(str => {\n        str = str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`');\n        if (!FieldPath.isValidIdentifier(str)) {\n          str = '`' + str + '`';\n        }\n        return str;\n      })\n      .join('.');\n  }\n\n  toString(): string {\n    return this.canonicalString();\n  }\n\n  /**\n   * Returns true if this field references the key of a document.\n   */\n  isKeyField(): boolean {\n    return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n  }\n\n  /**\n   * The field designating the key of a document.\n   */\n  static keyField(): FieldPath {\n    return new FieldPath([DOCUMENT_KEY_NAME]);\n  }\n\n  /**\n   * Parses a field string from the given server-formatted string.\n   *\n   * - Splitting the empty string is not allowed (for now at least).\n   * - Empty segments within the string (e.g. if there are two consecutive\n   *   separators) are not allowed.\n   *\n   * TODO(b/37244157): we should make this more strict. Right now, it allows\n   * non-identifier path components, even if they aren't escaped.\n   */\n  static fromServerFormat(path: string): FieldPath {\n    const segments: string[] = [];\n    let current = '';\n    let i = 0;\n\n    const addCurrentSegment = (): void => {\n      if (current.length === 0) {\n        throw new FirestoreError(\n          Code.INVALID_ARGUMENT,\n          `Invalid field path (${path}). Paths must not be empty, begin ` +\n            `with '.', end with '.', or contain '..'`\n        );\n      }\n      segments.push(current);\n      current = '';\n    };\n\n    let inBackticks = false;\n\n    while (i < path.length) {\n      const c = path[i];\n      if (c === '\\\\') {\n        if (i + 1 === path.length) {\n          throw new FirestoreError(\n            Code.INVALID_ARGUMENT,\n            'Path has trailing escape character: ' + path\n          );\n        }\n        const next = path[i + 1];\n        if (!(next === '\\\\' || next === '.' || next === '`')) {\n          throw new FirestoreError(\n            Code.INVALID_ARGUMENT,\n            'Path has invalid escape sequence: ' + path\n          );\n        }\n        current += next;\n        i += 2;\n      } else if (c === '`') {\n        inBackticks = !inBackticks;\n        i++;\n      } else if (c === '.' && !inBackticks) {\n        addCurrentSegment();\n        i++;\n      } else {\n        current += c;\n        i++;\n      }\n    }\n    addCurrentSegment();\n\n    if (inBackticks) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Unterminated ` in path: ' + path\n      );\n    }\n\n    return new FieldPath(segments);\n  }\n\n  static emptyPath(): FieldPath {\n    return new FieldPath([]);\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\n/**\n * @internal\n */\nexport class DocumentKey {\n  constructor(readonly path: ResourcePath) {\n    debugAssert(\n      DocumentKey.isDocumentKey(path),\n      'Invalid DocumentKey with an odd number of segments: ' +\n        path.toArray().join('/')\n    );\n  }\n\n  static fromPath(path: string): DocumentKey {\n    return new DocumentKey(ResourcePath.fromString(path));\n  }\n\n  static fromName(name: string): DocumentKey {\n    return new DocumentKey(ResourcePath.fromString(name).popFirst(5));\n  }\n\n  static empty(): DocumentKey {\n    return new DocumentKey(ResourcePath.emptyPath());\n  }\n\n  get collectionGroup(): string {\n    debugAssert(\n      !this.path.isEmpty(),\n      'Cannot get collection group for empty key'\n    );\n    return this.path.popLast().lastSegment();\n  }\n\n  /** Returns true if the document is in the specified collectionId. */\n  hasCollectionId(collectionId: string): boolean {\n    return (\n      this.path.length >= 2 &&\n      this.path.get(this.path.length - 2) === collectionId\n    );\n  }\n\n  /** Returns the collection group (i.e. the name of the parent collection) for this key. */\n  getCollectionGroup(): string {\n    debugAssert(\n      !this.path.isEmpty(),\n      'Cannot get collection group for empty key'\n    );\n    return this.path.get(this.path.length - 2);\n  }\n\n  /** Returns the fully qualified path to the parent collection. */\n  getCollectionPath(): ResourcePath {\n    return this.path.popLast();\n  }\n\n  isEqual(other: DocumentKey | null): boolean {\n    return (\n      other !== null && ResourcePath.comparator(this.path, other.path) === 0\n    );\n  }\n\n  toString(): string {\n    return this.path.toString();\n  }\n\n  static comparator(k1: DocumentKey, k2: DocumentKey): number {\n    return ResourcePath.comparator(k1.path, k2.path);\n  }\n\n  static isDocumentKey(path: ResourcePath): boolean {\n    return path.length % 2 === 0;\n  }\n\n  /**\n   * Creates and returns a new document key with the given segments.\n   *\n   * @param segments - The segments of the path to the document\n   * @returns A new instance of DocumentKey\n   */\n  static fromSegments(segments: string[]): DocumentKey {\n    return new DocumentKey(new ResourcePath(segments.slice()));\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 '../lite-api/reference';\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): input is DocumentData {\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<T>(\n  obj: object,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  constructor: { new (...args: any[]): T }\n): T | never {\n  if ('_delegate' in obj) {\n    // Unwrap Compat types\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    obj = (obj as any)._delegate;\n  }\n\n  if (!(obj instanceof constructor)) {\n    if (constructor.name === obj.constructor.name) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Type does not match the expected instance. Did you pass a ' +\n          `reference from a different Firestore SDK?`\n      );\n    } else {\n      const description = valueDescription(obj);\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        `Expected type '${constructor.name}', but it was: ${description}`\n      );\n    }\n  }\n  return obj as T;\n}\n\nexport function validatePositiveNumber(functionName: string, n: number): void {\n  if (n <= 0) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      `Function ${functionName}() requires a positive number, but it was: ${n}.`\n    );\n  }\n}\n","/**\n * @license\n * Copyright 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 JsonTypeDesc> = 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<T extends JsonTypeDesc> {\n  value?: TSType<T>;\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<JsonTypeDesc>;\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<T extends JsonSchema> = {\n  [K in keyof T]: Required<T[K]>['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property<T extends JsonTypeDesc>(\n  typeString: T,\n  optionalValue?: TSType<T>\n): Property<T> {\n  const result: Property<T> = {\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<S extends JsonSchema>(\n  json: object,\n  schema: S\n): json is Json<S> {\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 <seconds>.<nanoseconds> where\n    // <seconds> is translated to have a non-negative value and both <seconds>\n    // and <nanoseconds> are left-padded with zeroes to be a consistent length.\n    // Strings with this format then have a lexicographical ordering that matches\n    // the expected ordering. The <seconds> translation is done to avoid having\n    // a leading negative sign (i.e. a leading '-' character) in its string\n    // representation, which would affect its 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<LruResults>;\n\n  /** Manages the list of active field and collection indices. */\n  indexManager: IndexManager;\n\n  /**\n   * The \"local\" view of all documents (layering mutationQueue on top of\n   * remoteDocumentCache).\n   */\n  localDocuments: LocalDocumentsView;\n}\n\n/**\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\n * operation fails because the primary lease has been taken by another client,\n * we ignore the error (the persistence layer will immediately call\n * `applyPrimaryLease` to propagate the primary state change). All other errors\n * are re-thrown.\n *\n * @param err - An error returned by a LocalStore operation.\n * @returns A Promise that resolves after we recovered, or the original error.\n */\nexport async function ignoreIfPrimaryLeaseLoss(\n  err: FirestoreError\n): Promise<void> {\n  if (\n    err.code === Code.FAILED_PRECONDITION &&\n    err.message === PRIMARY_LEASE_LOST_ERROR_MSG\n  ) {\n    logDebug('LocalStore', 'Unexpectedly lost primary lease');\n  } else {\n    throw err;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\n\nexport type FulfilledHandler<T, R> =\n  | ((result: T) => R | PersistencePromise<R>)\n  | null;\nexport type RejectedHandler<R> =\n  | ((reason: Error) => R | PersistencePromise<R>)\n  | null;\nexport type Resolver<T> = (value?: T) => void;\nexport type Rejector = (error: Error) => void;\n\n/**\n * PersistencePromise is essentially a re-implementation of Promise except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */\nexport class PersistencePromise<T> {\n  // NOTE: next/catchCallback will always point to our own wrapper functions,\n  // not the user's raw next() or catch() callbacks.\n  private nextCallback: FulfilledHandler<T, unknown> = null;\n  private catchCallback: RejectedHandler<unknown> = null;\n\n  // When the operation resolves, we'll set result or error and mark isDone.\n  private result: T | undefined = undefined;\n  private error: Error | undefined = undefined;\n  private isDone = false;\n\n  // Set to true when .then() or .catch() are called and prevents additional\n  // chaining.\n  private callbackAttached = false;\n\n  constructor(callback: (resolve: Resolver<T>, reject: Rejector) => void) {\n    callback(\n      value => {\n        this.isDone = true;\n        this.result = value;\n        if (this.nextCallback) {\n          // value should be defined unless T is Void, but we can't express\n          // that in the type system.\n          this.nextCallback(value!);\n        }\n      },\n      error => {\n        this.isDone = true;\n        this.error = error;\n        if (this.catchCallback) {\n          this.catchCallback(error);\n        }\n      }\n    );\n  }\n\n  catch<R>(\n    fn: (error: Error) => R | PersistencePromise<R>\n  ): PersistencePromise<R> {\n    return this.next(undefined, fn);\n  }\n\n  next<R>(\n    nextFn?: FulfilledHandler<T, R>,\n    catchFn?: RejectedHandler<R>\n  ): PersistencePromise<R> {\n    if (this.callbackAttached) {\n      fail(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<R>((resolve, reject) => {\n        this.nextCallback = (value: T) => {\n          this.wrapSuccess(nextFn, value).next(resolve, reject);\n        };\n        this.catchCallback = (error: Error) => {\n          this.wrapFailure(catchFn, error).next(resolve, reject);\n        };\n      });\n    }\n  }\n\n  toPromise(): Promise<T> {\n    return new Promise((resolve, reject) => {\n      this.next(resolve, reject);\n    });\n  }\n\n  private wrapUserFunction<R>(\n    fn: () => R | PersistencePromise<R>\n  ): PersistencePromise<R> {\n    try {\n      const result = fn();\n      if (result instanceof PersistencePromise) {\n        return result;\n      } else {\n        return PersistencePromise.resolve(result);\n      }\n    } catch (e) {\n      return PersistencePromise.reject<R>(e as Error);\n    }\n  }\n\n  private wrapSuccess<R>(\n    nextFn: FulfilledHandler<T, R> | undefined,\n    value: T\n  ): PersistencePromise<R> {\n    if (nextFn) {\n      return this.wrapUserFunction(() => nextFn(value));\n    } else {\n      // If there's no nextFn, then R must be the same as T\n      return PersistencePromise.resolve<R>(value as unknown as R);\n    }\n  }\n\n  private wrapFailure<R>(\n    catchFn: RejectedHandler<R> | undefined,\n    error: Error\n  ): PersistencePromise<R> {\n    if (catchFn) {\n      return this.wrapUserFunction(() => catchFn(error));\n    } else {\n      return PersistencePromise.reject<R>(error);\n    }\n  }\n\n  static resolve(): PersistencePromise<void>;\n  static resolve<R>(result: R): PersistencePromise<R>;\n  static resolve<R>(result?: R): PersistencePromise<R | void> {\n    return new PersistencePromise<R | void>((resolve, reject) => {\n      resolve(result);\n    });\n  }\n\n  static reject<R>(error: Error): PersistencePromise<R> {\n    return new PersistencePromise<R>((resolve, reject) => {\n      reject(error);\n    });\n  }\n\n  static waitFor(\n    // Accept all Promise types in waitFor().\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    all: { forEach: (cb: (el: PersistencePromise<any>) => void) => void }\n  ): PersistencePromise<void> {\n    return new PersistencePromise<void>((resolve, reject) => {\n      let expectedCount = 0;\n      let resolvedCount = 0;\n      let done = false;\n\n      all.forEach(element => {\n        ++expectedCount;\n        element.next(\n          () => {\n            ++resolvedCount;\n            if (done && resolvedCount === expectedCount) {\n              resolve();\n            }\n          },\n          err => reject(err)\n        );\n      });\n\n      done = true;\n      if (resolvedCount === expectedCount) {\n        resolve();\n      }\n    });\n  }\n\n  /**\n   * Given an array of predicate functions that asynchronously evaluate to a\n   * boolean, implements a short-circuiting `or` between the results. Predicates\n   * will be evaluated until one of them returns `true`, then stop. The final\n   * result will be whether any of them returned `true`.\n   */\n  static or(\n    predicates: Array<() => PersistencePromise<boolean>>\n  ): PersistencePromise<boolean> {\n    let p: PersistencePromise<boolean> =\n      PersistencePromise.resolve<boolean>(false);\n    for (const predicate of predicates) {\n      p = p.next(isTrue => {\n        if (isTrue) {\n          return PersistencePromise.resolve<boolean>(isTrue);\n        } else {\n          return predicate();\n        }\n      });\n    }\n    return p;\n  }\n\n  /**\n   * Given an iterable, call the given function on each element in the\n   * collection and wait for all of the resulting concurrent PersistencePromises\n   * to resolve.\n   */\n  static forEach<R, S>(\n    collection: { forEach: (cb: (r: R, s: S) => void) => void },\n    f:\n      | ((r: R, s: S) => PersistencePromise<void>)\n      | ((r: R) => PersistencePromise<void>)\n  ): PersistencePromise<void>;\n  static forEach<R>(\n    collection: { forEach: (cb: (r: R) => void) => void },\n    f: (r: R) => PersistencePromise<void>\n  ): PersistencePromise<void>;\n  static forEach<R, S>(\n    collection: { forEach: (cb: (r: R, s?: S) => void) => void },\n    f: (r: R, s?: S) => PersistencePromise<void>\n  ): PersistencePromise<void> {\n    const promises: Array<PersistencePromise<void>> = [];\n    collection.forEach((r, s) => {\n      promises.push(f.call(this, r, s));\n    });\n    return this.waitFor(promises);\n  }\n\n  /**\n   * Concurrently map all array elements through asynchronous function.\n   */\n  static mapArray<T, U>(\n    array: T[],\n    f: (t: T) => PersistencePromise<U>\n  ): PersistencePromise<U[]> {\n    return new PersistencePromise<U[]>((resolve, reject) => {\n      const expectedCount = array.length;\n      const results: U[] = new Array(expectedCount);\n      let resolvedCount = 0;\n      for (let i = 0; i < expectedCount; i++) {\n        const current = i;\n        f(array[current]).next(\n          result => {\n            results[current] = result;\n            ++resolvedCount;\n            if (resolvedCount === expectedCount) {\n              resolve(results);\n            }\n          },\n          err => reject(err)\n        );\n      }\n    });\n  }\n\n  /**\n   * An alternative to recursive PersistencePromise calls, that avoids\n   * potential memory problems from unbounded chains of promises.\n   *\n   * The `action` will be called repeatedly while `condition` is true.\n   */\n  static doWhile(\n    condition: () => boolean,\n    action: () => PersistencePromise<void>\n  ): PersistencePromise<void> {\n    return new PersistencePromise<void>((resolve, reject) => {\n      const process = (): void => {\n        if (condition() === true) {\n          action().next(() => {\n            process();\n          }, reject);\n        } else {\n          resolve();\n        }\n      };\n      process();\n    });\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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<void>;\n}\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nexport class SimpleDbTransaction {\n  private aborted = false;\n\n  /**\n   * A `Promise` that resolves with the result of the IndexedDb transaction.\n   */\n  private readonly completionDeferred = new Deferred<void>();\n\n  static open(\n    db: IDBDatabase,\n    action: string,\n    mode: IDBTransactionMode,\n    objectStoreNames: string[]\n  ): SimpleDbTransaction {\n    try {\n      return new SimpleDbTransaction(\n        action,\n        db.transaction(objectStoreNames, mode)\n      );\n    } catch (e) {\n      throw new IndexedDbTransactionError(action, e as Error);\n    }\n  }\n\n  constructor(\n    private readonly action: string,\n    private readonly transaction: IDBTransaction\n  ) {\n    this.transaction.oncomplete = () => {\n      this.completionDeferred.resolve();\n    };\n    this.transaction.onabort = () => {\n      if (transaction.error) {\n        this.completionDeferred.reject(\n          new IndexedDbTransactionError(action, transaction.error)\n        );\n      } else {\n        this.completionDeferred.resolve();\n      }\n    };\n    this.transaction.onerror = (event: Event) => {\n      const error = checkForAndReportiOSError(\n        (event.target as IDBRequest).error!\n      );\n      this.completionDeferred.reject(\n        new IndexedDbTransactionError(action, error)\n      );\n    };\n  }\n\n  get completionPromise(): Promise<void> {\n    return this.completionDeferred.promise;\n  }\n\n  abort(error?: Error): void {\n    if (error) {\n      this.completionDeferred.reject(error);\n    }\n\n    if (!this.aborted) {\n      logDebug(\n        LOG_TAG,\n        'Aborting transaction:',\n        error ? error.message : 'Client-initiated abort'\n      );\n      this.aborted = true;\n      this.transaction.abort();\n    }\n  }\n\n  maybeCommit(): void {\n    // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n    // speed up index DB processing if the event loop remains blocks.\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    const maybeV3IndexedDb = this.transaction as any;\n    if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') {\n      maybeV3IndexedDb.commit();\n    }\n  }\n\n  /**\n   * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All\n   * operations performed on the SimpleDbStore happen within the context of this\n   * transaction and it cannot be used anymore once the transaction is\n   * completed.\n   *\n   * Note that we can't actually enforce that the KeyType and ValueType are\n   * correct, but they allow type safety through the rest of the consuming code.\n   */\n  store<KeyType extends IDBValidKey, ValueType extends unknown>(\n    storeName: string\n  ): SimpleDbStore<KeyType, ValueType> {\n    const store = this.transaction.objectStore(storeName);\n    debugAssert(!!store, 'Object store not part of transaction: ' + storeName);\n    return new SimpleDbStore<KeyType, ValueType>(store);\n  }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nexport class SimpleDb {\n  private db?: IDBDatabase;\n  private lastClosedDbVersion: number | null = null;\n  private versionchangelistener?: (event: IDBVersionChangeEvent) => void;\n\n  /** Deletes the specified database. */\n  static delete(name: string): Promise<void> {\n    logDebug(LOG_TAG, 'Removing database:', name);\n    const globals = getGlobal();\n    return wrapRequest<void>(\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<KeyType extends IDBValidKey, ValueType extends unknown>(\n    txn: SimpleDbTransaction,\n    store: string\n  ): SimpleDbStore<KeyType, ValueType> {\n    return txn.store<KeyType, ValueType>(store);\n  }\n\n  // visible for testing\n  /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n  static getIOSVersion(ua: string): number {\n    const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\n    const version = iOSVersionRegex\n      ? iOSVersionRegex[1].split('_').slice(0, 2).join('.')\n      : '-1';\n    return Number(version);\n  }\n\n  /*\n   * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n   *\n   * Note that `version` must not be a downgrade. IndexedDB does not support\n   * downgrading the schema version. We currently do not support any way to do\n   * versioning outside of IndexedDB's versioning mechanism, as only\n   * version-upgrade transactions are allowed to do things like create\n   * objectstores.\n   */\n  constructor(\n    private readonly name: string,\n    private readonly version: number,\n    private readonly schemaConverter: SimpleDbSchemaConverter\n  ) {\n    debugAssert(\n      SimpleDb.isAvailable(),\n      'IndexedDB not supported in current environment.'\n    );\n\n    const iOSVersion = SimpleDb.getIOSVersion(getUA());\n    // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n    // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n    // whatever reason it's much harder to hit after 12.2 so we only proactively\n    // log on 12.2.\n    if (iOSVersion === 12.2) {\n      logError(\n        'Firestore persistence suffers from a bug in iOS 12.2 ' +\n          'Safari that may cause your app to stop working. See ' +\n          'https://stackoverflow.com/q/56496296/110915 for details ' +\n          'and a potential workaround.'\n      );\n    }\n  }\n\n  /**\n   * Opens the specified database, creating or upgrading it if necessary.\n   */\n  async ensureDb(action: string): Promise<IDBDatabase> {\n    if (!this.db) {\n      logDebug(LOG_TAG, 'Opening database:', this.name);\n      this.db = await new Promise<IDBDatabase>((resolve, reject) => {\n        // TODO(mikelehen): Investigate browser compatibility.\n        // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n        // suggests IE9 and older WebKit browsers handle upgrade\n        // differently. They expect setVersion, as described here:\n        // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n        const request = indexedDB.open(this.name, this.version);\n\n        request.onsuccess = (event: Event) => {\n          const db = (event.target as IDBOpenDBRequest).result;\n          resolve(db);\n        };\n\n        request.onblocked = () => {\n          reject(\n            new IndexedDbTransactionError(\n              action,\n              'Cannot upgrade IndexedDB schema while another tab is open. ' +\n                'Close all tabs that access Firestore and reload this page to proceed.'\n            )\n          );\n        };\n\n        request.onerror = (event: Event) => {\n          const error: DOMException = (event.target as IDBOpenDBRequest).error!;\n          if (error.name === 'VersionError') {\n            reject(\n              new FirestoreError(\n                Code.FAILED_PRECONDITION,\n                'A newer version of the Firestore SDK was previously used and so the persisted ' +\n                  'data is not compatible with the version of the SDK you are now using. The SDK ' +\n                  'will operate with persistence disabled. If you need persistence, please ' +\n                  're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\n                  'data for your app to start fresh.'\n              )\n            );\n          } else if (error.name === 'InvalidStateError') {\n            reject(\n              new FirestoreError(\n                Code.FAILED_PRECONDITION,\n                'Unable to open an IndexedDB connection. This could be due to running in a ' +\n                  'private browsing session on a browser whose private browsing sessions do not ' +\n                  'support IndexedDB: ' +\n                  error\n              )\n            );\n          } else {\n            reject(new IndexedDbTransactionError(action, error));\n          }\n        };\n\n        request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n          logDebug(\n            LOG_TAG,\n            'Database \"' + this.name + '\" requires upgrade from version:',\n            event.oldVersion\n          );\n          const db = (event.target as IDBOpenDBRequest).result;\n          this.schemaConverter\n            .createOrUpgrade(\n              db,\n              request.transaction!,\n              event.oldVersion,\n              this.version\n            )\n            .next(() => {\n              logDebug(\n                LOG_TAG,\n                'Database upgrade to version ' + this.version + ' complete'\n              );\n            });\n        };\n      });\n    }\n\n    if (this.versionchangelistener) {\n      this.db.onversionchange = event => this.versionchangelistener!(event);\n    }\n\n    return this.db;\n  }\n\n  setVersionChangeListener(\n    versionChangeListener: (event: IDBVersionChangeEvent) => void\n  ): void {\n    this.versionchangelistener = versionChangeListener;\n    if (this.db) {\n      this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n        return versionChangeListener(event);\n      };\n    }\n  }\n\n  async runTransaction<T>(\n    action: string,\n    mode: SimpleDbTransactionMode,\n    objectStores: string[],\n    transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise<T>\n  ): Promise<T> {\n    const readonly = mode === 'readonly';\n    let attemptNumber = 0;\n\n    while (true) {\n      ++attemptNumber;\n\n      try {\n        this.db = await this.ensureDb(action);\n\n        const transaction = SimpleDbTransaction.open(\n          this.db,\n          action,\n          readonly ? 'readonly' : 'readwrite',\n          objectStores\n        );\n        const transactionFnResult = transactionFn(transaction)\n          .next(result => {\n            transaction.maybeCommit();\n            return result;\n          })\n          .catch(error => {\n            // Abort the transaction if there was an error.\n            transaction.abort(error);\n            // We cannot actually recover, and calling `abort()` will cause the transaction's\n            // completion promise to be rejected. This in turn means that we won't use\n            // `transactionFnResult` below. We return a rejection here so that we don't add the\n            // possibility of returning `void` to the type of `transactionFnResult`.\n            return PersistencePromise.reject<T>(error);\n          })\n          .toPromise();\n\n        // As noted above, errors are propagated by aborting the transaction. So\n        // we swallow any error here to avoid the browser logging it as unhandled.\n        transactionFnResult.catch(() => {});\n\n        // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n        // fire), but still return the original transactionFnResult back to the\n        // caller.\n        await transaction.completionPromise;\n        return transactionFnResult;\n      } catch (e) {\n        const error = e as Error;\n        // TODO(schmidt-sebastian): We could probably be smarter about this and\n        // not retry exceptions that are likely unrecoverable (such as quota\n        // exceeded errors).\n\n        // Note: We cannot use an instanceof check for FirestoreException, since the\n        // exception is wrapped in a generic error by our async/await handling.\n        const retryable =\n          error.name !== 'FirebaseError' &&\n          attemptNumber < TRANSACTION_RETRY_COUNT;\n        logDebug(\n          LOG_TAG,\n          'Transaction failed with error:',\n          error.message,\n          'Retrying:',\n          retryable\n        );\n\n        this.close();\n\n        if (!retryable) {\n          return Promise.reject(error);\n        }\n      }\n    }\n  }\n\n  close(): void {\n    if (this.db) {\n      this.db.close();\n    }\n    this.db = undefined;\n  }\n}\n\n/** 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<void> {\n    return wrapRequest<void>(this.dbCursor.delete());\n  }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback<KeyType, ValueType> = (\n  key: KeyType,\n  value: ValueType,\n  control: IterationController\n) => void | PersistencePromise<void>;\n\n/** Options available to the iterate() method. */\nexport interface IterateOptions {\n  /** Index to iterate over (else primary keys will be iterated) */\n  index?: string;\n\n  /** 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<void>;\n  put(key: KeyType, value: ValueType): PersistencePromise<void>;\n  put(\n    keyOrValue: KeyType | ValueType,\n    value?: ValueType\n  ): PersistencePromise<void> {\n    let request;\n    if (value !== undefined) {\n      logDebug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n      request = this.store.put(value, keyOrValue as KeyType);\n    } else {\n      logDebug(LOG_TAG, 'PUT', this.store.name, '<auto-key>', keyOrValue);\n      request = this.store.put(keyOrValue as ValueType);\n    }\n    return wrapRequest<void>(request);\n  }\n\n  /**\n   * Adds a new value into an Object Store and returns the new key. Similar to\n   * IndexedDb's `add()`, this method will fail on primary key collisions.\n   *\n   * @param value - The object to write.\n   * @returns The key of the value to add.\n   */\n  add(value: ValueType): PersistencePromise<KeyType> {\n    logDebug(LOG_TAG, 'ADD', this.store.name, value, value);\n    const request = this.store.add(value as ValueType);\n    return wrapRequest<KeyType>(request);\n  }\n\n  /**\n   * Gets the object with the specified key from the specified store, or null\n   * if no object exists with the specified key.\n   *\n   * @key The key of the object to get.\n   * @returns The object with the specified key or null if no object exists.\n   */\n  get(key: KeyType): PersistencePromise<ValueType | null> {\n    const request = this.store.get(key);\n    // We're doing an unsafe cast to ValueType.\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    return wrapRequest<any>(request).next(result => {\n      // Normalize nonexistence to null.\n      if (result === undefined) {\n        result = null;\n      }\n      logDebug(LOG_TAG, 'GET', this.store.name, key, result);\n      return result;\n    });\n  }\n\n  delete(key: KeyType | IDBKeyRange): PersistencePromise<void> {\n    logDebug(LOG_TAG, 'DELETE', this.store.name, key);\n    const request = this.store.delete(key);\n    return wrapRequest<void>(request);\n  }\n\n  /**\n   * If we ever need more of the count variants, we can add overloads. For now,\n   * all we need is to count everything in a store.\n   *\n   * Returns the number of rows in the store.\n   */\n  count(): PersistencePromise<number> {\n    logDebug(LOG_TAG, 'COUNT', this.store.name);\n    const request = this.store.count();\n    return wrapRequest<number>(request);\n  }\n\n  /** Loads all elements from the object store. */\n  loadAll(): PersistencePromise<ValueType[]>;\n  /** Loads all elements for the index range from the object store. */\n  loadAll(range: IDBKeyRange): PersistencePromise<ValueType[]>;\n  /** Loads all elements ordered by the given index. */\n  loadAll(index: string): PersistencePromise<ValueType[]>;\n  /**\n   * Loads all elements from the object store that fall into the provided in the\n   * index range for the given index.\n   */\n  loadAll(index: string, range: IDBKeyRange): PersistencePromise<ValueType[]>;\n  loadAll(\n    indexOrRange?: string | IDBKeyRange,\n    range?: IDBKeyRange\n  ): PersistencePromise<ValueType[]> {\n    const iterateOptions = this.options(indexOrRange, range);\n    // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n    // 20% faster.\n    const store = iterateOptions.index\n      ? this.store.index(iterateOptions.index)\n      : this.store;\n    if (typeof store.getAll === 'function') {\n      const request = store.getAll(iterateOptions.range);\n      return new PersistencePromise((resolve, reject) => {\n        request.onerror = (event: Event) => {\n          reject((event.target as IDBRequest).error!);\n        };\n        request.onsuccess = (event: Event) => {\n          resolve((event.target as IDBRequest).result);\n        };\n      });\n    } else {\n      const cursor = this.cursor(iterateOptions);\n      const results: ValueType[] = [];\n      return this.iterateCursor(cursor, (key, value) => {\n        results.push(value);\n      }).next(() => {\n        return results;\n      });\n    }\n  }\n\n  /**\n   * Loads the first `count` elements from the provided index range. Loads all\n   * elements if no limit is provided.\n   */\n  loadFirst(\n    range: IDBKeyRange,\n    count: number | null\n  ): PersistencePromise<ValueType[]> {\n    const request = this.store.getAll(\n      range,\n      count === null ? undefined : count\n    );\n    return new PersistencePromise((resolve, reject) => {\n      request.onerror = (event: Event) => {\n        reject((event.target as IDBRequest).error!);\n      };\n      request.onsuccess = (event: Event) => {\n        resolve((event.target as IDBRequest).result);\n      };\n    });\n  }\n\n  deleteAll(): PersistencePromise<void>;\n  deleteAll(range: IDBKeyRange): PersistencePromise<void>;\n  deleteAll(index: string, range: IDBKeyRange): PersistencePromise<void>;\n  deleteAll(\n    indexOrRange?: string | IDBKeyRange,\n    range?: IDBKeyRange\n  ): PersistencePromise<void> {\n    logDebug(LOG_TAG, 'DELETE ALL', this.store.name);\n    const options = this.options(indexOrRange, range);\n    options.keysOnly = false;\n    const cursor = this.cursor(options);\n    return this.iterateCursor(cursor, (key, value, control) => {\n      // NOTE: Calling delete() on a cursor is documented as more efficient than\n      // calling delete() on an object store with a single key\n      // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n      // however, this requires us *not* to use a keysOnly cursor\n      // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n      // may want to compare the performance of each method.\n      return control.delete();\n    });\n  }\n\n  /**\n   * Iterates over keys and values in an object store.\n   *\n   * @param options - Options specifying how to iterate the objects in the\n   * store.\n   * @param callback - will be called for each iterated object. Iteration can be\n   * canceled at any point by calling the doneFn passed to the callback.\n   * The callback can return a PersistencePromise if it performs async\n   * operations but note that iteration will continue without waiting for them\n   * to complete.\n   * @returns A PersistencePromise that resolves once all PersistencePromises\n   * returned by callbacks resolve.\n   */\n  iterate(\n    callback: IterateCallback<KeyType, ValueType>\n  ): PersistencePromise<void>;\n  iterate(\n    options: IterateOptions,\n    callback: IterateCallback<KeyType, ValueType>\n  ): PersistencePromise<void>;\n  iterate(\n    optionsOrCallback: IterateOptions | IterateCallback<KeyType, ValueType>,\n    callback?: IterateCallback<KeyType, ValueType>\n  ): PersistencePromise<void> {\n    let options;\n    if (!callback) {\n      options = {};\n      callback = optionsOrCallback as IterateCallback<KeyType, ValueType>;\n    } else {\n      options = optionsOrCallback as IterateOptions;\n    }\n    const cursor = this.cursor(options);\n    return this.iterateCursor(cursor, callback);\n  }\n\n  /**\n   * Iterates over a store, but waits for the given callback to complete for\n   * each entry before iterating the next entry. This allows the callback to do\n   * asynchronous work to determine if this iteration should continue.\n   *\n   * The provided callback should return `true` to continue iteration, and\n   * `false` otherwise.\n   */\n  iterateSerial(\n    callback: (k: KeyType, v: ValueType) => PersistencePromise<boolean>\n  ): PersistencePromise<void> {\n    const cursorRequest = this.cursor({});\n    return new PersistencePromise((resolve, reject) => {\n      cursorRequest.onerror = (event: Event) => {\n        const error = checkForAndReportiOSError(\n          (event.target as IDBRequest).error!\n        );\n        reject(error);\n      };\n      cursorRequest.onsuccess = (event: Event) => {\n        const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n        if (!cursor) {\n          resolve();\n          return;\n        }\n\n        callback(cursor.primaryKey as KeyType, cursor.value).next(\n          shouldContinue => {\n            if (shouldContinue) {\n              cursor.continue();\n            } else {\n              resolve();\n            }\n          }\n        );\n      };\n    });\n  }\n\n  private iterateCursor(\n    cursorRequest: IDBRequest,\n    fn: IterateCallback<KeyType, ValueType>\n  ): PersistencePromise<void> {\n    const results: Array<PersistencePromise<void>> = [];\n    return new PersistencePromise((resolve, reject) => {\n      cursorRequest.onerror = (event: Event) => {\n        reject((event.target as IDBRequest).error!);\n      };\n      cursorRequest.onsuccess = (event: Event) => {\n        const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n        if (!cursor) {\n          resolve();\n          return;\n        }\n        const controller = new IterationController(cursor);\n        const userResult = fn(\n          cursor.primaryKey as KeyType,\n          cursor.value,\n          controller\n        );\n        if (userResult instanceof PersistencePromise) {\n          const userPromise: PersistencePromise<void> = userResult.catch(\n            err => {\n              controller.done();\n              return PersistencePromise.reject(err);\n            }\n          );\n          results.push(userPromise);\n        }\n        if (controller.isDone) {\n          resolve();\n        } else if (controller.skipToKey === null) {\n          cursor.continue();\n        } else {\n          cursor.continue(controller.skipToKey);\n        }\n      };\n    }).next(() => PersistencePromise.waitFor(results));\n  }\n\n  private options(\n    indexOrRange?: string | IDBKeyRange,\n    range?: IDBKeyRange\n  ): IterateOptions {\n    let indexName: string | undefined = undefined;\n    if (indexOrRange !== undefined) {\n      if (typeof indexOrRange === 'string') {\n        indexName = indexOrRange;\n      } else {\n        debugAssert(\n          range === undefined,\n          '3rd argument must not be defined if 2nd is a range.'\n        );\n        range = indexOrRange;\n      }\n    }\n    return { index: indexName, range };\n  }\n\n  private cursor(options: IterateOptions): IDBRequest {\n    let direction: IDBCursorDirection = 'next';\n    if (options.reverse) {\n      direction = 'prev';\n    }\n    if (options.index) {\n      const index = this.store.index(options.index);\n      if (options.keysOnly) {\n        return index.openKeyCursor(options.range, direction);\n      } else {\n        return index.openCursor(options.range, direction);\n      }\n    } else {\n      return this.store.openCursor(options.range, direction);\n    }\n  }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest<R>(request: IDBRequest): PersistencePromise<R> {\n  return new PersistencePromise<R>((resolve, reject) => {\n    request.onsuccess = (event: Event) => {\n      const result = (event.target as IDBRequest).result;\n      resolve(result);\n    };\n\n    request.onerror = (event: Event) => {\n      const error = checkForAndReportiOSError(\n        (event.target as IDBRequest).error!\n      );\n      reject(error);\n    };\n  });\n}\n\n// Guard so we only report the error once.\nlet reportedIOSError = false;\nfunction checkForAndReportiOSError(error: DOMException): Error {\n  const iOSVersion = SimpleDb.getIOSVersion(getUA());\n  if (iOSVersion >= 12.2 && iOSVersion < 13) {\n    const IOS_ERROR =\n      'An internal error was encountered in the Indexed Database server';\n    if (error.message.indexOf(IOS_ERROR) >= 0) {\n      // Wrap error in a more descriptive one.\n      const newError = new FirestoreError(\n        'internal',\n        `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` +\n          `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` +\n          `for details and a potential workaround.`\n      );\n      if (!reportedIOSError) {\n        reportedIOSError = true;\n        // Throw a global exception outside of this promise chain, for the user to\n        // potentially catch.\n        setTimeout(() => {\n          throw newError;\n        }, 0);\n      }\n      return newError;\n    }\n  }\n  return error;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FirestoreError } from '../api';\nimport { DocumentMap } from '../model/collections';\nimport {\n  IndexOffset,\n  indexOffsetComparator,\n  newIndexOffsetFromDocument\n} from '../model/field_index';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport { LocalWriteResult } from './local_store_impl';\nimport { Persistence, Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'IndexBackfiller';\n\n/** How long we wait to try running index backfill after SDK initialization. */\nconst INITIAL_BACKFILL_DELAY_MS = 15 * 1000;\n\n/** Minimum amount of time between backfill checks, after the first one. */\nconst REGULAR_BACKFILL_DELAY_MS = 60 * 1000;\n\n/** The maximum number of documents to process each time backfill() is called. */\nconst MAX_DOCUMENTS_TO_PROCESS = 50;\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nexport class IndexBackfillerScheduler implements Scheduler {\n  private task: DelayedOperation<void> | null;\n\n  constructor(\n    private readonly asyncQueue: AsyncQueue,\n    private readonly backfiller: IndexBackfiller\n  ) {\n    this.task = null;\n  }\n\n  start(): void {\n    debugAssert(\n      this.task === null,\n      'Cannot start an already started IndexBackfillerScheduler'\n    );\n    this.schedule(INITIAL_BACKFILL_DELAY_MS);\n  }\n\n  stop(): void {\n    if (this.task) {\n      this.task.cancel();\n      this.task = null;\n    }\n  }\n\n  get started(): boolean {\n    return this.task !== null;\n  }\n\n  private schedule(delay: number): void {\n    debugAssert(\n      this.task === null,\n      'Cannot schedule IndexBackfiller while a task is pending'\n    );\n    logDebug(LOG_TAG, `Scheduled in ${delay}ms`);\n    this.task = this.asyncQueue.enqueueAfterDelay(\n      TimerId.IndexBackfill,\n      delay,\n      async () => {\n        this.task = null;\n        try {\n          const documentsProcessed = await this.backfiller.backfill();\n          logDebug(LOG_TAG, `Documents written: ${documentsProcessed}`);\n        } catch (e) {\n          if (isIndexedDbTransactionError(e as Error)) {\n            logDebug(\n              LOG_TAG,\n              'Ignoring IndexedDB error during index backfill: ',\n              e\n            );\n          } else {\n            await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n          }\n        }\n        await this.schedule(REGULAR_BACKFILL_DELAY_MS);\n      }\n    );\n  }\n}\n\n/** Implements the steps for backfilling indexes. */\nexport class IndexBackfiller {\n  constructor(\n    /**\n     * LocalStore provides access to IndexManager and LocalDocumentView.\n     * These properties will update when the user changes. Consequently,\n     * making a local copy of IndexManager and LocalDocumentView will require\n     * updates over time. The simpler solution is to rely on LocalStore to have\n     * an up-to-date references to IndexManager and LocalDocumentStore.\n     */\n    private readonly localStore: LocalStore,\n    private readonly persistence: Persistence\n  ) {}\n\n  async backfill(\n    maxDocumentsToProcess: number = MAX_DOCUMENTS_TO_PROCESS\n  ): Promise<number> {\n    return this.persistence.runTransaction(\n      'Backfill Indexes',\n      'readwrite-primary',\n      txn => this.writeIndexEntries(txn, maxDocumentsToProcess)\n    );\n  }\n\n  /** Writes index entries until the cap is reached. Returns the number of documents processed. */\n  private writeIndexEntries(\n    transaction: PersistenceTransaction,\n    maxDocumentsToProcess: number\n  ): PersistencePromise<number> {\n    const processedCollectionGroups = new Set<string>();\n    let documentsRemaining = maxDocumentsToProcess;\n    let continueLoop = true;\n    return PersistencePromise.doWhile(\n      () => continueLoop === true && documentsRemaining > 0,\n      () => {\n        return this.localStore.indexManager\n          .getNextCollectionGroupToUpdate(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<number> {\n    // Use the earliest offset of all field indexes to query the local cache.\n    return this.localStore.indexManager\n      .getMinOffsetFromCollectionGroup(transaction, collectionGroup)\n      .next(existingOffset =>\n        this.localStore.localDocuments\n          .getNextDocuments(\n            transaction,\n            collectionGroup,\n            existingOffset,\n            documentsRemainingUnderCap\n          )\n          .next(nextBatch => {\n            const docs: DocumentMap = nextBatch.changes;\n            return this.localStore.indexManager\n              .updateIndexEntries(transaction, docs)\n              .next(() => this.getNewOffset(existingOffset, nextBatch))\n              .next(newOffset => {\n                logDebug(LOG_TAG, `Updating offset: ${newOffset}`);\n                return this.localStore.indexManager.updateCollectionGroup(\n                  transaction,\n                  collectionGroup,\n                  newOffset\n                );\n              })\n              .next(() => docs.size);\n          })\n      );\n  }\n\n  /** Returns the next offset based on the provided documents. */\n  private getNewOffset(\n    existingOffset: IndexOffset,\n    lookupResult: LocalWriteResult\n  ): IndexOffset {\n    let maxOffset: IndexOffset = existingOffset;\n    lookupResult.changes.forEach((key, document) => {\n      const newOffset: IndexOffset = newIndexOffsetFromDocument(document);\n      if (indexOffsetComparator(newOffset, maxOffset) > 0) {\n        maxOffset = newOffset;\n      }\n    });\n    return new IndexOffset(\n      maxOffset.readTime,\n      maxOffset.documentKey,\n      Math.max(lookupResult.batchId, existingOffset.largestBatchId)\n    );\n  }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber } from './types';\n\n/**\n * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a\n * `ListenSequence` in sync.\n */\nexport interface SequenceNumberSyncer {\n  // Notify the syncer that a new sequence number has been used.\n  writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n  // Setting this property allows the syncer to notify when a sequence number has been used, and\n  // and lets the ListenSequence adjust its internal previous value accordingly.\n  sequenceNumberHandler:\n    | ((sequenceNumber: ListenSequenceNumber) => void)\n    | null;\n}\n\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */\nexport class ListenSequence {\n  static readonly INVALID: ListenSequenceNumber = -1;\n\n  private writeNewSequenceNumber?: (\n    newSequenceNumber: ListenSequenceNumber\n  ) => void;\n\n  constructor(\n    private previousValue: ListenSequenceNumber,\n    sequenceNumberSyncer?: SequenceNumberSyncer\n  ) {\n    if (sequenceNumberSyncer) {\n      sequenceNumberSyncer.sequenceNumberHandler = sequenceNumber =>\n        this.setPreviousValue(sequenceNumber);\n      this.writeNewSequenceNumber = sequenceNumber =>\n        sequenceNumberSyncer.writeSequenceNumber(sequenceNumber);\n    }\n  }\n\n  private setPreviousValue(\n    externalPreviousValue: ListenSequenceNumber\n  ): ListenSequenceNumber {\n    this.previousValue = Math.max(externalPreviousValue, this.previousValue);\n    return this.previousValue;\n  }\n\n  next(): ListenSequenceNumber {\n    const nextValue = ++this.previousValue;\n    if (this.writeNewSequenceNumber) {\n      this.writeNewSequenceNumber(nextValue);\n    }\n    return nextValue;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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<Key extends IDBValidKey, Value>(\n  txn: PersistenceTransaction,\n  store: string\n): SimpleDbStore<Key, Value> {\n  const indexedDbTransaction = debugCast(txn, IndexedDbTransaction);\n  return SimpleDb.getStore<Key, Value>(\n    indexedDbTransaction.simpleDbTransaction,\n    store\n  );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from './assert';\n\n/*\n * Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n *   http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\nexport type Comparator<K> = (key1: K, key2: K) => number;\n\nexport interface Entry<K, V> {\n  key: K;\n  value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap<K, V> {\n  // visible for testing\n  root: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n\n  constructor(\n    public comparator: Comparator<K>,\n    root?: LLRBNode<K, V> | LLRBEmptyNode<K, V>\n  ) {\n    this.root = root ? root : LLRBNode.EMPTY;\n  }\n\n  // Returns a copy of the map, with the specified key/value added or replaced.\n  insert(key: K, value: V): SortedMap<K, V> {\n    return new SortedMap<K, V>(\n      this.comparator,\n      this.root\n        .insert(key, value, this.comparator)\n        .copy(null, null, LLRBNode.BLACK, null, null)\n    );\n  }\n\n  // Returns a copy of the map, with the specified key removed.\n  remove(key: K): SortedMap<K, V> {\n    return new SortedMap<K, V>(\n      this.comparator,\n      this.root\n        .remove(key, this.comparator)\n        .copy(null, null, LLRBNode.BLACK, null, null)\n    );\n  }\n\n  // Returns the value of the node with the given key, or null.\n  get(key: K): V | null {\n    let node = this.root;\n    while (!node.isEmpty()) {\n      const cmp = this.comparator(key, node.key);\n      if (cmp === 0) {\n        return node.value;\n      } else if (cmp < 0) {\n        node = node.left;\n      } else if (cmp > 0) {\n        node = node.right;\n      }\n    }\n    return null;\n  }\n\n  // Returns the index of the element in this sorted map, or -1 if it doesn't\n  // exist.\n  indexOf(key: K): number {\n    // Number of nodes that were pruned when descending right\n    let prunedNodes = 0;\n    let node = this.root;\n    while (!node.isEmpty()) {\n      const cmp = this.comparator(key, node.key);\n      if (cmp === 0) {\n        return prunedNodes + node.left.size;\n      } else if (cmp < 0) {\n        node = node.left;\n      } else {\n        // Count all nodes left of the node plus the node itself\n        prunedNodes += node.left.size + 1;\n        node = node.right;\n      }\n    }\n    // Node not found\n    return -1;\n  }\n\n  isEmpty(): boolean {\n    return this.root.isEmpty();\n  }\n\n  // Returns the total number of nodes in the map.\n  get size(): number {\n    return this.root.size;\n  }\n\n  // Returns the minimum key in the map.\n  minKey(): K | null {\n    return this.root.minKey();\n  }\n\n  // Returns the maximum key in the map.\n  maxKey(): K | null {\n    return this.root.maxKey();\n  }\n\n  // Traverses the map in key order and calls the specified action function\n  // for each key/value pair. If action returns true, traversal is aborted.\n  // Returns the first truthy value returned by action, or the last falsey\n  // value returned by action.\n  inorderTraversal<T>(action: (k: K, v: V) => T): T {\n    return (this.root as LLRBNode<K, V>).inorderTraversal(action);\n  }\n\n  forEach(fn: (k: K, v: V) => void): void {\n    this.inorderTraversal((k, v) => {\n      fn(k, v);\n      return false;\n    });\n  }\n\n  toString(): string {\n    const descriptions: string[] = [];\n    this.inorderTraversal((k, v) => {\n      descriptions.push(`${k}:${v}`);\n      return false;\n    });\n    return `{${descriptions.join(', ')}}`;\n  }\n\n  // Traverses the map in reverse key order and calls the specified action\n  // function for each key/value pair. If action returns true, traversal is\n  // aborted.\n  // Returns the first truthy value returned by action, or the last falsey\n  // value returned by action.\n  reverseTraversal<T>(action: (k: K, v: V) => T): T {\n    return (this.root as LLRBNode<K, V>).reverseTraversal(action);\n  }\n\n  // Returns an iterator over the SortedMap.\n  getIterator(): SortedMapIterator<K, V> {\n    return new SortedMapIterator<K, V>(this.root, null, this.comparator, false);\n  }\n\n  getIteratorFrom(key: K): SortedMapIterator<K, V> {\n    return new SortedMapIterator<K, V>(this.root, key, this.comparator, false);\n  }\n\n  getReverseIterator(): SortedMapIterator<K, V> {\n    return new SortedMapIterator<K, V>(this.root, null, this.comparator, true);\n  }\n\n  getReverseIteratorFrom(key: K): SortedMapIterator<K, V> {\n    return new SortedMapIterator<K, V>(this.root, key, this.comparator, true);\n  }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator<K, V> {\n  private isReverse: boolean;\n  private nodeStack: Array<LLRBNode<K, V> | LLRBEmptyNode<K, V>>;\n\n  constructor(\n    node: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n    startKey: K | null,\n    comparator: Comparator<K>,\n    isReverse: boolean\n  ) {\n    this.isReverse = isReverse;\n    this.nodeStack = [];\n\n    let cmp = 1;\n    while (!node.isEmpty()) {\n      cmp = startKey ? comparator(node.key, startKey) : 1;\n      // flip the comparison if we're going in reverse\n      if (startKey && isReverse) {\n        cmp *= -1;\n      }\n\n      if (cmp < 0) {\n        // This node is less than our start key. ignore it\n        if (this.isReverse) {\n          node = node.left;\n        } else {\n          node = node.right;\n        }\n      } else if (cmp === 0) {\n        // This node is exactly equal to our start key. Push it on the stack,\n        // but stop iterating;\n        this.nodeStack.push(node);\n        break;\n      } else {\n        // This node is greater than our start key, add it to the stack and move\n        // to the next one\n        this.nodeStack.push(node);\n        if (this.isReverse) {\n          node = node.right;\n        } else {\n          node = node.left;\n        }\n      }\n    }\n  }\n\n  getNext(): Entry<K, V> {\n    debugAssert(\n      this.nodeStack.length > 0,\n      'getNext() called on iterator when hasNext() is false.'\n    );\n\n    let node = this.nodeStack.pop()!;\n    const result = { key: node.key, value: node.value };\n\n    if (this.isReverse) {\n      node = node.left;\n      while (!node.isEmpty()) {\n        this.nodeStack.push(node);\n        node = node.right;\n      }\n    } else {\n      node = node.right;\n      while (!node.isEmpty()) {\n        this.nodeStack.push(node);\n        node = node.left;\n      }\n    }\n\n    return result;\n  }\n\n  hasNext(): boolean {\n    return this.nodeStack.length > 0;\n  }\n\n  peek(): Entry<K, V> | null {\n    if (this.nodeStack.length === 0) {\n      return null;\n    }\n\n    const node = this.nodeStack[this.nodeStack.length - 1];\n    return { key: node.key, value: node.value };\n  }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode<K, V> {\n  readonly color: boolean;\n  readonly left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n  readonly right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n  readonly size: number;\n\n  // Empty node is shared between all LLRB trees.\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  static EMPTY: LLRBEmptyNode<any, any> = null as any;\n\n  static RED = true;\n  static BLACK = false;\n\n  constructor(\n    public key: K,\n    public value: V,\n    color?: boolean,\n    left?: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n    right?: LLRBNode<K, V> | LLRBEmptyNode<K, V>\n  ) {\n    this.color = color != null ? color : LLRBNode.RED;\n    this.left = left != null ? left : LLRBNode.EMPTY;\n    this.right = right != null ? right : LLRBNode.EMPTY;\n    this.size = this.left.size + 1 + this.right.size;\n  }\n\n  // Returns a copy of the current node, optionally replacing pieces of it.\n  copy(\n    key: K | null,\n    value: V | null,\n    color: boolean | null,\n    left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n    right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n  ): LLRBNode<K, V> {\n    return new LLRBNode<K, V>(\n      key != null ? key : this.key,\n      value != null ? value : this.value,\n      color != null ? color : this.color,\n      left != null ? left : this.left,\n      right != null ? right : this.right\n    );\n  }\n\n  isEmpty(): boolean {\n    return false;\n  }\n\n  // Traverses the tree in key order and calls the specified action function\n  // for each node. If action returns true, traversal is aborted.\n  // Returns the first truthy value returned by action, or the last falsey\n  // value returned by action.\n  inorderTraversal<T>(action: (k: K, v: V) => T): T {\n    return (\n      (this.left as LLRBNode<K, V>).inorderTraversal(action) ||\n      action(this.key, this.value) ||\n      (this.right as LLRBNode<K, V>).inorderTraversal(action)\n    );\n  }\n\n  // Traverses the tree in reverse key order and calls the specified action\n  // function for each node. If action returns true, traversal is aborted.\n  // Returns the first truthy value returned by action, or the last falsey\n  // value returned by action.\n  reverseTraversal<T>(action: (k: K, v: V) => T): T {\n    return (\n      (this.right as LLRBNode<K, V>).reverseTraversal(action) ||\n      action(this.key, this.value) ||\n      (this.left as LLRBNode<K, V>).reverseTraversal(action)\n    );\n  }\n\n  // Returns the minimum node in the tree.\n  private min(): LLRBNode<K, V> {\n    if (this.left.isEmpty()) {\n      return this;\n    } else {\n      return (this.left as LLRBNode<K, V>).min();\n    }\n  }\n\n  // Returns the maximum key in the tree.\n  minKey(): K | null {\n    return this.min().key;\n  }\n\n  // Returns the maximum key in the tree.\n  maxKey(): K | null {\n    if (this.right.isEmpty()) {\n      return this.key;\n    } else {\n      return this.right.maxKey();\n    }\n  }\n\n  // Returns new tree, with the key/value added.\n  insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n    let n: LLRBNode<K, V> = this;\n    const cmp = comparator(key, n.key);\n    if (cmp < 0) {\n      n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n    } else if (cmp === 0) {\n      n = n.copy(null, value, null, null, null);\n    } else {\n      n = n.copy(\n        null,\n        null,\n        null,\n        null,\n        n.right.insert(key, value, comparator)\n      );\n    }\n    return n.fixUp();\n  }\n\n  private removeMin(): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n    if (this.left.isEmpty()) {\n      return LLRBNode.EMPTY;\n    }\n    let n: LLRBNode<K, V> = this;\n    if (!n.left.isRed() && !n.left.left.isRed()) {\n      n = n.moveRedLeft();\n    }\n    n = n.copy(null, null, null, (n.left as LLRBNode<K, V>).removeMin(), null);\n    return n.fixUp();\n  }\n\n  // Returns new tree, with the specified item removed.\n  remove(\n    key: K,\n    comparator: Comparator<K>\n  ): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n    let smallest: LLRBNode<K, V>;\n    let n: LLRBNode<K, V> = this;\n    if (comparator(key, n.key) < 0) {\n      if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n        n = n.moveRedLeft();\n      }\n      n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n    } else {\n      if (n.left.isRed()) {\n        n = n.rotateRight();\n      }\n      if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n        n = n.moveRedRight();\n      }\n      if (comparator(key, n.key) === 0) {\n        if (n.right.isEmpty()) {\n          return LLRBNode.EMPTY;\n        } else {\n          smallest = (n.right as LLRBNode<K, V>).min();\n          n = n.copy(\n            smallest.key,\n            smallest.value,\n            null,\n            null,\n            (n.right as LLRBNode<K, V>).removeMin()\n          );\n        }\n      }\n      n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n    }\n    return n.fixUp();\n  }\n\n  isRed(): boolean {\n    return this.color;\n  }\n\n  // Returns new tree after performing any needed rotations.\n  private fixUp(): LLRBNode<K, V> {\n    let n: LLRBNode<K, V> = this;\n    if (n.right.isRed() && !n.left.isRed()) {\n      n = n.rotateLeft();\n    }\n    if (n.left.isRed() && n.left.left.isRed()) {\n      n = n.rotateRight();\n    }\n    if (n.left.isRed() && n.right.isRed()) {\n      n = n.colorFlip();\n    }\n    return n;\n  }\n\n  private moveRedLeft(): LLRBNode<K, V> {\n    let n = this.colorFlip();\n    if (n.right.left.isRed()) {\n      n = n.copy(\n        null,\n        null,\n        null,\n        null,\n        (n.right as LLRBNode<K, V>).rotateRight()\n      );\n      n = n.rotateLeft();\n      n = n.colorFlip();\n    }\n    return n;\n  }\n\n  private moveRedRight(): LLRBNode<K, V> {\n    let n = this.colorFlip();\n    if (n.left.left.isRed()) {\n      n = n.rotateRight();\n      n = n.colorFlip();\n    }\n    return n;\n  }\n\n  private rotateLeft(): LLRBNode<K, V> {\n    const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n    return (this.right as LLRBNode<K, V>).copy(\n      null,\n      null,\n      this.color,\n      nl,\n      null\n    );\n  }\n\n  private rotateRight(): LLRBNode<K, V> {\n    const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n    return (this.left as LLRBNode<K, V>).copy(null, null, this.color, null, nr);\n  }\n\n  private colorFlip(): LLRBNode<K, V> {\n    const left = this.left.copy(null, null, !this.left.color, null, null);\n    const right = this.right.copy(null, null, !this.right.color, null, null);\n    return this.copy(null, null, !this.color, left, right);\n  }\n\n  // For testing.\n  checkMaxDepth(): boolean {\n    const blackDepth = this.check();\n    if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n      return true;\n    } else {\n      return false;\n    }\n  }\n\n  // In a balanced RB tree, the black-depth (number of black nodes) from root to\n  // leaves is equal on both sides.  This function verifies that or asserts.\n  protected check(): number {\n    if (this.isRed() && this.left.isRed()) {\n      throw fail(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<K, V>).check();\n    if (blackDepth !== (this.right as LLRBNode<K, V>).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<K, V> {\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<K, V> | LLRBEmptyNode<K, V> | null,\n    right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n  ): LLRBEmptyNode<K, V> {\n    return this;\n  }\n\n  // Returns a copy of the tree, with the specified key/value added.\n  insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n    return new LLRBNode<K, V>(key, value);\n  }\n\n  // Returns a copy of the tree, with the specified key removed.\n  remove(key: K, comparator: Comparator<K>): LLRBEmptyNode<K, V> {\n    return this;\n  }\n\n  isEmpty(): boolean {\n    return true;\n  }\n\n  inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n    return false;\n  }\n\n  reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n    return false;\n  }\n\n  minKey(): K | null {\n    return null;\n  }\n\n  maxKey(): K | null {\n    return null;\n  }\n\n  isRed(): boolean {\n    return false;\n  }\n\n  // For testing.\n  checkMaxDepth(): boolean {\n    return true;\n  }\n\n  protected check(): 0 {\n    return 0;\n  }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode<unknown, unknown>();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap, SortedMapIterator } from './sorted_map';\n\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nexport class SortedSet<T> {\n  private data: SortedMap<T, boolean>;\n\n  constructor(private comparator: (left: T, right: T) => number) {\n    this.data = new SortedMap<T, boolean>(this.comparator);\n  }\n\n  has(elem: T): boolean {\n    return this.data.get(elem) !== null;\n  }\n\n  first(): T | null {\n    return this.data.minKey();\n  }\n\n  last(): T | null {\n    return this.data.maxKey();\n  }\n\n  get size(): number {\n    return this.data.size;\n  }\n\n  indexOf(elem: T): number {\n    return this.data.indexOf(elem);\n  }\n\n  /** Iterates elements in order defined by \"comparator\" */\n  forEach(cb: (elem: T) => void): void {\n    this.data.inorderTraversal((k: T, v: boolean) => {\n      cb(k);\n      return false;\n    });\n  }\n\n  /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */\n  forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n    const iter = this.data.getIteratorFrom(range[0]);\n    while (iter.hasNext()) {\n      const elem = iter.getNext();\n      if (this.comparator(elem.key, range[1]) >= 0) {\n        return;\n      }\n      cb(elem.key);\n    }\n  }\n\n  /**\n   * Iterates over `elem`s such that: start &lt;= elem until false is returned.\n   */\n  forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n    let iter: SortedMapIterator<T, boolean>;\n    if (start !== undefined) {\n      iter = this.data.getIteratorFrom(start);\n    } else {\n      iter = this.data.getIterator();\n    }\n    while (iter.hasNext()) {\n      const elem = iter.getNext();\n      const result = cb(elem.key);\n      if (!result) {\n        return;\n      }\n    }\n  }\n\n  /** Finds the least element greater than or equal to `elem`. */\n  firstAfterOrEqual(elem: T): T | null {\n    const iter = this.data.getIteratorFrom(elem);\n    return iter.hasNext() ? iter.getNext().key : null;\n  }\n\n  getIterator(): SortedSetIterator<T> {\n    return new SortedSetIterator<T>(this.data.getIterator());\n  }\n\n  getIteratorFrom(key: T): SortedSetIterator<T> {\n    return new SortedSetIterator<T>(this.data.getIteratorFrom(key));\n  }\n\n  /** Inserts or updates an element */\n  add(elem: T): SortedSet<T> {\n    return this.copy(this.data.remove(elem).insert(elem, true));\n  }\n\n  /** Deletes an element */\n  delete(elem: T): SortedSet<T> {\n    if (!this.has(elem)) {\n      return this;\n    }\n    return this.copy(this.data.remove(elem));\n  }\n\n  isEmpty(): boolean {\n    return this.data.isEmpty();\n  }\n\n  unionWith(other: SortedSet<T>): SortedSet<T> {\n    let result: SortedSet<T> = this;\n\n    // Make sure `result` always refers to the larger one of the two sets.\n    if (result.size < other.size) {\n      result = other;\n      other = this;\n    }\n\n    other.forEach(elem => {\n      result = result.add(elem);\n    });\n    return result;\n  }\n\n  isEqual(other: SortedSet<T>): boolean {\n    if (!(other instanceof SortedSet)) {\n      return false;\n    }\n    if (this.size !== other.size) {\n      return false;\n    }\n\n    const thisIt = this.data.getIterator();\n    const otherIt = other.data.getIterator();\n    while (thisIt.hasNext()) {\n      const thisElem = thisIt.getNext().key;\n      const otherElem = otherIt.getNext().key;\n      if (this.comparator(thisElem, otherElem) !== 0) {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  toArray(): T[] {\n    const res: T[] = [];\n    this.forEach(targetId => {\n      res.push(targetId);\n    });\n    return res;\n  }\n\n  toString(): string {\n    const result: T[] = [];\n    this.forEach(elem => result.push(elem));\n    return 'SortedSet(' + result.toString() + ')';\n  }\n\n  private copy(data: SortedMap<T, boolean>): SortedSet<T> {\n    const result = new SortedSet(this.comparator);\n    result.data = data;\n    return result;\n  }\n}\n\nexport class SortedSetIterator<T> {\n  constructor(private iter: SortedMapIterator<T, boolean>) {}\n\n  getNext(): T {\n    return this.iter.getNext().key;\n  }\n\n  hasNext(): boolean {\n    return this.iter.hasNext();\n  }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffSortedSets<T>(\n  before: SortedSet<T>,\n  after: SortedSet<T>,\n  comparator: (l: T, r: T) => number,\n  onAdd: (entry: T) => void,\n  onRemove: (entry: T) => void\n): void {\n  const beforeIt = before.getIterator();\n  const afterIt = after.getIterator();\n\n  let beforeValue = advanceIterator(beforeIt);\n  let afterValue = advanceIterator(afterIt);\n\n  // Walk through the two sets at the same time, using the ordering defined by\n  // `comparator`.\n  while (beforeValue || afterValue) {\n    let added = false;\n    let removed = false;\n\n    if (beforeValue && afterValue) {\n      const cmp = comparator(beforeValue, afterValue);\n      if (cmp < 0) {\n        // The element was removed if the next element in our ordered\n        // walkthrough is only in `before`.\n        removed = true;\n      } else if (cmp > 0) {\n        // The element was added if the next element in our ordered walkthrough\n        // is only in `after`.\n        added = true;\n      }\n    } else if (beforeValue != null) {\n      removed = true;\n    } else {\n      added = true;\n    }\n\n    if (added) {\n      onAdd(afterValue!);\n      afterValue = advanceIterator(afterIt);\n    } else if (removed) {\n      onRemove(beforeValue!);\n      beforeValue = advanceIterator(beforeIt);\n    } else {\n      beforeValue = advanceIterator(beforeIt);\n      afterValue = advanceIterator(afterIt);\n    }\n  }\n}\n\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction advanceIterator<T>(it: SortedSetIterator<T>): T | undefined {\n  return it.hasNext() ? it.getNext() : undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { FieldPath } from './path';\n\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n *   foo - Overwrites foo entirely with the provided value. If foo is not\n *         present in the companion ObjectValue, the field is deleted.\n *   foo.bar - Overwrites only the field bar of the object foo.\n *             If foo is not an object, foo is replaced with an object\n *             containing foo\n */\nexport class FieldMask {\n  constructor(readonly fields: FieldPath[]) {\n    // TODO(dimond): validation of FieldMask\n    // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n    fields.sort(FieldPath.comparator);\n    debugAssert(\n      !fields.some((v, i) => i !== 0 && v.isEqual(fields[i - 1])),\n      'FieldMask contains field that is not unique: ' +\n        fields.find((v, i) => i !== 0 && v.isEqual(fields[i - 1]))!\n    );\n  }\n\n  static empty(): FieldMask {\n    return new FieldMask([]);\n  }\n\n  /**\n   * Returns a new FieldMask object that is the result of adding all the given\n   * fields paths to this field mask.\n   */\n  unionWith(extraFields: FieldPath[]): FieldMask {\n    let mergedMaskSet = new SortedSet<FieldPath>(FieldPath.comparator);\n    for (const fieldPath of this.fields) {\n      mergedMaskSet = mergedMaskSet.add(fieldPath);\n    }\n    for (const fieldPath of extraFields) {\n      mergedMaskSet = mergedMaskSet.add(fieldPath);\n    }\n    return new FieldMask(mergedMaskSet.toArray());\n  }\n\n  /**\n   * Verifies that `fieldPath` is included by at least one field in this field\n   * mask.\n   *\n   * This is an O(n) operation, where `n` is the size of the field mask.\n   */\n  covers(fieldPath: FieldPath): boolean {\n    for (const fieldMaskPath of this.fields) {\n      if (fieldMaskPath.isPrefixOf(fieldPath)) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  isEqual(other: FieldMask): boolean {\n    return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict<V> {\n  [stringKey: string]: V;\n}\n\nexport function objectSize(obj: object): number {\n  let count = 0;\n  for (const key in obj) {\n    if (Object.prototype.hasOwnProperty.call(obj, key)) {\n      count++;\n    }\n  }\n  return count;\n}\n\nexport function forEach<V>(\n  obj: Record<string, V> | undefined,\n  fn: (key: string, val: V) => void\n): void {\n  for (const key in obj) {\n    if (Object.prototype.hasOwnProperty.call(obj, key)) {\n      fn(key, obj[key]);\n    }\n  }\n}\n\nexport function mapToArray<V, R>(\n  obj: Dict<V>,\n  fn: (element: V, key: string, obj: Dict<V>) => R\n): R[] {\n  const result: R[] = [];\n  for (const key in obj) {\n    if (Object.prototype.hasOwnProperty.call(obj, key)) {\n      result.push(fn(obj[key], key, obj));\n    }\n  }\n  return result;\n}\n\nexport function isEmpty<V>(obj: Dict<V>): boolean {\n  debugAssert(\n    obj != null && typeof obj === 'object',\n    'isEmpty() expects object parameter.'\n  );\n  for (const key in obj) {\n    if (Object.prototype.hasOwnProperty.call(obj, key)) {\n      return false;\n    }\n  }\n  return true;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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<number> {\n    let i = 0;\n    return {\n      next: () => {\n        if (i < this.binaryString.length) {\n          return { value: this.binaryString.charCodeAt(i++), done: false };\n        } else {\n          return { value: undefined, done: true };\n        }\n      }\n    };\n  }\n\n  toBase64(): string {\n    return encodeBase64(this.binaryString);\n  }\n\n  toUint8Array(): Uint8Array {\n    return uint8ArrayFromBinaryString(this.binaryString);\n  }\n\n  approximateByteSize(): number {\n    return this.binaryString.length * 2;\n  }\n\n  compareTo(other: ByteString): number {\n    return primitiveComparator(this.binaryString, other.binaryString);\n  }\n\n  isEqual(other: ByteString): boolean {\n    return this.binaryString === other.binaryString;\n  }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n  let binaryString = '';\n  for (let i = 0; i < array.length; ++i) {\n    binaryString += String.fromCharCode(array[i]);\n  }\n  return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n  const buffer = new Uint8Array(binaryString.length);\n  for (let i = 0; i < binaryString.length; i++) {\n    buffer[i] = binaryString.charCodeAt(i);\n  }\n  return buffer;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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    readonly apiKey: string | undefined\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\nexport function isNumber(value: unknown): value is number {\n  return typeof value === 'number';\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\nexport function isString(value: unknown): value is string {\n  return typeof value === 'string';\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/**\n * Utility type to create an type that only allows one\n * property of the Type param T to be set.\n *\n * @example\n * ```typescript\n * type XorY = OneOf<{ x: unknown, y: unknown }>\n * let a = { x: \"foo\" }           // OK\n * let b = { y: \"foo\" }           // OK\n * let c = { a: \"foo\", y: \"foo\" } // Not OK\n * ```\n */\nexport type OneOf<T> = {\n  [K in keyof T]: Pick<T, K> & {\n    [P in Exclude<keyof T, K>]?: undefined;\n  };\n}[keyof T];\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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\nexport const TRUE_VALUE: Value = {\n  booleanValue: true\n};\n\nexport const FALSE_VALUE: Value = {\n  booleanValue: false\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\nexport interface EqualOptions {\n  nanEqual: boolean;\n  mixIntegerDouble: boolean;\n  semanticsEqual: boolean;\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */\nexport function valueEquals(\n  left: Value,\n  right: Value,\n  options?: EqualOptions\n): 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, options);\n    case TypeOrder.ArrayValue:\n      return arrayEquals(\n        left.arrayValue!.values || [],\n        right.arrayValue!.values || [],\n        (l, r) => valueEquals(l, r, options)\n      );\n    case TypeOrder.VectorValue:\n    case TypeOrder.ObjectValue:\n      return objectEquals(left, right, options);\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(\n  left: Value,\n  right: Value,\n  options?: EqualOptions\n): boolean {\n  if ('integerValue' in left && 'integerValue' in right) {\n    return (\n      normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)\n    );\n  }\n\n  let n1: number, n2: number;\n  if ('doubleValue' in left && 'doubleValue' in right) {\n    n1 = normalizeNumber(left.doubleValue!);\n    n2 = normalizeNumber(right.doubleValue!);\n  } else if (options?.mixIntegerDouble) {\n    n1 = normalizeNumber(left.integerValue ?? left.doubleValue);\n    n2 = normalizeNumber(right.integerValue ?? right.doubleValue);\n  } else {\n    return false;\n  }\n\n  if (n1 === n2) {\n    return options?.semanticsEqual\n      ? true\n      : isNegativeZero(n1) === isNegativeZero(n2);\n  } else {\n    const nanEqual = options === undefined ? true : options.nanEqual;\n    return nanEqual ? isNaN(n1) && isNaN(n2) : false;\n  }\n}\n\nfunction objectEquals(\n  left: Value,\n  right: Value,\n  options?: EqualOptions\n): 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], options)\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 !== undefined && compare !== 0) {\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 BooleanValue . */\nexport function isBoolean(\n  value?: Value | null\n): value is { booleanValue: boolean } {\n  return !!value && 'booleanValue' in value;\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(\n  value?: Value | null\n): value is\n  | { doubleValue: string | number }\n  | { integerValue: string | number } {\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 an ArrayValue. */\nexport function isString(\n  value?: Value | null\n): value is { stringValue: string } {\n  return !!value && 'stringValue' in value;\n}\n\n/** Returns true if `value` is an BytesValue. */\nexport function isBytes(value?: Value | null): value is { bytesValue: string } {\n  return !!value && 'bytesValue' 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 Timestamp. */\nexport function isTimestampValue(\n  value?: Value | null\n): value is { timestampValue: Timestamp } {\n  return !!value && 'timestampValue' in value && !!value.timestampValue;\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/** Returns true if `value` is a VetorValue. */\nexport function getVectorValue(\n  value: ProtoValue | null\n): ArrayValue | undefined {\n  return (value?.mapValue?.fields || {})[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\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<T> {\n  [name: string]: T;\n}\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */\nexport class ObjectValue {\n  constructor(readonly value: { mapValue: ProtoMapValue }) {\n    debugAssert(\n      !isServerTimestamp(value),\n      'ServerTimestamps should be converted to ServerTimestampValue'\n    );\n  }\n\n  static empty(): ObjectValue {\n    return new ObjectValue({ mapValue: {} });\n  }\n\n  /**\n   * Returns the value at the given path or null.\n   *\n   * @param path - the path to search\n   * @returns The value at the path or null if the path is not set.\n   */\n  field(path: FieldPath): ProtoValue | null {\n    if (path.isEmpty()) {\n      return this.value;\n    } else {\n      let currentLevel: ProtoValue = this.value;\n      for (let i = 0; i < path.length - 1; ++i) {\n        currentLevel = (currentLevel.mapValue!.fields || {})[path.get(i)];\n        if (!isMapValue(currentLevel)) {\n          return null;\n        }\n      }\n      currentLevel = (currentLevel.mapValue!.fields! || {})[path.lastSegment()];\n      return currentLevel || null;\n    }\n  }\n\n  /**\n   * Sets the field to the provided value.\n   *\n   * @param path - The field path to set.\n   * @param value - The value to set.\n   */\n  set(path: FieldPath, value: ProtoValue): void {\n    debugAssert(\n      !path.isEmpty(),\n      'Cannot set field for empty path on ObjectValue'\n    );\n    const fieldsMap = this.getFieldsMap(path.popLast());\n    fieldsMap[path.lastSegment()] = deepClone(value);\n  }\n\n  /**\n   * Sets the provided fields to the provided values.\n   *\n   * @param data - A map of fields to values (or null for deletes).\n   */\n  setAll(data: Map<FieldPath, ProtoValue | null>): void {\n    let parent = FieldPath.emptyPath();\n\n    let upserts: { [key: string]: ProtoValue } = {};\n    let deletes: string[] = [];\n\n    data.forEach((value, path) => {\n      if (!parent.isImmediateParentOf(path)) {\n        // Insert the accumulated changes at this parent location\n        const fieldsMap = this.getFieldsMap(parent);\n        this.applyChanges(fieldsMap, upserts, deletes);\n        upserts = {};\n        deletes = [];\n        parent = path.popLast();\n      }\n\n      if (value) {\n        upserts[path.lastSegment()] = deepClone(value);\n      } else {\n        deletes.push(path.lastSegment());\n      }\n    });\n\n    const fieldsMap = this.getFieldsMap(parent);\n    this.applyChanges(fieldsMap, upserts, deletes);\n  }\n\n  /**\n   * Removes the field at the specified path. If there is no field at the\n   * specified path, nothing is changed.\n   *\n   * @param path - The field path to remove.\n   */\n  delete(path: FieldPath): void {\n    debugAssert(\n      !path.isEmpty(),\n      'Cannot delete field for empty path on ObjectValue'\n    );\n    const nestedValue = this.field(path.popLast());\n    if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {\n      delete nestedValue.mapValue.fields[path.lastSegment()];\n    }\n  }\n\n  isEqual(other: ObjectValue): boolean {\n    return valueEquals(this.value, other.value);\n  }\n\n  /**\n   * Returns the map that contains the leaf element of `path`. If the parent\n   * entry does not yet exist, or if it is not a map, a new map will be created.\n   */\n  private getFieldsMap(path: FieldPath): Record<string, ProtoValue> {\n    let current = this.value;\n\n    if (!current.mapValue!.fields) {\n      current.mapValue = { fields: {} };\n    }\n\n    for (let i = 0; i < path.length; ++i) {\n      let next = current.mapValue!.fields![path.get(i)];\n      if (!isMapValue(next) || !next.mapValue.fields) {\n        next = { mapValue: { fields: {} } };\n        current.mapValue!.fields![path.get(i)] = next;\n      }\n      current = next as { mapValue: ProtoMapValue };\n    }\n\n    return current.mapValue!.fields!;\n  }\n\n  /**\n   * Modifies `fieldsMap` by adding, replacing or deleting the specified\n   * entries.\n   */\n  private applyChanges(\n    fieldsMap: Record<string, ProtoValue>,\n    inserts: { [key: string]: ProtoValue },\n    deletes: string[]\n  ): void {\n    forEach(inserts, (key, val) => (fieldsMap[key] = val));\n    for (const field of deletes) {\n      delete fieldsMap[field];\n    }\n  }\n\n  clone(): ObjectValue {\n    return new ObjectValue(\n      deepClone(this.value) as { mapValue: ProtoMapValue }\n    );\n  }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */\nexport function extractFieldMask(value: ProtoMapValue): FieldMask {\n  const fields: FieldPath[] = [];\n  forEach(value!.fields, (key, value) => {\n    const currentPath = new FieldPath([key]);\n    if (isMapValue(value)) {\n      const nestedMask = extractFieldMask(value.mapValue!);\n      const nestedFields = nestedMask.fields;\n      if (nestedFields.length === 0) {\n        // Preserve the empty map by adding it to the FieldMask.\n        fields.push(currentPath);\n      } else {\n        // For nested and non-empty ObjectValues, add the FieldPath of the\n        // leaf nodes.\n        for (const nestedPath of nestedFields) {\n          fields.push(currentPath.child(nestedPath));\n        }\n      }\n    } else {\n      // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n      // nodes.\n      fields.push(currentPath);\n    }\n  });\n  return new FieldMask(fields);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(\n  serializer: Serializer,\n  value: number,\n  options?: { preferIntegers: boolean }\n): ProtoValue {\n  if (Number.isInteger(value) && options?.preferIntegers) {\n    return toInteger(value);\n  }\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 if (transform instanceof NumericIncrementTransformOperation) {\n    return applyNumericIncrementTransformOperationToLocalView(\n      transform,\n      previousValue\n    );\n  } else if (transform instanceof NumericMinimumTransformOperation) {\n    return applyNumericMinimumTransformOperationToLocalView(\n      transform,\n      previousValue\n    );\n  } else if (transform instanceof NumericMaximumTransformOperation) {\n    return applyNumericMaximumTransformOperationToLocalView(\n      transform,\n      previousValue\n    );\n  } else {\n    debugAssert(false, 'Unsupported transform: ' + transform);\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  } else if (\n    left instanceof NumericMinimumTransformOperation &&\n    right instanceof NumericMinimumTransformOperation\n  ) {\n    return valueEquals(left.operand, right.operand);\n  } else if (\n    left instanceof NumericMaximumTransformOperation &&\n    right instanceof NumericMaximumTransformOperation\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 abstract class NumericTransformOperation extends TransformOperation {\n  constructor(readonly serializer: Serializer, readonly operand: ProtoValue) {\n    super();\n    debugAssert(\n      isNumber(operand),\n      'NumericTransformOperation transform requires a NumberValue'\n    );\n  }\n}\n\nexport class NumericIncrementTransformOperation extends NumericTransformOperation {}\n\nexport class NumericMinimumTransformOperation extends NumericTransformOperation {}\n\nexport class NumericMaximumTransformOperation extends NumericTransformOperation {}\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\nexport function applyNumericTransformOperationToLocalView(\n  operation: NumericTransformOperation,\n  previousValue: ProtoValue | null,\n  transform: (x: number, y: number) => number\n): ProtoValue {\n  if (!isNumber(previousValue)) {\n    return operation.operand;\n  }\n  const prev = asNumber(previousValue);\n  const oper = asNumber(operation.operand);\n  const result = transform(prev, oper);\n  if (isInteger(previousValue) && isInteger(operation.operand)) {\n    return toInteger(result);\n  } else {\n    return toDouble(operation.serializer, result);\n  }\n}\n\nexport function applyNumericMinimumTransformOperationToLocalView(\n  operation: NumericMinimumTransformOperation,\n  previousValue: ProtoValue | null\n): ProtoValue {\n  return applyNumericTransformOperationToLocalView(\n    operation,\n    previousValue,\n    Math.min\n  );\n}\n\nexport function applyNumericMaximumTransformOperationToLocalView(\n  operation: NumericMaximumTransformOperation,\n  previousValue: ProtoValue | null\n): ProtoValue {\n  return applyNumericTransformOperationToLocalView(\n    operation,\n    previousValue,\n    Math.max\n  );\n}\n\nfunction asNumber(value: ProtoValue): number {\n  return normalizeNumber(value.integerValue || value.doubleValue);\n}\n\nfunction coercedFieldValuesArray(value: ProtoValue | null): ProtoValue[] {\n  return isArray(value) && value.arrayValue.values\n    ? value.arrayValue.values.slice()\n    : [];\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './field_mask';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport {\n  applyTransformOperationToLocalView,\n  applyTransformOperationToRemoteDocument,\n  computeTransformOperationBaseValue,\n  TransformOperation,\n  transformOperationEquals\n} from './transform_operation';\n\n/** A field path and the TransformOperation to perform upon it. */\nexport class FieldTransform {\n  constructor(\n    readonly field: FieldPath,\n    readonly transform: TransformOperation\n  ) {}\n}\n\nexport function fieldTransformEquals(\n  left: FieldTransform,\n  right: FieldTransform\n): boolean {\n  return (\n    left.field.isEqual(right.field) &&\n    transformOperationEquals(left.transform, right.transform)\n  );\n}\n\nexport function fieldTransformsAreEqual(\n  left?: FieldTransform[],\n  right?: FieldTransform[]\n): boolean {\n  if (left === undefined && right === undefined) {\n    return true;\n  }\n\n  if (left && right) {\n    return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r));\n  }\n\n  return false;\n}\n\n/** The result of successfully applying a mutation to the backend. */\nexport class MutationResult {\n  constructor(\n    /**\n     * The version at which the mutation was committed:\n     *\n     * - For most operations, this is the updateTime in the WriteResult.\n     * - For deletes, the commitTime of the WriteResponse (because deletes are\n     *   not stored and have no updateTime).\n     *\n     * Note that these versions can be different: No-op writes will not change\n     * the updateTime even though the commitTime advances.\n     */\n    readonly version: SnapshotVersion,\n    /**\n     * The resulting fields returned from the backend after a mutation\n     * containing field transforms has been committed. Contains one FieldValue\n     * for each FieldTransform that was in the mutation.\n     *\n     * Will be empty if the mutation did not contain any field transforms.\n     */\n    readonly transformResults: Array<ProtoValue | null>\n  ) {}\n}\n\nexport const enum MutationType {\n  Set,\n  Patch,\n  Delete,\n  Verify\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */\nexport class Precondition {\n  private constructor(\n    readonly updateTime?: SnapshotVersion,\n    readonly exists?: boolean\n  ) {\n    debugAssert(\n      updateTime === undefined || exists === undefined,\n      'Precondition can specify \"exists\" or \"updateTime\" but not both'\n    );\n  }\n\n  /** Creates a new empty Precondition. */\n  static none(): Precondition {\n    return new Precondition();\n  }\n\n  /** Creates a new Precondition with an exists flag. */\n  static exists(exists: boolean): Precondition {\n    return new Precondition(undefined, exists);\n  }\n\n  /** Creates a new Precondition based on a version a document exists at. */\n  static updateTime(version: SnapshotVersion): Precondition {\n    return new Precondition(version);\n  }\n\n  /** Returns whether this Precondition is empty. */\n  get isNone(): boolean {\n    return this.updateTime === undefined && this.exists === undefined;\n  }\n\n  isEqual(other: Precondition): boolean {\n    return (\n      this.exists === other.exists &&\n      (this.updateTime\n        ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)\n        : !other.updateTime)\n    );\n  }\n}\n\n/** Returns true if the preconditions is valid for the given document. */\nexport function preconditionIsValidForDocument(\n  precondition: Precondition,\n  document: MutableDocument\n): boolean {\n  if (precondition.updateTime !== undefined) {\n    return (\n      document.isFoundDocument() &&\n      document.version.isEqual(precondition.updateTime)\n    );\n  } else if (precondition.exists !== undefined) {\n    return precondition.exists === document.isFoundDocument();\n  } else {\n    debugAssert(precondition.isNone, 'Precondition should be empty');\n    return true;\n  }\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION           APPLIED TO            RESULTS IN\n *\n * SetMutation        Document(v3)          Document(v3)\n * SetMutation        NoDocument(v3)        Document(v0)\n * SetMutation        InvalidDocument(v0)   Document(v0)\n * PatchMutation      Document(v3)          Document(v3)\n * PatchMutation      NoDocument(v3)        NoDocument(v3)\n * PatchMutation      InvalidDocument(v0)   UnknownDocument(v3)\n * DeleteMutation     Document(v3)          NoDocument(v0)\n * DeleteMutation     NoDocument(v3)        NoDocument(v0)\n * DeleteMutation     InvalidDocument(v0)   NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */\nexport abstract class Mutation {\n  abstract readonly type: MutationType;\n  abstract readonly key: DocumentKey;\n  abstract readonly precondition: Precondition;\n  abstract readonly fieldTransforms: FieldTransform[];\n  /**\n   * Returns a `FieldMask` representing the fields that will be changed by\n   * applying this mutation. Returns `null` if the mutation will overwrite the\n   * entire document.\n   */\n  abstract getFieldMask(): FieldMask | null;\n}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */\nexport function calculateOverlayMutation(\n  doc: MutableDocument,\n  mask: FieldMask | null\n): Mutation | null {\n  if (!doc.hasLocalMutations || (mask && mask!.fields.length === 0)) {\n    return null;\n  }\n\n  // mask is null when sets or deletes are applied to the current document.\n  if (mask === null) {\n    if (doc.isNoDocument()) {\n      return new DeleteMutation(doc.key, Precondition.none());\n    } else {\n      return new SetMutation(doc.key, doc.data, Precondition.none());\n    }\n  } else {\n    const docValue = doc.data;\n    const patchValue = ObjectValue.empty();\n    let maskSet = new SortedSet<FieldPath>(FieldPath.comparator);\n    for (let path of mask.fields) {\n      if (!maskSet.has(path)) {\n        let value = docValue.field(path);\n        // If we are deleting a nested field, we take the immediate parent as\n        // the mask used to construct the resulting mutation.\n        // Justification: Nested fields can create parent fields implicitly. If\n        // only a leaf entry is deleted in later mutations, the parent field\n        // should still remain, but we may have lost this information.\n        // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n        // This leaves the final result (foo, {}). Despite the fact that `doc`\n        // has the correct result, `foo` is not in `mask`, and the resulting\n        // mutation would miss `foo`.\n        if (value === null && path.length > 1) {\n          path = path.popLast();\n          value = docValue.field(path);\n        }\n        if (value === null) {\n          patchValue.delete(path);\n        } else {\n          patchValue.set(path, value);\n        }\n        maskSet = maskSet.add(path);\n      }\n    }\n    return new PatchMutation(\n      doc.key,\n      patchValue,\n      new FieldMask(maskSet.toArray()),\n      Precondition.none()\n    );\n  }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n *     invalid document if the client has no knowledge of the pre-mutation state\n *     of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */\nexport function mutationApplyToRemoteDocument(\n  mutation: Mutation,\n  document: MutableDocument,\n  mutationResult: MutationResult\n): void {\n  mutationVerifyKeyMatches(mutation, document);\n  if (mutation instanceof SetMutation) {\n    setMutationApplyToRemoteDocument(mutation, document, mutationResult);\n  } else if (mutation instanceof PatchMutation) {\n    patchMutationApplyToRemoteDocument(mutation, document, mutationResult);\n  } else {\n    debugAssert(\n      mutation instanceof DeleteMutation,\n      'Unexpected mutation type: ' + mutation\n    );\n    deleteMutationApplyToRemoteDocument(mutation, document, mutationResult);\n  }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n *     invalid document if the client has no knowledge of the pre-mutation state\n *     of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n *     batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */\nexport function mutationApplyToLocalView(\n  mutation: Mutation,\n  document: MutableDocument,\n  previousMask: FieldMask | null,\n  localWriteTime: Timestamp\n): FieldMask | null {\n  mutationVerifyKeyMatches(mutation, document);\n\n  if (mutation instanceof SetMutation) {\n    return setMutationApplyToLocalView(\n      mutation,\n      document,\n      previousMask,\n      localWriteTime\n    );\n  } else if (mutation instanceof PatchMutation) {\n    return patchMutationApplyToLocalView(\n      mutation,\n      document,\n      previousMask,\n      localWriteTime\n    );\n  } else {\n    debugAssert(\n      mutation instanceof DeleteMutation,\n      'Unexpected mutation type: ' + mutation\n    );\n    return deleteMutationApplyToLocalView(mutation, document, previousMask);\n  }\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */\nexport function mutationExtractBaseValue(\n  mutation: Mutation,\n  document: Document\n): ObjectValue | null {\n  let baseObject: ObjectValue | null = null;\n  for (const fieldTransform of mutation.fieldTransforms) {\n    const existingValue = document.data.field(fieldTransform.field);\n    const coercedValue = computeTransformOperationBaseValue(\n      fieldTransform.transform,\n      existingValue || null\n    );\n\n    if (coercedValue != null) {\n      if (baseObject === null) {\n        baseObject = ObjectValue.empty();\n      }\n      baseObject.set(fieldTransform.field, coercedValue);\n    }\n  }\n  return baseObject ? baseObject : null;\n}\n\nexport function mutationEquals(left: Mutation, right: Mutation): boolean {\n  if (left.type !== right.type) {\n    return false;\n  }\n\n  if (!left.key.isEqual(right.key)) {\n    return false;\n  }\n\n  if (!left.precondition.isEqual(right.precondition)) {\n    return false;\n  }\n\n  if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) {\n    return false;\n  }\n\n  if (left.type === MutationType.Set) {\n    return (left as SetMutation).value.isEqual((right as SetMutation).value);\n  }\n\n  if (left.type === MutationType.Patch) {\n    return (\n      (left as PatchMutation).data.isEqual((right as PatchMutation).data) &&\n      (left as PatchMutation).fieldMask.isEqual(\n        (right as PatchMutation).fieldMask\n      )\n    );\n  }\n\n  return true;\n}\n\nfunction mutationVerifyKeyMatches(\n  mutation: Mutation,\n  document: MutableDocument\n): void {\n  debugAssert(\n    document.key.isEqual(mutation.key),\n    'Can only apply a mutation to a document with the same key'\n  );\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nexport class SetMutation extends Mutation {\n  constructor(\n    readonly key: DocumentKey,\n    readonly value: ObjectValue,\n    readonly precondition: Precondition,\n    readonly fieldTransforms: FieldTransform[] = []\n  ) {\n    super();\n  }\n\n  readonly type: MutationType = MutationType.Set;\n\n  getFieldMask(): FieldMask | null {\n    return null;\n  }\n}\n\nfunction setMutationApplyToRemoteDocument(\n  mutation: SetMutation,\n  document: MutableDocument,\n  mutationResult: MutationResult\n): void {\n  // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n  // remote document the server has accepted the mutation so the precondition\n  // must have held.\n  const newData = mutation.value.clone();\n  const transformResults = serverTransformResults(\n    mutation.fieldTransforms,\n    document,\n    mutationResult.transformResults\n  );\n  newData.setAll(transformResults);\n  document\n    .convertToFoundDocument(mutationResult.version, newData)\n    .setHasCommittedMutations();\n}\n\nfunction setMutationApplyToLocalView(\n  mutation: SetMutation,\n  document: MutableDocument,\n  previousMask: FieldMask | null,\n  localWriteTime: Timestamp\n): FieldMask | null {\n  if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n    // The mutation failed to apply (e.g. a document ID created with add()\n    // caused a name collision).\n    return previousMask;\n  }\n\n  const newData = mutation.value.clone();\n  const transformResults = localTransformResults(\n    mutation.fieldTransforms,\n    localWriteTime,\n    document\n  );\n  newData.setAll(transformResults);\n  document\n    .convertToFoundDocument(document.version, newData)\n    .setHasLocalMutations();\n  return null; // SetMutation overwrites all fields.\n}\n\n/**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n *  * When a field is in both the mask and the values, the corresponding field\n *    is updated.\n *  * When a field is in neither the mask nor the values, the corresponding\n *    field is unmodified.\n *  * When a field is in the mask but not in the values, the corresponding field\n *    is deleted.\n *  * When a field is not in the mask but is in the values, the values map is\n *    ignored.\n */\nexport class PatchMutation extends Mutation {\n  constructor(\n    readonly key: DocumentKey,\n    readonly data: ObjectValue,\n    readonly fieldMask: FieldMask,\n    readonly precondition: Precondition,\n    readonly fieldTransforms: FieldTransform[] = []\n  ) {\n    super();\n  }\n\n  readonly type: MutationType = MutationType.Patch;\n\n  getFieldMask(): FieldMask | null {\n    return this.fieldMask;\n  }\n}\n\nfunction patchMutationApplyToRemoteDocument(\n  mutation: PatchMutation,\n  document: MutableDocument,\n  mutationResult: MutationResult\n): void {\n  if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n    // Since the mutation was not rejected, we know that the precondition\n    // matched on the backend. We therefore must not have the expected version\n    // of the document in our cache and convert to an UnknownDocument with a\n    // known updateTime.\n    document.convertToUnknownDocument(mutationResult.version);\n    return;\n  }\n\n  const transformResults = serverTransformResults(\n    mutation.fieldTransforms,\n    document,\n    mutationResult.transformResults\n  );\n  const newData = document.data;\n  newData.setAll(getPatch(mutation));\n  newData.setAll(transformResults);\n  document\n    .convertToFoundDocument(mutationResult.version, newData)\n    .setHasCommittedMutations();\n}\n\nfunction patchMutationApplyToLocalView(\n  mutation: PatchMutation,\n  document: MutableDocument,\n  previousMask: FieldMask | null,\n  localWriteTime: Timestamp\n): FieldMask | null {\n  if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n    return previousMask;\n  }\n\n  const transformResults = localTransformResults(\n    mutation.fieldTransforms,\n    localWriteTime,\n    document\n  );\n  const newData = document.data;\n  newData.setAll(getPatch(mutation));\n  newData.setAll(transformResults);\n  document\n    .convertToFoundDocument(document.version, newData)\n    .setHasLocalMutations();\n\n  if (previousMask === null) {\n    return null;\n  }\n\n  return previousMask\n    .unionWith(mutation.fieldMask.fields)\n    .unionWith(mutation.fieldTransforms.map(transform => transform.field));\n}\n\n/**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */\nfunction getPatch(mutation: PatchMutation): Map<FieldPath, ProtoValue | null> {\n  const result = new Map<FieldPath, ProtoValue | null>();\n  mutation.fieldMask.fields.forEach(fieldPath => {\n    if (!fieldPath.isEmpty()) {\n      const newValue = mutation.data.field(fieldPath);\n      result.set(fieldPath, newValue);\n    }\n  });\n  return result;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */\nfunction serverTransformResults(\n  fieldTransforms: FieldTransform[],\n  mutableDocument: MutableDocument,\n  serverTransformResults: Array<ProtoValue | null>\n): Map<FieldPath, ProtoValue> {\n  const transformResults = new Map<FieldPath, ProtoValue>();\n  hardAssert(\n    fieldTransforms.length === serverTransformResults.length,\n    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<FieldPath, ProtoValue> {\n  const transformResults = new Map<FieldPath, ProtoValue>();\n  for (const fieldTransform of fieldTransforms) {\n    const transform = fieldTransform.transform;\n\n    const previousValue = mutableDocument.data.field(fieldTransform.field);\n    transformResults.set(\n      fieldTransform.field,\n      applyTransformOperationToLocalView(\n        transform,\n        previousValue,\n        localWriteTime\n      )\n    );\n  }\n  return transformResults;\n}\n\n/** A mutation that deletes the document at the given key. */\nexport class DeleteMutation extends Mutation {\n  constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n    super();\n  }\n\n  readonly type: MutationType = MutationType.Delete;\n  readonly fieldTransforms: FieldTransform[] = [];\n\n  getFieldMask(): FieldMask | null {\n    return null;\n  }\n}\n\nfunction deleteMutationApplyToRemoteDocument(\n  mutation: DeleteMutation,\n  document: MutableDocument,\n  mutationResult: MutationResult\n): void {\n  debugAssert(\n    mutationResult.transformResults.length === 0,\n    'Transform results received by DeleteMutation.'\n  );\n\n  // Unlike applyToLocalView, if we're applying a mutation to a remote\n  // document the server has accepted the mutation so the precondition must\n  // have held.\n  document\n    .convertToNoDocument(mutationResult.version)\n    .setHasCommittedMutations();\n}\n\nfunction deleteMutationApplyToLocalView(\n  mutation: DeleteMutation,\n  document: MutableDocument,\n  previousMask: FieldMask | null\n): FieldMask | null {\n  debugAssert(\n    document.key.isEqual(mutation.key),\n    'Can only apply mutation to document with same key'\n  );\n  if (preconditionIsValidForDocument(mutation.precondition, document)) {\n    document.convertToNoDocument(document.version).setHasLocalMutations();\n    return null;\n  }\n  return previousMask;\n}\n\n/**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */\nexport class VerifyMutation extends Mutation {\n  constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n    super();\n  }\n\n  readonly type: MutationType = MutationType.Verify;\n  readonly fieldTransforms: FieldTransform[] = [];\n\n  getFieldMask(): FieldMask | null {\n    return null;\n  }\n}\n","/**\n * @license\n * Copyright 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 { 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';\nimport type { CorePipeline } from './pipeline';\nimport { TargetOrPipeline } from './pipeline-util';\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 targetIsPipelineTarget(\n  target: TargetOrPipeline\n): target is CorePipeline {\n  // Workaround for circular dependency\n  return !!(target as CorePipeline).isCorePipeline;\n}\n\nexport function targetIsDocumentTarget(target: Target): boolean {\n  return (\n    !!target.path &&\n    DocumentKey.isDocumentKey(target.path) &&\n    target.collectionGroup === null &&\n    target.filters.length === 0\n  );\n}\n\n/** Returns the field filters that target the given field path. */\nexport function targetGetFieldFiltersForPath(\n  target: Target,\n  path: FieldPath\n): FieldFilter[] {\n  return target.filters.filter(\n    f => f instanceof FieldFilter && f.field.isEqual(path)\n  ) as FieldFilter[];\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\nexport function targetGetArrayValues(\n  target: Target,\n  fieldIndex: FieldIndex\n): ProtoValue[] | null {\n  const segment = fieldIndexGetArraySegment(fieldIndex);\n  if (segment === undefined) {\n    return null;\n  }\n\n  for (const fieldFilter of targetGetFieldFiltersForPath(\n    target,\n    segment.fieldPath\n  )) {\n    switch (fieldFilter.op) {\n      case Operator.ARRAY_CONTAINS_ANY:\n        return fieldFilter.value.arrayValue!.values || [];\n      case Operator.ARRAY_CONTAINS:\n        return [fieldFilter.value];\n      default:\n      // Remaining filters are not array filters.\n    }\n  }\n  return null;\n}\n\n/**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */\nexport function targetGetNotInValues(\n  target: Target,\n  fieldIndex: FieldIndex\n): ProtoValue[] | null {\n  const values = new Map</* fieldPath = */ string, ProtoValue>();\n\n  for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n    for (const fieldFilter of targetGetFieldFiltersForPath(\n      target,\n      segment.fieldPath\n    )) {\n      switch (fieldFilter.op) {\n        case Operator.EQUAL:\n        case Operator.IN:\n          // Encode equality prefix, which is encoded in the index value before\n          // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n          // `value != 'ab'`).\n          values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n          break;\n        case Operator.NOT_IN:\n        case Operator.NOT_EQUAL:\n          // NotIn/NotEqual is always a suffix. There cannot be any remaining\n          // segments and hence we can return early here.\n          values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n          return Array.from(values.values());\n        default:\n        // Remaining filters cannot be used as notIn bounds.\n      }\n    }\n  }\n\n  return null;\n}\n\n/**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */\nexport function targetGetLowerBound(\n  target: Target,\n  fieldIndex: FieldIndex\n): Bound {\n  const values: ProtoValue[] = [];\n  let inclusive = true;\n\n  // For each segment, retrieve a lower bound if there is a suitable filter or\n  // startAt.\n  for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n    const segmentBound =\n      segment.kind === IndexKind.ASCENDING\n        ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)\n        : targetGetDescendingBound(target, segment.fieldPath, target.startAt);\n\n    values.push(segmentBound.value);\n    inclusive &&= segmentBound.inclusive;\n  }\n  return new Bound(values, inclusive);\n}\n\n/**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */\nexport function targetGetUpperBound(\n  target: Target,\n  fieldIndex: FieldIndex\n): Bound {\n  const values: ProtoValue[] = [];\n  let inclusive = true;\n\n  // For each segment, retrieve an upper bound if there is a suitable filter or\n  // endAt.\n  for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n    const segmentBound =\n      segment.kind === IndexKind.ASCENDING\n        ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)\n        : targetGetAscendingBound(target, segment.fieldPath, target.endAt);\n\n    values.push(segmentBound.value);\n    inclusive &&= segmentBound.inclusive;\n  }\n\n  return new Bound(values, inclusive);\n}\n\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction targetGetAscendingBound(\n  target: Target,\n  fieldPath: FieldPath,\n  bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n  let value: ProtoValue = MIN_VALUE;\n\n  let inclusive = true;\n\n  // Process all filters to find a value for the current field segment\n  for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n    let filterValue: ProtoValue = MIN_VALUE;\n    let filterInclusive = true;\n\n    switch (fieldFilter.op) {\n      case Operator.LESS_THAN:\n      case Operator.LESS_THAN_OR_EQUAL:\n        filterValue = valuesGetLowerBound(fieldFilter.value);\n        break;\n      case Operator.EQUAL:\n      case Operator.IN:\n      case Operator.GREATER_THAN_OR_EQUAL:\n        filterValue = fieldFilter.value;\n        break;\n      case Operator.GREATER_THAN:\n        filterValue = fieldFilter.value;\n        filterInclusive = false;\n        break;\n      case Operator.NOT_EQUAL:\n      case Operator.NOT_IN:\n        filterValue = MIN_VALUE;\n        break;\n      default:\n      // Remaining filters cannot be used as lower bounds.\n    }\n\n    if (\n      lowerBoundCompare(\n        { value, inclusive },\n        { value: filterValue, inclusive: filterInclusive }\n      ) < 0\n    ) {\n      value = filterValue;\n      inclusive = filterInclusive;\n    }\n  }\n\n  // If there is an additional bound, compare the values against the existing\n  // range to see if we can narrow the scope.\n  if (bound !== null) {\n    for (let i = 0; i < target.orderBy.length; ++i) {\n      const orderBy = target.orderBy[i];\n      if (orderBy.field.isEqual(fieldPath)) {\n        const cursorValue = bound.position[i];\n        if (\n          lowerBoundCompare(\n            { value, inclusive },\n            { value: cursorValue, inclusive: bound.inclusive }\n          ) < 0\n        ) {\n          value = cursorValue;\n          inclusive = bound.inclusive;\n        }\n        break;\n      }\n    }\n  }\n\n  return { value, inclusive };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */\nfunction targetGetDescendingBound(\n  target: Target,\n  fieldPath: FieldPath,\n  bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n  let value: ProtoValue = MAX_VALUE;\n  let inclusive = true;\n\n  // Process all filters to find a value for the current field segment\n  for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n    let filterValue: ProtoValue = MAX_VALUE;\n    let filterInclusive = true;\n\n    switch (fieldFilter.op) {\n      case Operator.GREATER_THAN_OR_EQUAL:\n      case Operator.GREATER_THAN:\n        filterValue = valuesGetUpperBound(fieldFilter.value);\n        filterInclusive = false;\n        break;\n      case Operator.EQUAL:\n      case Operator.IN:\n      case Operator.LESS_THAN_OR_EQUAL:\n        filterValue = fieldFilter.value;\n        break;\n      case Operator.LESS_THAN:\n        filterValue = fieldFilter.value;\n        filterInclusive = false;\n        break;\n      case Operator.NOT_EQUAL:\n      case Operator.NOT_IN:\n        filterValue = MAX_VALUE;\n        break;\n      default:\n      // Remaining filters cannot be used as upper bounds.\n    }\n\n    if (\n      upperBoundCompare(\n        { value, inclusive },\n        { value: filterValue, inclusive: filterInclusive }\n      ) > 0\n    ) {\n      value = filterValue;\n      inclusive = filterInclusive;\n    }\n  }\n\n  // If there is an additional bound, compare the values against the existing\n  // range to see if we can narrow the scope.\n  if (bound !== null) {\n    for (let i = 0; i < target.orderBy.length; ++i) {\n      const orderBy = target.orderBy[i];\n      if (orderBy.field.isEqual(fieldPath)) {\n        const cursorValue = bound.position[i];\n        if (\n          upperBoundCompare(\n            { value, inclusive },\n            { value: cursorValue, inclusive: bound.inclusive }\n          ) > 0\n        ) {\n          value = cursorValue;\n          inclusive = bound.inclusive;\n        }\n        break;\n      }\n    }\n  }\n\n  return { value, inclusive };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\nexport function targetGetSegmentCount(target: Target): number {\n  let fields = new SortedSet<FieldPath>(FieldPath.comparator);\n  let hasArraySegment = false;\n\n  for (const filter of target.filters) {\n    for (const subFilter of filter.getFlattenedFilters()) {\n      // __name__ is not an explicit segment of any index, so we don't need to\n      // count it.\n      if (subFilter.field.isKeyField()) {\n        continue;\n      }\n\n      // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n      // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n      // though these are on the same field, they should be counted as two\n      // separate segments in an index.\n      if (\n        subFilter.op === Operator.ARRAY_CONTAINS ||\n        subFilter.op === Operator.ARRAY_CONTAINS_ANY\n      ) {\n        hasArraySegment = true;\n      } else {\n        fields = fields.add(subFilter.field);\n      }\n    }\n  }\n\n  for (const orderBy of target.orderBy) {\n    // __name__ is not an explicit segment of any index, so we don't need to\n    // count it.\n    if (!orderBy.field.isKeyField()) {\n      fields = fields.add(orderBy.field);\n    }\n  }\n\n  return fields.size + (hasArraySegment ? 1 : 0);\n}\n\nexport function targetHasLimit(target: Target): boolean {\n  return target.limit !== null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { compareDocumentsByField, Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { debugAssert, debugCast, fail } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n  Bound,\n  boundSortsAfterDocument,\n  boundSortsBeforeDocument\n} from './bound';\nimport { FieldFilter, Filter } from './filter';\nimport { Direction, OrderBy } from './order_by';\nimport {\n  canonifyTarget,\n  newTarget,\n  stringifyTarget,\n  Target,\n  targetEquals\n} from './target';\n\nexport const enum LimitType {\n  First = 'F',\n  Last = 'L'\n}\n\n/**\n * The Query interface defines all external properties of a query.\n *\n * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy`\n * and `queryToTarget`.\n */\nexport interface Query {\n  readonly path: ResourcePath;\n  readonly collectionGroup: string | null;\n  readonly explicitOrderBy: OrderBy[];\n  readonly filters: Filter[];\n  readonly limit: number | null;\n  readonly limitType: LimitType;\n  readonly startAt: Bound | null;\n  readonly endAt: Bound | null;\n}\n\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nexport class QueryImpl implements Query {\n  memoizedNormalizedOrderBy: OrderBy[] | null = null;\n\n  // The corresponding `Target` of this `Query` instance, for use with\n  // non-aggregate queries.\n  memoizedTarget: Target | null = null;\n\n  // The corresponding `Target` of this `Query` instance, for use with\n  // aggregate queries. Unlike targets for non-aggregate queries,\n  // aggregate query targets do not contain normalized order-bys, they only\n  // contain explicit order-bys.\n  memoizedAggregateTarget: Target | null = null;\n\n  /**\n   * Initializes a Query with a path and optional additional query constraints.\n   * Path must currently be empty if this is a collection group query.\n   */\n  constructor(\n    readonly path: ResourcePath,\n    readonly collectionGroup: string | null = null,\n    readonly explicitOrderBy: OrderBy[] = [],\n    readonly filters: Filter[] = [],\n    readonly limit: number | null = null,\n    readonly limitType: LimitType = LimitType.First,\n    readonly startAt: Bound | null = null,\n    readonly endAt: Bound | null = null\n  ) {\n    if (this.startAt) {\n      debugAssert(\n        this.startAt.position.length <= queryNormalizedOrderBy(this).length,\n        'Bound is longer than orderBy'\n      );\n    }\n    if (this.endAt) {\n      debugAssert(\n        this.endAt.position.length <= queryNormalizedOrderBy(this).length,\n        'Bound is longer than orderBy'\n      );\n    }\n  }\n}\n\n/** Creates a new Query instance with the options provided. */\nexport function newQuery(\n  path: ResourcePath,\n  collectionGroup: string | null,\n  explicitOrderBy: OrderBy[],\n  filters: Filter[],\n  limit: number | null,\n  limitType: LimitType,\n  startAt: Bound | null,\n  endAt: Bound | null\n): Query {\n  return new QueryImpl(\n    path,\n    collectionGroup,\n    explicitOrderBy,\n    filters,\n    limit,\n    limitType,\n    startAt,\n    endAt\n  );\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */\nexport function newQueryForPath(path: ResourcePath): Query {\n  return new QueryImpl(path);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\nexport function asCollectionQueryAtPath(\n  query: Query,\n  path: ResourcePath\n): Query {\n  return new QueryImpl(\n    path,\n    /*collectionGroup=*/ null,\n    query.explicitOrderBy.slice(),\n    query.filters.slice(),\n    query.limit,\n    query.limitType,\n    query.startAt,\n    query.endAt\n  );\n}\n\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nexport function queryMatchesAllDocuments(query: Query): boolean {\n  return (\n    query.filters.length === 0 &&\n    query.limit === null &&\n    query.startAt == null &&\n    query.endAt == null &&\n    (query.explicitOrderBy.length === 0 ||\n      (query.explicitOrderBy.length === 1 &&\n        query.explicitOrderBy[0].field.isKeyField()))\n  );\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\nexport function getInequalityFilterFields(query: Query): SortedSet<FieldPath> {\n  let result = new SortedSet<FieldPath>(FieldPath.comparator);\n  query.filters.forEach((filter: Filter) => {\n    const subFilters = filter.getFlattenedFilters();\n    subFilters.forEach((filter: FieldFilter) => {\n      if (filter.isInequality()) {\n        result = result.add(filter.field);\n      }\n    });\n  });\n  return result;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\nexport function newQueryForCollectionGroup(collectionId: string): Query {\n  return new QueryImpl(ResourcePath.emptyPath(), collectionId);\n}\n\n/**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\nexport function isDocumentQuery(query: Query): boolean {\n  return (\n    DocumentKey.isDocumentKey(query.path) &&\n    query.collectionGroup === null &&\n    query.filters.length === 0\n  );\n}\n\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nexport function isCollectionGroupQuery(query: Query): boolean {\n  return query.collectionGroup !== null;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */\nexport function queryNormalizedOrderBy(query: Query): OrderBy[] {\n  const queryImpl = debugCast(query, QueryImpl);\n  if (queryImpl.memoizedNormalizedOrderBy === null) {\n    queryImpl.memoizedNormalizedOrderBy = [];\n    const fieldsNormalized = new Set<string>();\n\n    // Any explicit order by fields should be added as is.\n    for (const orderBy of queryImpl.explicitOrderBy) {\n      queryImpl.memoizedNormalizedOrderBy.push(orderBy);\n      fieldsNormalized.add(orderBy.field.canonicalString());\n    }\n\n    // The order of the implicit ordering always matches the last explicit order by.\n    const lastDirection =\n      queryImpl.explicitOrderBy.length > 0\n        ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir\n        : Direction.ASCENDING;\n\n    // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n    // order. When there are multiple inequality filters on the same field, the field should be added\n    // only once.\n    // Note: `SortedSet<FieldPath>` sorts the key field before other fields. However, we want the key\n    // field to be sorted last.\n    const inequalityFields: SortedSet<FieldPath> =\n      getInequalityFilterFields(queryImpl);\n    inequalityFields.forEach(field => {\n      if (\n        !fieldsNormalized.has(field.canonicalString()) &&\n        !field.isKeyField()\n      ) {\n        queryImpl.memoizedNormalizedOrderBy!.push(\n          new OrderBy(field, lastDirection)\n        );\n      }\n    });\n\n    // Add the document key field to the last if it is not explicitly ordered.\n    if (!fieldsNormalized.has(FieldPath.keyField().canonicalString())) {\n      queryImpl.memoizedNormalizedOrderBy.push(\n        new OrderBy(FieldPath.keyField(), lastDirection)\n      );\n    }\n  }\n  return queryImpl.memoizedNormalizedOrderBy;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */\nexport function queryToTarget(query: Query): Target {\n  const queryImpl = debugCast(query, QueryImpl);\n  if (!queryImpl.memoizedTarget) {\n    queryImpl.memoizedTarget = _queryToTarget(\n      queryImpl,\n      queryNormalizedOrderBy(query)\n    );\n  }\n\n  return queryImpl.memoizedTarget;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */\nexport function queryToAggregateTarget(query: Query): Target {\n  const queryImpl = debugCast(query, QueryImpl);\n\n  if (!queryImpl.memoizedAggregateTarget) {\n    // Do not include implicit order-bys for aggregate queries.\n    queryImpl.memoizedAggregateTarget = _queryToTarget(\n      queryImpl,\n      query.explicitOrderBy\n    );\n  }\n\n  return queryImpl.memoizedAggregateTarget;\n}\n\nfunction _queryToTarget(queryImpl: QueryImpl, orderBys: OrderBy[]): Target {\n  if (queryImpl.limitType === LimitType.First) {\n    return newTarget(\n      queryImpl.path,\n      queryImpl.collectionGroup,\n      orderBys,\n      queryImpl.filters,\n      queryImpl.limit,\n      queryImpl.startAt,\n      queryImpl.endAt\n    );\n  } else {\n    // Flip the orderBy directions since we want the last results\n    orderBys = orderBys.map(orderBy => {\n      const dir =\n        orderBy.dir === Direction.DESCENDING\n          ? Direction.ASCENDING\n          : Direction.DESCENDING;\n      return new OrderBy(orderBy.field, dir);\n    });\n\n    // We need to swap the cursors to match the now-flipped query ordering.\n    const startAt = queryImpl.endAt\n      ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)\n      : null;\n    const endAt = queryImpl.startAt\n      ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)\n      : null;\n\n    // Now return as a LimitType.First query.\n    return newTarget(\n      queryImpl.path,\n      queryImpl.collectionGroup,\n      orderBys,\n      queryImpl.filters,\n      queryImpl.limit,\n      startAt,\n      endAt\n    );\n  }\n}\n\nexport function queryWithAddedFilter(query: Query, filter: Filter): Query {\n  debugAssert(\n    !isDocumentQuery(query),\n    'No filtering allowed for document query'\n  );\n\n  const newFilters = query.filters.concat([filter]);\n  return new QueryImpl(\n    query.path,\n    query.collectionGroup,\n    query.explicitOrderBy.slice(),\n    newFilters,\n    query.limit,\n    query.limitType,\n    query.startAt,\n    query.endAt\n  );\n}\n\nexport function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query {\n  debugAssert(\n    !query.startAt && !query.endAt,\n    'Bounds must be set after orderBy'\n  );\n  // TODO(dimond): validate that orderBy does not list the same key twice.\n  const newOrderBy = query.explicitOrderBy.concat([orderBy]);\n  return new QueryImpl(\n    query.path,\n    query.collectionGroup,\n    newOrderBy,\n    query.filters.slice(),\n    query.limit,\n    query.limitType,\n    query.startAt,\n    query.endAt\n  );\n}\n\nexport function queryWithLimit(\n  query: Query,\n  limit: number | null,\n  limitType: LimitType\n): Query {\n  return new QueryImpl(\n    query.path,\n    query.collectionGroup,\n    query.explicitOrderBy.slice(),\n    query.filters.slice(),\n    limit,\n    limitType,\n    query.startAt,\n    query.endAt\n  );\n}\n\nexport function queryWithStartAt(query: Query, bound: Bound): Query {\n  return new QueryImpl(\n    query.path,\n    query.collectionGroup,\n    query.explicitOrderBy.slice(),\n    query.filters.slice(),\n    query.limit,\n    query.limitType,\n    bound,\n    query.endAt\n  );\n}\n\nexport function queryWithEndAt(query: Query, bound: Bound): Query {\n  return new QueryImpl(\n    query.path,\n    query.collectionGroup,\n    query.explicitOrderBy.slice(),\n    query.filters.slice(),\n    query.limit,\n    query.limitType,\n    query.startAt,\n    bound\n  );\n}\n\nexport function queryEquals(left: Query, right: Query): boolean {\n  return (\n    targetEquals(queryToTarget(left), queryToTarget(right)) &&\n    left.limitType === right.limitType\n  );\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nexport function canonifyQuery(query: Query): string {\n  return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;\n}\n\nexport function stringifyQuery(query: Query): string {\n  return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${\n    query.limitType\n  })`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */\nexport function queryMatches(query: Query, doc: Document): boolean {\n  return (\n    doc.isFoundDocument() &&\n    queryMatchesPathAndCollectionGroup(query, doc) &&\n    queryMatchesOrderBy(query, doc) &&\n    queryMatchesFilters(query, doc) &&\n    queryMatchesBounds(query, doc)\n  );\n}\n\nfunction queryMatchesPathAndCollectionGroup(\n  query: Query,\n  doc: Document\n): boolean {\n  const docPath = doc.key.path;\n  if (query.collectionGroup !== null) {\n    // NOTE: this.path is currently always empty since we don't expose Collection\n    // Group queries rooted at a document path yet.\n    return (\n      doc.key.hasCollectionId(query.collectionGroup) &&\n      query.path.isPrefixOf(docPath)\n    );\n  } else if (DocumentKey.isDocumentKey(query.path)) {\n    // exact match for document queries\n    return query.path.isEqual(docPath);\n  } else {\n    // shallow ancestor queries by default\n    return query.path.isImmediateParentOf(docPath);\n  }\n}\n\n/**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\nfunction queryMatchesOrderBy(query: Query, doc: Document): boolean {\n  // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n  // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n  // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n  // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n  // A document with content of {b:1} matches the filters, but does not match the orderBy because\n  // it's missing the field 'a'.\n  for (const orderBy of queryNormalizedOrderBy(query)) {\n    // order-by key always matches\n    if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {\n      return false;\n    }\n  }\n  return true;\n}\n\nfunction queryMatchesFilters(query: Query, doc: Document): boolean {\n  for (const filter of query.filters) {\n    if (!filter.matches(doc)) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/** Makes sure a document is within the bounds, if provided. */\nfunction queryMatchesBounds(query: Query, doc: Document): boolean {\n  if (\n    query.startAt &&\n    !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)\n  ) {\n    return false;\n  }\n  if (\n    query.endAt &&\n    !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)\n  ) {\n    return false;\n  }\n  return true;\n}\n\n/**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */\nexport function queryCollectionGroup(query: Query): string {\n  return (\n    query.collectionGroup ||\n    (query.path.length % 2 === 1\n      ? query.path.lastSegment()\n      : query.path.get(query.path.length - 2))\n  );\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */\nexport function newQueryComparator(\n  query: Query\n): (d1: Document, d2: Document) => number {\n  return (d1: Document, d2: Document): number => {\n    let comparedOnKeyField = false;\n    for (const orderBy of queryNormalizedOrderBy(query)) {\n      const comp = compareDocs(orderBy, d1, d2);\n      if (comp !== 0) {\n        return comp;\n      }\n      comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n    }\n    // Assert that we actually compared by key\n    debugAssert(\n      comparedOnKeyField,\n      \"orderBy used that doesn't compare on key field\"\n    );\n    return 0;\n  };\n}\n\nexport function compareDocs(\n  orderBy: OrderBy,\n  d1: Document,\n  d2: Document\n): number {\n  const comparison = orderBy.field.isKeyField()\n    ? DocumentKey.comparator(d1.key, d2.key)\n    : compareDocumentsByField(orderBy.field, d1, d2);\n  switch (orderBy.dir) {\n    case Direction.ASCENDING:\n      return comparison;\n    case Direction.DESCENDING:\n      return -1 * comparison;\n    default:\n      return fail(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 { 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { forEach, isEmpty } from './obj';\n\ntype Entry<K, V> = [K, V];\n\n/**\n * A map implementation that uses objects as keys. Objects must have an\n * associated equals function and must be immutable. Entries in the map are\n * stored together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nexport class ObjectMap<KeyType, ValueType> {\n  /**\n   * The inner map for a key/value pair. Due to the possibility of collisions we\n   * keep a list of entries that we do a linear search through to find an actual\n   * match. Note that collisions should be rare, so we still expect near\n   * constant time lookups in practice.\n   */\n  private inner: {\n    [canonicalId: string]: Array<Entry<KeyType, ValueType>>;\n  } = {};\n\n  /** The number of entries stored in the map */\n  private innerSize = 0;\n\n  constructor(\n    private mapKeyFn: (key: KeyType) => string,\n    private equalsFn: (l: KeyType, r: KeyType) => boolean\n  ) {}\n\n  /** Get a value for this key, or undefined if it does not exist. */\n  get(key: KeyType): ValueType | undefined {\n    const id = this.mapKeyFn(key);\n    const matches = this.inner[id];\n    if (matches === undefined) {\n      return undefined;\n    }\n    for (const [otherKey, value] of matches) {\n      if (this.equalsFn(otherKey, key)) {\n        return value;\n      }\n    }\n    return undefined;\n  }\n\n  has(key: KeyType): boolean {\n    return this.get(key) !== undefined;\n  }\n\n  /** Put this key and value in the map. */\n  set(key: KeyType, value: ValueType): void {\n    const id = this.mapKeyFn(key);\n    const matches = this.inner[id];\n    if (matches === undefined) {\n      this.inner[id] = [[key, value]];\n      this.innerSize++;\n      return;\n    }\n    for (let i = 0; i < matches.length; i++) {\n      if (this.equalsFn(matches[i][0], key)) {\n        // This is updating an existing entry and does not increase `innerSize`.\n        matches[i] = [key, value];\n        return;\n      }\n    }\n    matches.push([key, value]);\n    this.innerSize++;\n  }\n\n  /**\n   * Remove this key from the map. Returns a boolean if anything was deleted.\n   */\n  delete(key: KeyType): boolean {\n    const id = this.mapKeyFn(key);\n    const matches = this.inner[id];\n    if (matches === undefined) {\n      return false;\n    }\n    for (let i = 0; i < matches.length; i++) {\n      if (this.equalsFn(matches[i][0], key)) {\n        if (matches.length === 1) {\n          delete this.inner[id];\n        } else {\n          matches.splice(i, 1);\n        }\n        this.innerSize--;\n        return true;\n      }\n    }\n    return false;\n  }\n\n  forEach(fn: (key: KeyType, val: ValueType) => void): void {\n    forEach(this.inner, (_, entries) => {\n      for (const [k, v] of entries) {\n        fn(k, v);\n      }\n    });\n  }\n\n  isEmpty(): boolean {\n    return isEmpty(this.inner);\n  }\n\n  size(): number {\n    return this.innerSize;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { OverlayedDocument } from '../local/overlayed_document';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { Mutation } from './mutation';\nimport { Overlay } from './overlay';\n\n/** Miscellaneous collection types / constants. */\n\nexport type MutableDocumentMap = SortedMap<DocumentKey, MutableDocument>;\nconst EMPTY_MUTABLE_DOCUMENT_MAP = new SortedMap<DocumentKey, MutableDocument>(\n  DocumentKey.comparator\n);\nexport function mutableDocumentMap(): MutableDocumentMap {\n  return EMPTY_MUTABLE_DOCUMENT_MAP;\n}\n\nexport interface DocumentSizeEntries {\n  documents: MutableDocumentMap;\n  sizeMap: SortedMap<DocumentKey, number>;\n}\n\nexport type DocumentMap = SortedMap<DocumentKey, Document>;\nconst EMPTY_DOCUMENT_MAP = new SortedMap<DocumentKey, Document>(\n  DocumentKey.comparator\n);\nexport function documentMap(...docs: Document[]): DocumentMap {\n  let map = EMPTY_DOCUMENT_MAP;\n  for (const doc of docs) {\n    map = map.insert(doc.key, doc);\n  }\n  return map;\n}\n\nexport type OverlayedDocumentMap = DocumentKeyMap<OverlayedDocument>;\nexport function newOverlayedDocumentMap(): OverlayedDocumentMap {\n  return newDocumentKeyMap<OverlayedDocument>();\n}\n\nexport function convertOverlayedDocumentMapToDocumentMap(\n  collection: OverlayedDocumentMap\n): DocumentMap {\n  let documents = EMPTY_DOCUMENT_MAP;\n  collection.forEach(\n    (k, v) => (documents = documents.insert(k, v.overlayedDocument))\n  );\n  return documents;\n}\n\nexport type OverlayMap = DocumentKeyMap<Overlay>;\nexport function newOverlayMap(): OverlayMap {\n  return newDocumentKeyMap<Overlay>();\n}\n\nexport type MutationMap = DocumentKeyMap<Mutation>;\nexport function newMutationMap(): MutationMap {\n  return newDocumentKeyMap<Mutation>();\n}\n\nexport type DocumentKeyMap<T> = ObjectMap<DocumentKey, T>;\nexport function newDocumentKeyMap<T>(): DocumentKeyMap<T> {\n  return new ObjectMap<DocumentKey, T>(\n    key => key.toString(),\n    (l, r) => l.isEqual(r)\n  );\n}\n\nexport type DocumentVersionMap = SortedMap<DocumentKey, SnapshotVersion>;\nconst EMPTY_DOCUMENT_VERSION_MAP = new SortedMap<DocumentKey, SnapshotVersion>(\n  DocumentKey.comparator\n);\nexport function documentVersionMap(): DocumentVersionMap {\n  return EMPTY_DOCUMENT_VERSION_MAP;\n}\n\nexport type DocumentKeySet = SortedSet<DocumentKey>;\nconst EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator);\nexport function documentKeySet(...keys: DocumentKey[]): DocumentKeySet {\n  let set = EMPTY_DOCUMENT_KEY_SET;\n  for (const key of keys) {\n    set = set.add(key);\n  }\n  return set;\n}\n\nexport type TargetIdSet = SortedSet<TargetId>;\nconst EMPTY_TARGET_ID_SET = new SortedSet<TargetId>(primitiveComparator);\nexport function targetIdSet(): SortedSet<TargetId> {\n  return EMPTY_TARGET_ID_SET;\n}\n","/**\n * @license\n * Copyright 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 { RemoteTargetId, 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<T extends TargetId | RemoteTargetId = TargetId> {\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<T, TargetChange>,\n    /**\n     * A map of targets that is known to be inconsistent, and the purpose for\n     * re-listening. Listens for these targets should be re-established without\n     * resume tokens.\n     */\n    readonly targetMismatches: SortedMap<T, TargetPurpose>,\n    /**\n     * A set of which documents have changed or been deleted, along with the\n     * doc's new values (if not deleted).\n     */\n    readonly documentUpdates: MutableDocumentMap,\n    /**\n     * A set of which augmented documents (pipeline) have changed or been deleted, along with the\n     * doc's new values (if not deleted).\n     */\n    readonly augmentedDocumentUpdates: 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<TargetId> {\n    const targetChanges = new Map<TargetId, TargetChange>();\n    targetChanges.set(\n      targetId,\n      TargetChange.createSynthesizedTargetChangeForCurrentChange(\n        targetId,\n        current,\n        resumeToken\n      )\n    );\n    return new RemoteEvent<TargetId>(\n      SnapshotVersion.min(),\n      targetChanges,\n      new SortedMap<TargetId, TargetPurpose>(primitiveComparator),\n      mutableDocumentMap(),\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 type { CorePipeline } from '../core/pipeline';\nimport type { TargetOrPipeline } from '../core/pipeline-util';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, targetIsPipelineTarget } from '../core/target';\nimport { RemoteTargetId } 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 { ResourcePath } from '../model/path';\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: RemoteTargetId[],\n    /** The new document is removed from all of these targets. */\n    public removedTargetIds: RemoteTargetId[],\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: RemoteTargetId,\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: RemoteTargetId[],\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. */\nexport class TargetState {\n  /**\n   * Track the targetId for logging.\n   */\n  constructor(private targetId: RemoteTargetId) {}\n\n  /**\n   * The number of pending responses (adds or removes) that we are waiting on.\n   * We only consider targets active that have no pending responses.\n   */\n  private pendingResponses = 0;\n\n  /**\n   * Keeps track of the document changes since the last raised snapshot.\n   *\n   * These changes are continuously updated as we receive document updates and\n   * always reflect the current set of changes against the last issued snapshot.\n   */\n  private documentChanges: SortedMap<DocumentKey, ChangeType> =\n    snapshotChangesMap();\n\n  /** See public getters for explanations of these fields. */\n  private _resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING;\n  private _current = false;\n\n  /**\n   * Whether this target state should be included in the next snapshot. We\n   * initialize to true so that newly-added targets are included in the next\n   * RemoteEvent.\n   */\n  private _hasPendingChanges = true;\n\n  /**\n   * Whether this target has been marked 'current'.\n   *\n   * 'Current' has special meaning in the RPC protocol: It implies that the\n   * Watch backend has sent us all changes up to the point at which the target\n   * was added and that the target is consistent with the rest of the watch\n   * stream.\n   */\n  get current(): boolean {\n    return this._current;\n  }\n\n  /** The last resume token sent to us for this target. */\n  get resumeToken(): ByteString {\n    return this._resumeToken;\n  }\n\n  /** Whether this target has pending target adds or target removes. */\n  get isPending(): boolean {\n    return this.pendingResponses !== 0;\n  }\n\n  /** Whether we have modified any state that should trigger a snapshot. */\n  get hasPendingChanges(): boolean {\n    return this._hasPendingChanges;\n  }\n\n  /**\n   * Applies the resume token to the TargetChange, but only when it has a new\n   * value. Empty resumeTokens are discarded.\n   */\n  updateResumeToken(resumeToken: ByteString): void {\n    if (resumeToken.approximateByteSize() > 0) {\n      this._hasPendingChanges = true;\n      this._resumeToken = resumeToken;\n    }\n  }\n\n  /**\n   * Creates a target change from the current set of changes.\n   *\n   * To reset the document changes after raising this snapshot, call\n   * `clearPendingChanges()`.\n   */\n  toTargetChange(): TargetChange {\n    let addedDocuments = documentKeySet();\n    let modifiedDocuments = documentKeySet();\n    let removedDocuments = documentKeySet();\n\n    this.documentChanges.forEach((key, changeType) => {\n      switch (changeType) {\n        case ChangeType.Added:\n          addedDocuments = addedDocuments.add(key);\n          break;\n        case ChangeType.Modified:\n          modifiedDocuments = modifiedDocuments.add(key);\n          break;\n        case ChangeType.Removed:\n          removedDocuments = removedDocuments.add(key);\n          break;\n        default:\n          fail(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, targetId: this.targetId }\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: RemoteTargetId): DocumentKeySet;\n\n  /**\n   * Returns the TargetData for an active target ID or 'null' if this target\n   * has become inactive\n   */\n  getTargetDataForTarget(\n    targetId: RemoteTargetId\n  ): TargetData<RemoteTargetId> | 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  /**\n   * The internal state of all tracked targets.\n   *\n   * Targets have the following lifecycle of [states] within the WatchChangeAggregator:\n   * [unknown] -> recordPendingTargetRequest(t)\n   *           -> [pending]\n   *           -> handleTargetChange(t, Added)\n   *           -> [added / !pending]\n   *           -> recordPendingTargetRequest(t)\n   *           -> [pending]\n   *           -> handleTargetChange(t, Removed)\n   *           -> [unknown]\n   *\n   * A reset on an [added] target leaves the target in an [added] state.\n   * [added / !pending] -> handleTargetChange(t, Reset)\n   *                    -> [added / !pending]\n   *\n   * [active]: is a substate of [added], where also `remoteStore.listenTargets.has(t) === true`.\n   *           Generally it is expected that when a target is [active / !pending]\n   *           then it is also [active], but the implementation does not guarantee\n   *           this will always be true.\n   *\n   */\n  private targetStates = new Map<RemoteTargetId, TargetState>();\n\n  /** Keeps track of the documents to update since the last raised snapshot. */\n  private pendingDocumentUpdates = mutableDocumentMap();\n  private pendingDocumentUpdatesByTarget = documentTargetMap();\n\n  /** Keeps track of the augmented documents to update since the last raised snapshot. */\n  private pendingAugmentedDocumentUpdates = mutableDocumentMap();\n\n  /** A mapping of document keys to their set of target IDs. */\n  private pendingDocumentTargetMapping = documentTargetMap();\n\n  /**\n   * A map of targets with existence filter mismatches. These targets are\n   * known to be inconsistent and their listens needs to be re-established by\n   * RemoteStore.\n   */\n  private pendingTargetResets = new SortedMap<RemoteTargetId, TargetPurpose>(\n    primitiveComparator\n  );\n\n  /**\n   * Processes and adds the DocumentWatchChange to the current set of changes.\n   */\n  handleDocumentChange(docChange: DocumentWatchChange): void {\n    for (const targetId of docChange.updatedTargetIds) {\n      if (docChange.newDoc && docChange.newDoc.isFoundDocument()) {\n        this.addDocumentToTarget(targetId, docChange.newDoc);\n      } else {\n        this.removeDocumentFromTarget(\n          targetId,\n          docChange.key,\n          docChange.newDoc\n        );\n      }\n    }\n\n    for (const targetId of docChange.removedTargetIds) {\n      this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc);\n    }\n  }\n\n  /** Processes and adds the WatchTargetChange to the current set of changes. */\n  handleTargetChange(targetChange: WatchTargetChange): void {\n    this.forEachTarget(targetChange, targetId => {\n      const targetState = this.targetStates.get(targetId);\n\n      // skip unknown target state, this indicates the target change is for\n      // an old target\n      if (!targetState) {\n        logDebug(\n          LOG_TAG,\n          `handleTargetChange received targetChange for untracked target ID (${targetId}) with state (${targetChange.state})`\n        );\n        return;\n      }\n\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: RemoteTargetId) => 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  isSingleDocumentTarget(target: TargetOrPipeline): boolean {\n    if (targetIsPipelineTarget(target)) {\n      return (\n        target.getPipelineSourceType() === 'documents' &&\n        target.getPipelineDocuments()?.length === 1\n      );\n    }\n\n    return targetIsDocumentTarget(target);\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 (!this.isSingleDocumentTarget(target)) {\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      } else {\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(\n            targetIsPipelineTarget(target)\n              ? ResourcePath.fromString(target.getPipelineDocuments()![0])\n              : target.path\n          );\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: ' + expectedCount\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: RemoteTargetId\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(\n    snapshotVersion: SnapshotVersion\n  ): RemoteEvent<RemoteTargetId> {\n    const targetChanges = new Map<RemoteTargetId, TargetChange>();\n\n    this.targetStates.forEach((targetState, targetId) => {\n      const targetData = this.targetDataForActiveTarget(targetId);\n      if (targetData) {\n        if (\n          targetState.current &&\n          this.isSingleDocumentTarget(targetData.target)\n        ) {\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 path = targetIsPipelineTarget(targetData.target)\n            ? ResourcePath.fromString(\n                targetData.target.getPipelineDocuments()![0]\n              )\n            : targetData.target.path;\n          const key = new DocumentKey(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    this.pendingAugmentedDocumentUpdates.forEach((_, doc) =>\n      doc.setReadTime(snapshotVersion)\n    );\n\n    const remoteEvent = new RemoteEvent(\n      snapshotVersion,\n      targetChanges,\n      this.pendingTargetResets,\n      this.pendingDocumentUpdates,\n      this.pendingAugmentedDocumentUpdates,\n      resolvedLimboDocuments\n    );\n\n    this.pendingDocumentUpdates = mutableDocumentMap();\n    this.pendingDocumentUpdatesByTarget = documentTargetMap();\n    this.pendingAugmentedDocumentUpdates = mutableDocumentMap();\n    this.pendingDocumentTargetMapping = documentTargetMap();\n    this.pendingTargetResets = new SortedMap<RemoteTargetId, TargetPurpose>(\n      primitiveComparator\n    );\n\n    return remoteEvent;\n  }\n\n  /**\n   * Adds the provided document to the internal list of document updates and\n   * its document key to the given target's mapping.\n   */\n  // Visible for testing.\n  addDocumentToTarget(\n    targetId: RemoteTargetId,\n    document: MutableDocument\n  ): void {\n    const targetState = this.targetStates.get(targetId);\n\n    // skip unknown or inactive targets\n    if (!targetState || !this.isActiveTarget(targetId)) {\n      logDebug(\n        LOG_TAG,\n        `addDocumentToTarget received document for unknown inactive target (${targetId})`\n      );\n      return;\n    }\n\n    const changeType = this.targetContainsDocument(targetId, document.key)\n      ? ChangeType.Modified\n      : ChangeType.Added;\n\n    targetState.addDocumentChange(document.key, changeType);\n\n    if (\n      targetIsPipelineTarget(\n        this.targetDataForActiveTarget(targetId)!.target\n      ) &&\n      (\n        this.targetDataForActiveTarget(targetId)!.target as CorePipeline\n      ).getPipelineFlavor() !== 'exact'\n    ) {\n      this.pendingAugmentedDocumentUpdates =\n        this.pendingAugmentedDocumentUpdates.insert(document.key, document);\n    } else {\n      this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(\n        document.key,\n        document\n      );\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: RemoteTargetId,\n    key: DocumentKey,\n    updatedDocument: MutableDocument | null\n  ): void {\n    const targetState = this.targetStates.get(targetId);\n\n    // skip unknown target state, this indicates the target change is for\n    // an old target\n    if (!targetState || !this.isActiveTarget(targetId)) {\n      logDebug(\n        LOG_TAG,\n        `removeDocumentFromTarget received document for unknown or inactive target (${targetId})`\n      );\n      return;\n    }\n\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      if (\n        targetIsPipelineTarget(\n          this.targetDataForActiveTarget(targetId)!.target\n        ) &&\n        (\n          this.targetDataForActiveTarget(targetId)!.target as CorePipeline\n        ).getPipelineFlavor() !== 'exact'\n      ) {\n        this.pendingAugmentedDocumentUpdates =\n          this.pendingAugmentedDocumentUpdates.insert(key, updatedDocument);\n      } else {\n        this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(\n          key,\n          updatedDocument\n        );\n      }\n    }\n  }\n\n  removeTarget(targetId: RemoteTargetId): 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: RemoteTargetId): number {\n    const targetState = this.targetStates.get(targetId);\n\n    // skip unknown target state\n    if (!targetState) {\n      return 0;\n    }\n\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: RemoteTargetId): void {\n    // For each request we get we need to record we need a response for it.\n    let targetState = this.targetStates.get(targetId);\n    if (!targetState) {\n      logDebug(\n        LOG_TAG,\n        `recordPendingTargetRequest set up tracking for target ID ${targetId}`\n      );\n      targetState = new TargetState(targetId);\n      this.targetStates.set(targetId, targetState);\n    }\n    targetState.recordPendingTargetRequest();\n  }\n\n  private ensureDocumentTargetMapping(\n    key: DocumentKey\n  ): SortedSet<RemoteTargetId> {\n    let targetMapping = this.pendingDocumentTargetMapping.get(key);\n\n    if (!targetMapping) {\n      targetMapping = new SortedSet<RemoteTargetId>(primitiveComparator);\n      this.pendingDocumentTargetMapping =\n        this.pendingDocumentTargetMapping.insert(key, targetMapping);\n    }\n\n    return targetMapping;\n  }\n\n  private ensureDocumentUpdateByTarget(\n    key: DocumentKey\n  ): SortedSet<RemoteTargetId> {\n    let targetMapping = this.pendingDocumentUpdatesByTarget.get(key);\n\n    if (!targetMapping) {\n      targetMapping = new SortedSet<RemoteTargetId>(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: RemoteTargetId): 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(\n    targetId: RemoteTargetId\n  ): TargetData<RemoteTargetId> | null {\n    const targetState = this.targetStates.get(targetId);\n    return targetState === undefined || 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: RemoteTargetId): void {\n    debugAssert(\n      !this.targetStates.get(targetId)!.isPending,\n      'Should only reset active targets'\n    );\n    this.targetStates.set(targetId, new TargetState(targetId));\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  /**\n   * Returns whether the LocalStore considers the document to be part of the\n   * specified target.\n   */\n  private targetContainsDocument(\n    targetId: RemoteTargetId,\n    key: DocumentKey\n  ): boolean {\n    const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n    return existingKeys.has(key);\n  }\n}\n\nfunction documentTargetMap(): SortedMap<\n  DocumentKey,\n  SortedSet<RemoteTargetId>\n> {\n  return new SortedMap<DocumentKey, SortedSet<RemoteTargetId>>(\n    DocumentKey.comparator\n  );\n}\n\nfunction snapshotChangesMap(): SortedMap<DocumentKey, ChangeType> {\n  return new SortedMap<DocumentKey, ChangeType>(DocumentKey.comparator);\n}\n\nfunction createExistenceFilterMismatchInfoForTestingHooks(\n  localCacheCount: number,\n  existenceFilter: ExistenceFilter,\n  databaseId: DatabaseId,\n  bloomFilter: BloomFilter | null,\n  bloomFilterStatus: BloomFilterApplicationStatus\n): TestingHooksExistenceFilterMismatchInfo {\n  const result: TestingHooksExistenceFilterMismatchInfo = {\n    localCacheCount,\n    existenceFilterCount: existenceFilter.count,\n    databaseId: databaseId.database,\n    projectId: databaseId.projectId\n  };\n\n  const unchangedNames = existenceFilter.unchangedNames;\n  if (unchangedNames) {\n    result.bloomFilter = {\n      applied: bloomFilterStatus === BloomFilterApplicationStatus.Success,\n      hashCount: unchangedNames?.hashCount ?? 0,\n      bitmapLength: unchangedNames?.bits?.bitmap?.length ?? 0,\n      padding: unchangedNames?.bits?.padding ?? 0,\n      mightContain: (value: string): boolean =>\n        bloomFilter?.mightContain(value) ?? false\n    };\n  }\n\n  return result;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Aggregate } from '../core/aggregate';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n  CompositeFilter,\n  compositeFilterIsFlatConjunction,\n  CompositeOperator,\n  FieldFilter,\n  Filter,\n  Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport { CorePipeline } from '../core/pipeline';\nimport {\n  LimitType,\n  newQuery,\n  newQueryForPath,\n  Query,\n  queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n  targetIsDocumentTarget,\n  Target,\n  targetIsPipelineTarget\n} from '../core/target';\nimport { RemoteTargetId } from '../core/types';\nimport { Bytes } from '../lite-api/bytes';\nimport { GeoPoint } from '../lite-api/geo_point';\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 { PipelineStreamElement } from '../model/pipeline_stream_element';\nimport {\n  ArrayRemoveTransformOperation,\n  ArrayUnionTransformOperation,\n  NumericIncrementTransformOperation,\n  NumericMaximumTransformOperation,\n  NumericMinimumTransformOperation,\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  PipelineQueryTarget as ProtoPipelineQueryTarget,\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  Value as ProtoValue,\n  MapValue as ProtoMapValue,\n  ExecutePipelineResponse as ProtoExecutePipelineResponse,\n  Pipeline as ProtoPipeline\n} from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExistenceFilter } from './existence_filter';\nimport { Serializer } from './number_serializer';\nimport { mapCodeFromRpcCode } from './rpc_error';\nimport {\n  DocumentWatchChange,\n  ExistenceFilterChange,\n  WatchChange,\n  WatchTargetChange,\n  WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n  const dirs: { [dir: string]: ProtoOrderDirection } = {};\n  dirs[Direction.ASCENDING] = 'ASCENDING';\n  dirs[Direction.DESCENDING] = 'DESCENDING';\n  return dirs;\n})();\n\nconst OPERATORS = (() => {\n  const ops: { [op: string]: ProtoFieldFilterOp } = {};\n  ops[Operator.LESS_THAN] = 'LESS_THAN';\n  ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';\n  ops[Operator.GREATER_THAN] = 'GREATER_THAN';\n  ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';\n  ops[Operator.EQUAL] = 'EQUAL';\n  ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';\n  ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';\n  ops[Operator.IN] = 'IN';\n  ops[Operator.NOT_IN] = 'NOT_IN';\n  ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';\n  return ops;\n})();\n\nconst COMPOSITE_OPERATORS = (() => {\n  const ops: { [op: string]: ProtoCompositeFilterOp } = {};\n  ops[CompositeOperator.AND] = 'AND';\n  ops[CompositeOperator.OR] = 'OR';\n  return ops;\n})();\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n  debugAssert(!isNullOrUndefined(value), description + ' is missing');\n}\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer implements Serializer {\n  constructor(\n    readonly databaseId: DatabaseId,\n    readonly useProto3Json: boolean\n  ) {}\n}\n\nfunction fromRpcStatus(status: ProtoStatus): FirestoreError {\n  const code =\n    status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);\n  return new FirestoreError(code, status.message || '');\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: <number> } struct.\n */\nexport function 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 fromPipelineResponse(\n  serializer: JsonProtoSerializer,\n  proto: ProtoExecutePipelineResponse,\n  document?: ProtoDocument\n): PipelineStreamElement {\n  const output: PipelineStreamElement = {};\n  if (proto.transaction?.length) {\n    output.transaction = proto.transaction;\n  }\n  const executionTime = proto.executionTime\n    ? fromVersion(proto.executionTime)\n    : undefined;\n  output.executionTime = executionTime;\n\n  if (!!document) {\n    output.key = document.name\n      ? fromName(serializer, document.name)\n      : undefined;\n\n    output.fields = new ObjectValue({ mapValue: { fields: document.fields } });\n\n    output.createTime = document.createTime\n      ? fromVersion(document.createTime!)\n      : undefined;\n    output.updateTime = document.updateTime\n      ? fromVersion(document.updateTime!)\n      : undefined;\n  }\n  return output;\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: RemoteTargetId[] = (change.targetChange.targetIds ||\n      []) as RemoteTargetId[];\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 || []) as RemoteTargetId[];\n    const removedTargetIds = (entityChange.removedTargetIds ||\n      []) as RemoteTargetId[];\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      []) as RemoteTargetId[];\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      []) as RemoteTargetId[];\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 as RemoteTargetId;\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 if (transform instanceof NumericMinimumTransformOperation) {\n    return {\n      fieldPath: fieldTransform.field.canonicalString(),\n      minimum: transform.operand\n    };\n  } else if (transform instanceof NumericMaximumTransformOperation) {\n    return {\n      fieldPath: fieldTransform.field.canonicalString(),\n      maximum: 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 if ('minimum' in proto) {\n    transform = new NumericMinimumTransformOperation(\n      serializer,\n      proto.minimum!\n    );\n  } else if ('maximum' in proto) {\n    transform = new NumericMaximumTransformOperation(\n      serializer,\n      proto.maximum!\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<string, string>;\n  parent: ResourcePath;\n} {\n  const { queryTarget, parent } = toQueryTarget(serializer, target);\n  const aliasMap: Record<string, string> = {};\n\n  const aggregations: ProtoAggregation[] = [];\n  let aggregationNum = 0;\n\n  aggregates.forEach(aggregate => {\n    // Map all client-side aliases to a unique short-form\n    // alias. This avoids issues with client-side aliases that\n    // exceed the 1500-byte string size limit.\n    const serverAlias = 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<number>\n): ProtoApiClientObjectMap<string> | null {\n  const value = toLabel(targetData.purpose);\n  if (value == null) {\n    return null;\n  } else {\n    return {\n      'goog-listen-tags': value\n    };\n  }\n}\n\nexport function toLabel(purpose: TargetPurpose): string | null {\n  switch (purpose) {\n    case TargetPurpose.Listen:\n      return null;\n    case TargetPurpose.ExistenceFilterMismatch:\n      return 'existence-filter-mismatch';\n    case TargetPurpose.ExistenceFilterMismatchBloom:\n      return 'existence-filter-mismatch-bloom';\n    case TargetPurpose.LimboResolution:\n      return 'limbo-document';\n    default:\n      return fail(0x713b, 'Unrecognized query purpose', { purpose });\n  }\n}\n\nexport function toPipelineTarget(\n  serializer: JsonProtoSerializer,\n  target: CorePipeline\n): ProtoPipelineQueryTarget {\n  return {\n    structuredPipeline: {\n      pipeline: {\n        stages: target.stages.map(s => s._toProto(serializer))\n      }\n    }\n  };\n}\n\nexport function toTarget(\n  serializer: JsonProtoSerializer,\n  targetData: TargetData<number>\n): ProtoTarget {\n  let result: ProtoTarget;\n  const target = targetData.target;\n  if (targetIsPipelineTarget(target)) {\n    result = {\n      pipelineQuery: toPipelineTarget(serializer, target as CorePipeline)\n    };\n  } else if (targetIsDocumentTarget(target as Target)) {\n    result = { documents: toDocumentsTarget(serializer, target as Target) };\n  } else {\n    result = { query: toQueryTarget(serializer, target as 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}\nexport interface ProtoSerializable<ProtoType> {\n  _toProto(serializer: JsonProtoSerializer): ProtoType;\n}\n\nexport interface ProtoValueSerializable extends ProtoSerializable<ProtoValue> {\n  // Supports runtime identification of the ProtoSerializable<ProtoValue> type.\n  _protoValueType: 'ProtoValue';\n}\n\nexport function isProtoValueSerializable(\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  value: any\n): value is ProtoValueSerializable {\n  return (\n    !!value &&\n    typeof value._toProto === 'function' &&\n    value._protoValueType === 'ProtoValue'\n  );\n}\n\nexport function toMapValue(\n  serializer: JsonProtoSerializer,\n  input: Map<string, ProtoSerializable<ProtoValue>>\n): ProtoValue {\n  const map: ProtoMapValue = { fields: {} };\n  input.forEach((exp: ProtoSerializable<ProtoValue>, key: string) => {\n    if (typeof key !== 'string') {\n      throw new Error(`Cannot encode map with non-string key: ${key}`);\n    }\n\n    map.fields![key] = exp._toProto(serializer)!;\n  });\n  return {\n    mapValue: map\n  };\n}\n\nexport function toNullValue(value: null): ProtoValue {\n  return { nullValue: 'NULL_VALUE' };\n}\n\nexport function toBooleanValue(value: boolean): ProtoValue {\n  return { booleanValue: value };\n}\n\nexport function toStringValue(value: string): ProtoValue {\n  return { stringValue: value };\n}\n\nexport function toPipelineValue(value: ProtoPipeline): ProtoValue {\n  return { pipelineValue: value };\n}\n\nexport function dateToTimestampValue(\n  serializer: JsonProtoSerializer,\n  value: Date\n): ProtoValue {\n  const timestamp = Timestamp.fromDate(value);\n  return {\n    timestampValue: toTimestamp(serializer, timestamp)\n  };\n}\n\nexport function timestampToTimestampValue(\n  serializer: JsonProtoSerializer,\n  value: Timestamp\n): ProtoValue {\n  // Firestore backend truncates precision down to microseconds. To ensure\n  // offline mode works the same in 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(serializer, timestamp)\n  };\n}\n\nexport function toGeoPointValue(value: GeoPoint): ProtoValue {\n  return {\n    geoPointValue: {\n      latitude: value.latitude,\n      longitude: value.longitude\n    }\n  };\n}\n\nexport function toBytesValue(\n  serializer: JsonProtoSerializer,\n  value: Bytes\n): ProtoValue {\n  return { bytesValue: toBytes(serializer, value._byteString) };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 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<I, O> implements Stream<I, O> {\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 * @returns 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<fs.Stats>) => {\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<R>(\n  action: (callback: NodeCallback<R>) => void\n): Promise<R> {\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<R> {\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  apiKey: string | undefined\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  if (apiKey) {\n    metadata.set('X-Goog-Api-Key', apiKey);\n  }\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  /** made protected for testing */\n  protected 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<Req, Resp>(\n    rpcName: string,\n    path: ResourcePath,\n    request: Req,\n    authToken: Token | null,\n    appCheckToken: Token | null\n  ): Promise<Resp> {\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      this.databaseInfo.apiKey\n    );\n    const jsonRequest = { database: this.databasePath, ...request };\n\n    return nodePromise((callback: NodeCallback<Resp>) => {\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<Req, Resp>(\n    rpcName: string,\n    path: ResourcePath,\n    request: Req,\n    authToken: Token | null,\n    appCheckToken: Token | null,\n    expectedResponseCount?: number\n  ): Promise<Resp[]> {\n    const streamId = generateUniqueDebugId();\n    const results: Resp[] = [];\n    const responseDeferred = new Deferred<Resp[]>();\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      this.databaseInfo.apiKey\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<Req, Resp>(\n    rpcName: string,\n    authToken: Token | null,\n    appCheckToken: Token | null\n  ): Stream<Req, Resp> {\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      this.databaseInfo.apiKey\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<Req, Resp>({\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nconst LOG_TAG = 'ExponentialBackoff';\n\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nconst DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;\n\nconst DEFAULT_BACKOFF_FACTOR = 1.5;\n\n/** Maximum backoff time in milliseconds */\nconst DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;\n\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nexport class ExponentialBackoff {\n  private currentBaseMs: number = 0;\n  private timerPromise: DelayedOperation<void> | null = null;\n  /** The last backoff attempt, as epoch milliseconds. */\n  private lastAttemptTime = Date.now();\n\n  constructor(\n    /**\n     * The AsyncQueue to run backoff operations on.\n     */\n    private readonly queue: AsyncQueue,\n    /**\n     * The ID to use when scheduling backoff operations on the AsyncQueue.\n     */\n    private readonly timerId: TimerId,\n    /**\n     * The initial delay (used as the base delay on the first retry attempt).\n     * Note that jitter will still be applied, so the actual delay could be as\n     * little as 0.5*initialDelayMs.\n     */\n    private readonly initialDelayMs: number = DEFAULT_BACKOFF_INITIAL_DELAY_MS,\n    /**\n     * The multiplier to use to determine the extended base delay after each\n     * attempt.\n     */\n    private readonly backoffFactor: number = DEFAULT_BACKOFF_FACTOR,\n    /**\n     * The maximum base delay after which no further backoff is performed.\n     * Note that jitter will still be applied, so the actual delay could be as\n     * much as 1.5*maxDelayMs.\n     */\n    private readonly maxDelayMs: number = DEFAULT_BACKOFF_MAX_DELAY_MS\n  ) {\n    this.reset();\n  }\n\n  /**\n   * Resets the backoff delay.\n   *\n   * The very next backoffAndWait() will have no delay. If it is called again\n   * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n   * subsequent ones will increase according to the backoffFactor.\n   */\n  reset(): void {\n    this.currentBaseMs = 0;\n  }\n\n  /**\n   * Resets the backoff delay to the maximum delay (e.g. for use after a\n   * RESOURCE_EXHAUSTED error).\n   */\n  resetToMax(): void {\n    this.currentBaseMs = this.maxDelayMs;\n  }\n\n  /**\n   * Returns a promise that resolves after currentDelayMs, and increases the\n   * delay for any subsequent attempts. If there was a pending backoff operation\n   * already, it will be canceled.\n   */\n  backoffAndRun(op: () => Promise<void>): void {\n    // Cancel any pending backoff operation.\n    this.cancel();\n\n    // First schedule using the current base (which may be 0 and should be\n    // honored as such).\n    const desiredDelayWithJitterMs = Math.floor(\n      this.currentBaseMs + this.jitterDelayMs()\n    );\n\n    // Guard against lastAttemptTime being in the future due to a clock change.\n    const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\n\n    // Guard against the backoff delay already being past.\n    const remainingDelayMs = Math.max(\n      0,\n      desiredDelayWithJitterMs - delaySoFarMs\n    );\n\n    if (remainingDelayMs > 0) {\n      logDebug(\n        LOG_TAG,\n        `Backing off for ${remainingDelayMs} ms ` +\n          `(base delay: ${this.currentBaseMs} ms, ` +\n          `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +\n          `last attempt: ${delaySoFarMs} ms ago)`\n      );\n    }\n\n    this.timerPromise = this.queue.enqueueAfterDelay(\n      this.timerId,\n      remainingDelayMs,\n      () => {\n        this.lastAttemptTime = Date.now();\n        return op();\n      }\n    );\n\n    // Apply backoff factor to determine next delay and ensure it is within\n    // bounds.\n    this.currentBaseMs *= this.backoffFactor;\n    if (this.currentBaseMs < this.initialDelayMs) {\n      this.currentBaseMs = this.initialDelayMs;\n    }\n    if (this.currentBaseMs > this.maxDelayMs) {\n      this.currentBaseMs = this.maxDelayMs;\n    }\n  }\n\n  skipBackoff(): void {\n    if (this.timerPromise !== null) {\n      this.timerPromise.skipDelay();\n      this.timerPromise = null;\n    }\n  }\n\n  cancel(): void {\n    if (this.timerPromise !== null) {\n      this.timerPromise.cancel();\n      this.timerPromise = null;\n    }\n  }\n\n  /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n  private jitterDelayMs(): number {\n    return (Math.random() - 0.5) * this.currentBaseMs;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider, Token } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { 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<void>;\n  /**\n   * Called after the stream was established and can accept outgoing\n   * messages\n   */\n  onOpen: () => Promise<void>;\n  /**\n   * Called after the stream has closed. If there was an error, the\n   * FirestoreError will be set.\n   */\n  onClose: (err?: FirestoreError) => Promise<void>;\n}\n\n/** The time a stream stays open after it is marked idle. */\nconst IDLE_TIMEOUT_MS = 60 * 1000;\n\n/** The time a stream stays open until we consider it healthy. */\nconst HEALTHY_TIMEOUT_MS = 10 * 1000;\n\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n *   - Exponential backoff on failure\n *   - Authentication via CredentialsProvider\n *   - Dispatching all callbacks into the shared worker queue\n *   - Closing idle streams after 60 seconds of inactivity\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be start()ed before messages can\n * be sent and received. The PersistentStream will call the onOpen() function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a start() fail, PersistentStream will call the registered onClose()\n * listener with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n *  SendType: The type of the outgoing message of the underlying\n *    connection stream\n *  ReceiveType: The type of the incoming message of the underlying\n *    connection stream\n *  ListenerType: The type of the listener that will be used for callbacks\n */\nexport abstract class PersistentStream<\n  SendType,\n  ReceiveType,\n  ListenerType extends PersistentStreamListener\n> {\n  private state = PersistentStreamState.Initial;\n  /**\n   * A close count that's incremented every time the stream is closed; used by\n   * getCloseGuardedDispatcher() to invalidate callbacks that happen after\n   * close.\n   */\n  private closeCount = 0;\n\n  private idleTimer: DelayedOperation<void> | null = null;\n  private healthCheck: DelayedOperation<void> | null = null;\n  private stream: Stream<SendType, ReceiveType> | null = null;\n\n  protected backoff: ExponentialBackoff;\n\n  constructor(\n    private queue: AsyncQueue,\n    connectionTimerId: TimerId,\n    private idleTimerId: TimerId,\n    private healthTimerId: TimerId,\n    protected connection: Connection,\n    private authCredentialsProvider: CredentialsProvider<User>,\n    private appCheckCredentialsProvider: CredentialsProvider<string>,\n    protected listener: ListenerType\n  ) {\n    this.backoff = new ExponentialBackoff(queue, connectionTimerId);\n  }\n\n  /**\n   * 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<void> {\n    if (this.isStarted()) {\n      await this.close(PersistentStreamState.Initial);\n    }\n  }\n\n  /**\n   * After an error the stream will usually back off on the next attempt to\n   * start it. If the error warrants an immediate restart of the stream, the\n   * sender can use this to indicate that the receiver should not back off.\n   *\n   * Each error will call the onClose() listener. That function can decide to\n   * inhibit backoff if required.\n   */\n  inhibitBackoff(): void {\n    debugAssert(\n      !this.isStarted(),\n      'Can only inhibit backoff in a stopped state'\n    );\n\n    this.state = PersistentStreamState.Initial;\n    this.backoff.reset();\n  }\n\n  /**\n   * Marks this stream as idle. If no further actions are performed on the\n   * stream for one minute, the stream will automatically close itself and\n   * notify the stream's onClose() handler with Status.OK. The stream will then\n   * be in a !isStarted() state, requiring the caller to start the stream again\n   * before further use.\n   *\n   * Only streams that are in state 'Open' can be marked idle, as all other\n   * states imply pending network operations.\n   */\n  markIdle(): void {\n    // Starts the idle time if we are in state 'Open' and are not yet already\n    // running a timer (in which case the previous idle timeout still applies).\n    if (this.isOpen() && this.idleTimer === null) {\n      this.idleTimer = this.queue.enqueueAfterDelay(\n        this.idleTimerId,\n        IDLE_TIMEOUT_MS,\n        () => this.handleIdleCloseTimer()\n      );\n    }\n  }\n\n  /** Sends a message to the underlying stream. */\n  protected sendRequest(msg: SendType): void {\n    this.cancelIdleCheck();\n    this.stream!.send(msg);\n  }\n\n  /** Called by the idle timer when the stream should close due to inactivity. */\n  private async handleIdleCloseTimer(): Promise<void> {\n    if (this.isOpen()) {\n      // When timing out an idle stream there's no reason to force the stream into backoff when\n      // it restarts so set the stream state to Initial instead of Error.\n      return this.close(PersistentStreamState.Initial);\n    }\n  }\n\n  /** Marks the stream as active again. */\n  private cancelIdleCheck(): void {\n    if (this.idleTimer) {\n      this.idleTimer.cancel();\n      this.idleTimer = null;\n    }\n  }\n\n  /** Cancels the health check delayed operation. */\n  private cancelHealthCheck(): void {\n    if (this.healthCheck) {\n      this.healthCheck.cancel();\n      this.healthCheck = null;\n    }\n  }\n\n  /**\n   * Closes the stream and cleans up as necessary:\n   *\n   * * closes the underlying GRPC stream;\n   * * calls the onClose handler with the given 'error';\n   * * sets internal stream state to 'finalState';\n   * * adjusts the backoff timer based on the error\n   *\n   * A new stream can be opened by calling start().\n   *\n   * @param finalState - the intended state of the stream after closing.\n   * @param error - the error the connection was closed with.\n   */\n  private async close(\n    finalState: PersistentStreamState,\n    error?: FirestoreError\n  ): Promise<void> {\n    debugAssert(this.isStarted(), 'Only started streams should be closed.');\n    debugAssert(\n      finalState === PersistentStreamState.Error || isNullOrUndefined(error),\n      \"Can't provide an error when not in an error state.\"\n    );\n\n    // Cancel any outstanding timers (they're guaranteed not to execute).\n    this.cancelIdleCheck();\n    this.cancelHealthCheck();\n    this.backoff.cancel();\n\n    // Invalidates any stream-related callbacks (e.g. from auth or the\n    // underlying stream), guaranteeing they won't execute.\n    this.closeCount++;\n\n    if (finalState !== PersistentStreamState.Error) {\n      // If this is an intentional close ensure we don't delay our next connection attempt.\n      this.backoff.reset();\n    } else if (error && error.code === Code.RESOURCE_EXHAUSTED) {\n      // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n      logError(error.toString());\n      logError(\n        'Using maximum backoff delay to prevent overloading the backend.'\n      );\n      this.backoff.resetToMax();\n    } else if (\n      error &&\n      error.code === Code.UNAUTHENTICATED &&\n      this.state !== PersistentStreamState.Healthy\n    ) {\n      // \"unauthenticated\" error means the token was rejected. This should rarely\n      // happen since both Auth and AppCheck ensure a sufficient TTL when we\n      // request a token. If a user manually resets their system clock this can\n      // fail, however. In this case, we should get a Code.UNAUTHENTICATED error\n      // before we received the first message and we need to invalidate the token\n      // to ensure that we fetch a new token.\n      this.authCredentialsProvider.invalidateToken();\n      this.appCheckCredentialsProvider.invalidateToken();\n    }\n\n    // Clean up the underlying stream because we are no longer interested in events.\n    if (this.stream !== null) {\n      this.tearDown();\n      this.stream.close();\n      this.stream = null;\n    }\n\n    // This state must be assigned before calling onClose() to allow the callback to\n    // inhibit backoff or otherwise manipulate the state in its non-started state.\n    this.state = finalState;\n\n    // Notify the listener that the stream closed.\n    await this.listener.onClose(error);\n  }\n\n  /**\n   * Can be overridden to perform additional cleanup before the stream is closed.\n   * Calling super.tearDown() is not required.\n   */\n  protected tearDown(): void {}\n\n  /**\n   * Used by subclasses to start the concrete RPC and return the underlying\n   * connection stream.\n   */\n  protected abstract startRpc(\n    authToken: Token | null,\n    appCheckToken: Token | null\n  ): Stream<SendType, ReceiveType>;\n\n  /**\n   * Called 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<void>;\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<void>;\n\n  private auth(): void {\n    debugAssert(\n      this.state === PersistentStreamState.Initial,\n      'Must be in initial state to auth'\n    );\n\n    this.state = PersistentStreamState.Starting;\n\n    const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n\n    // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n    const closeCount = this.closeCount;\n\n    Promise.all([\n      this.authCredentialsProvider.getToken(),\n      this.appCheckCredentialsProvider.getToken()\n    ]).then(\n      ([authToken, appCheckToken]) => {\n        // Stream can be stopped while waiting for authentication.\n        // TODO(mikelehen): We really should just use dispatchIfNotClosed\n        // and let this dispatch onto the queue, but that opened a spec test can\n        // of worms that I don't want to deal with in this PR.\n        if (this.closeCount === closeCount) {\n          // Normally we'd have to schedule the callback on the AsyncQueue.\n          // However, the following calls are safe to be called outside the\n          // AsyncQueue since they don't chain asynchronous calls\n          this.startStream(authToken, appCheckToken);\n        }\n      },\n      (error: Error) => {\n        dispatchIfNotClosed(() => {\n          const rpcError = new FirestoreError(\n            Code.UNKNOWN,\n            'Fetching auth token failed: ' + error.message\n          );\n          return this.handleStreamClose(rpcError);\n        });\n      }\n    );\n  }\n\n  private startStream(\n    authToken: Token | null,\n    appCheckToken: Token | null\n  ): void {\n    debugAssert(\n      this.state === PersistentStreamState.Starting,\n      'Trying to start stream in a non-starting state'\n    );\n\n    const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n\n    this.stream = this.startRpc(authToken, appCheckToken);\n    this.stream.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<void> {\n    debugAssert(\n      this.isStarted(),\n      \"Can't handle server close on non-started stream\"\n    );\n    logDebug(LOG_TAG, `close with error: ${error}`);\n\n    this.stream = null;\n\n    // In theory the stream could close cleanly, however, in our current model\n    // we never expect this to happen because if we stop a stream ourselves,\n    // this callback will never be called. To prevent cases where we retry\n    // without a backoff accidentally, we set the stream to error in all cases.\n    return this.close(PersistentStreamState.Error, error);\n  }\n\n  /**\n   * Returns a \"dispatcher\" function that dispatches operations onto the\n   * AsyncQueue but only runs them if closeCount remains unchanged. This allows\n   * us to turn auth / stream callbacks into no-ops if the stream is closed /\n   * re-opened, etc.\n   */\n  private getCloseGuardedDispatcher(\n    startCloseCount: number\n  ): (fn: () => Promise<void>) => void {\n    return (fn: () => Promise<void>): void => {\n      this.queue.enqueueAndForget(() => {\n        if (this.closeCount === startCloseCount) {\n          return fn();\n        } else {\n          logDebug(\n            LOG_TAG,\n            'stream callback skipped by getCloseGuardedDispatcher.'\n          );\n          return Promise.resolve();\n        }\n      });\n    };\n  }\n}\n\n/** Listener for the PersistentWatchStream */\nexport interface WatchStreamListener extends PersistentStreamListener {\n  /**\n   * Called on a watchChange. The snapshot parameter will be MIN if the watch\n   * change did not have a snapshot associated with it.\n   */\n  onWatchChange: (\n    watchChange: WatchChange,\n    snapshot: SnapshotVersion\n  ) => Promise<void>;\n}\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the onOpen() listener, any number of\n * listen() and unlisten() calls can be made to control what changes will be\n * sent from the server for ListenResponses.\n */\nexport class PersistentListenStream extends PersistentStream<\n  ProtoListenRequest,\n  ProtoListenResponse,\n  WatchStreamListener\n> {\n  constructor(\n    queue: AsyncQueue,\n    connection: Connection,\n    authCredentials: CredentialsProvider<User>,\n    appCheckCredentials: CredentialsProvider<string>,\n    private serializer: JsonProtoSerializer,\n    listener: WatchStreamListener\n  ) {\n    super(\n      queue,\n      TimerId.ListenStreamConnectionBackoff,\n      TimerId.ListenStreamIdle,\n      TimerId.HealthCheckTimeout,\n      connection,\n      authCredentials,\n      appCheckCredentials,\n      listener\n    );\n  }\n\n  protected startRpc(\n    authToken: Token | null,\n    appCheckToken: Token | null\n  ): Stream<ProtoListenRequest, ProtoListenResponse> {\n    return this.connection.openStream<ProtoListenRequest, ProtoListenResponse>(\n      'Listen',\n      authToken,\n      appCheckToken\n    );\n  }\n\n  protected onFirst(watchChangeProto: ProtoListenResponse): Promise<void> {\n    return this.onNext(watchChangeProto);\n  }\n\n  protected onNext(watchChangeProto: ProtoListenResponse): Promise<void> {\n    // A successful response means the stream is healthy\n    this.backoff.reset();\n\n    const watchChange = fromWatchChange(this.serializer, watchChangeProto);\n    const snapshot = versionFromListenResponse(watchChangeProto);\n    return this.listener!.onWatchChange(watchChange, snapshot);\n  }\n\n  /**\n   * Registers interest in the results of the given target. If the target\n   * includes a resumeToken it will be included in the request. Results that\n   * affect the target will be streamed back as WatchChange messages that\n   * reference the targetId.\n   */\n  watch(targetData: TargetData<number>): 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: number): void {\n    const request: ListenRequest = {};\n    request.database = getEncodedDatabaseId(this.serializer);\n    request.removeTarget = targetId;\n    this.sendRequest(request);\n  }\n}\n\n/** Listener for the PersistentWriteStream */\nexport interface WriteStreamListener extends PersistentStreamListener {\n  /**\n   * Called by the PersistentWriteStream upon a successful handshake response\n   * from the server, which is the receiver's cue to send any pending writes.\n   */\n  onHandshakeComplete: () => Promise<void>;\n\n  /**\n   * Called by the PersistentWriteStream upon receiving a StreamingWriteResponse\n   * from the server that contains a mutation result.\n   */\n  onMutationResult: (\n    commitVersion: SnapshotVersion,\n    results: MutationResult[]\n  ) => Promise<void>;\n}\n\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */\nexport class PersistentWriteStream extends PersistentStream<\n  ProtoWriteRequest,\n  ProtoWriteResponse,\n  WriteStreamListener\n> {\n  constructor(\n    queue: AsyncQueue,\n    connection: Connection,\n    authCredentials: CredentialsProvider<User>,\n    appCheckCredentials: CredentialsProvider<string>,\n    private serializer: JsonProtoSerializer,\n    listener: WriteStreamListener\n  ) {\n    super(\n      queue,\n      TimerId.WriteStreamConnectionBackoff,\n      TimerId.WriteStreamIdle,\n      TimerId.HealthCheckTimeout,\n      connection,\n      authCredentials,\n      appCheckCredentials,\n      listener\n    );\n  }\n\n  /**\n   * The last received stream token from the server, used to acknowledge which\n   * responses the client has processed. Stream tokens are opaque checkpoint\n   * markers whose only real value is their inclusion in the next request.\n   *\n   * PersistentWriteStream manages propagating this value from responses to the\n   * next request.\n   */\n  private lastStreamToken: string | Uint8Array | undefined;\n\n  /**\n   * Tracks whether or not a handshake has been successfully exchanged and\n   * the stream is ready to accept mutations.\n   */\n  get handshakeComplete(): boolean {\n    return this.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<ProtoWriteRequest, ProtoWriteResponse> {\n    return this.connection.openStream<ProtoWriteRequest, ProtoWriteResponse>(\n      'Write',\n      authToken,\n      appCheckToken\n    );\n  }\n\n  protected onFirst(responseProto: ProtoWriteResponse): Promise<void> {\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<void> {\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 { StructuredPipeline } from '../core/structured_pipeline';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport { PipelineStreamElement } from '../model/pipeline_stream_element';\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  ExecutePipelineRequest as ProtoExecutePipelineRequest,\n  ExecutePipelineResponse as ProtoExecutePipelineResponse,\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  fromPipelineResponse,\n  getEncodedDatabaseId\n} from './serializer';\n\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\nexport abstract class Datastore {\n  abstract terminate(): void;\n  abstract serializer: JsonProtoSerializer;\n}\n\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass DatastoreImpl extends Datastore {\n  terminated = false;\n\n  constructor(\n    readonly authCredentials: CredentialsProvider<User>,\n    readonly appCheckCredentials: CredentialsProvider<string>,\n    readonly connection: Connection,\n    readonly serializer: JsonProtoSerializer\n  ) {\n    super();\n  }\n\n  verifyInitialized(): void {\n    debugAssert(!!this.connection, 'Datastore.start() not called');\n    if (this.terminated) {\n      throw new FirestoreError(\n        Code.FAILED_PRECONDITION,\n        'The client has already been terminated.'\n      );\n    }\n  }\n\n  /** Invokes the provided RPC with auth and AppCheck tokens. */\n  invokeRPC<Req, Resp>(\n    rpcName: string,\n    databaseId: DatabaseId,\n    resourcePath: ResourcePath,\n    request: Req\n  ): Promise<Resp> {\n    this.verifyInitialized();\n    return Promise.all([\n      this.authCredentials.getToken(),\n      this.appCheckCredentials.getToken()\n    ])\n      .then(([authToken, appCheckToken]) => {\n        return this.connection.invokeRPC<Req, Resp>(\n          rpcName,\n          toResourcePath(databaseId, resourcePath),\n          request,\n          authToken,\n          appCheckToken\n        );\n      })\n      .catch((error: FirestoreError) => {\n        if (error.name === 'FirebaseError') {\n          if (error.code === Code.UNAUTHENTICATED) {\n            this.authCredentials.invalidateToken();\n            this.appCheckCredentials.invalidateToken();\n          }\n          throw error;\n        } else {\n          throw new FirestoreError(Code.UNKNOWN, error.toString());\n        }\n      });\n  }\n\n  /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */\n  invokeStreamingRPC<Req, Resp>(\n    rpcName: string,\n    databaseId: DatabaseId,\n    resourcePath: ResourcePath,\n    request: Req,\n    expectedResponseCount?: number\n  ): Promise<Resp[]> {\n    this.verifyInitialized();\n    return Promise.all([\n      this.authCredentials.getToken(),\n      this.appCheckCredentials.getToken()\n    ])\n      .then(([authToken, appCheckToken]) => {\n        return this.connection.invokeStreamingRPC<Req, Resp>(\n          rpcName,\n          toResourcePath(databaseId, resourcePath),\n          request,\n          authToken,\n          appCheckToken,\n          expectedResponseCount\n        );\n      })\n      .catch((error: FirestoreError) => {\n        if (error.name === 'FirebaseError') {\n          if (error.code === Code.UNAUTHENTICATED) {\n            this.authCredentials.invalidateToken();\n            this.appCheckCredentials.invalidateToken();\n          }\n          throw error;\n        } else {\n          throw new FirestoreError(Code.UNKNOWN, error.toString());\n        }\n      });\n  }\n\n  terminate(): void {\n    this.terminated = true;\n    this.connection.terminate();\n  }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nexport function newDatastore(\n  authCredentials: CredentialsProvider<User>,\n  appCheckCredentials: CredentialsProvider<string>,\n  connection: Connection,\n  serializer: JsonProtoSerializer\n): Datastore {\n  return new DatastoreImpl(\n    authCredentials,\n    appCheckCredentials,\n    connection,\n    serializer\n  );\n}\n\nexport async function invokeCommitRpc(\n  datastore: Datastore,\n  mutations: Mutation[]\n): Promise<void> {\n  const datastoreImpl = debugCast(datastore, DatastoreImpl);\n  const request = {\n    writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))\n  };\n  await datastoreImpl.invokeRPC(\n    'Commit',\n    datastoreImpl.serializer.databaseId,\n    ResourcePath.emptyPath(),\n    request\n  );\n}\n\nexport async function invokeBatchGetDocumentsRpc(\n  datastore: Datastore,\n  keys: DocumentKey[]\n): Promise<Document[]> {\n  const datastoreImpl = debugCast(datastore, DatastoreImpl);\n  const request = {\n    documents: keys.map(k => toName(datastoreImpl.serializer, k))\n  };\n  const response = await datastoreImpl.invokeStreamingRPC<\n    ProtoBatchGetDocumentsRequest,\n    ProtoBatchGetDocumentsResponse\n  >(\n    'BatchGetDocuments',\n    datastoreImpl.serializer.databaseId,\n    ResourcePath.emptyPath(),\n    request,\n    keys.length\n  );\n\n  const docs = new Map<string, Document>();\n  response.forEach(proto => {\n    const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);\n    docs.set(doc.key.toString(), doc);\n  });\n  const result: Document[] = [];\n  keys.forEach(key => {\n    const doc = docs.get(key.toString());\n    hardAssert(!!doc, 0xd7c2, 'Missing entity in write response for `key`', {\n      key\n    });\n    result.push(doc);\n  });\n  return result;\n}\n\nexport async function invokeExecutePipeline(\n  datastore: Datastore,\n  structuredPipeline: StructuredPipeline\n): Promise<PipelineStreamElement[]> {\n  const datastoreImpl = debugCast(datastore, DatastoreImpl);\n  const executePipelineRequest: ProtoExecutePipelineRequest = {\n    database: getEncodedDatabaseId(datastoreImpl.serializer),\n    structuredPipeline: structuredPipeline._toProto(datastoreImpl.serializer)\n  };\n\n  const response = await datastoreImpl.invokeStreamingRPC<\n    ProtoExecutePipelineRequest,\n    ProtoExecutePipelineResponse\n  >(\n    'ExecutePipeline',\n    datastoreImpl.serializer.databaseId,\n    ResourcePath.emptyPath(),\n    executePipelineRequest\n  );\n\n  const result: PipelineStreamElement[] = [];\n  response.forEach(proto => {\n    if (!proto.results || proto.results!.length === 0) {\n      result.push(fromPipelineResponse(datastoreImpl.serializer, proto));\n    } else {\n      return proto.results!.forEach(document =>\n        result.push(\n          fromPipelineResponse(datastoreImpl.serializer, proto, document)\n        )\n      );\n    }\n  });\n\n  return result;\n}\n\nexport async function invokeRunQueryRpc(\n  datastore: Datastore,\n  query: Query\n): Promise<Document[]> {\n  const datastoreImpl = debugCast(datastore, DatastoreImpl);\n  const { queryTarget, parent } = toQueryTarget(\n    datastoreImpl.serializer,\n    queryToTarget(query)\n  );\n  const response = await datastoreImpl.invokeStreamingRPC<\n    ProtoRunQueryRequest,\n    ProtoRunQueryResponse\n  >('RunQuery', datastoreImpl.serializer.databaseId, parent, {\n    structuredQuery: queryTarget.structuredQuery\n  });\n  return (\n    response\n      // Omit RunQueryResponses that only contain readTimes.\n      .filter(proto => !!proto.document)\n      .map(proto =>\n        fromDocument(datastoreImpl.serializer, proto.document!, undefined)\n      )\n  );\n}\n\nexport async function invokeRunAggregationQueryRpc(\n  datastore: Datastore,\n  query: Query,\n  aggregates: Aggregate[]\n): Promise<ApiClientObjectMap<Value>> {\n  const datastoreImpl = debugCast(datastore, DatastoreImpl);\n  const { request, aliasMap, parent } = toRunAggregationQueryRequest(\n    datastoreImpl.serializer,\n    queryToAggregateTarget(query),\n    aggregates\n  );\n\n  if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {\n    delete request.parent;\n  }\n  const response = await datastoreImpl.invokeStreamingRPC<\n    ProtoRunAggregationQueryRequest,\n    ProtoRunAggregationQueryResponse\n  >(\n    'RunAggregationQuery',\n    datastoreImpl.serializer.databaseId,\n    parent,\n    request,\n    /*expectedResponseCount=*/ 1\n  );\n\n  // Omit RunAggregationQueryResponse that only contain readTimes.\n  const filteredResult = response.filter(proto => !!proto.result);\n\n  hardAssert(\n    filteredResult.length === 1,\n    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<Value>\n  >((accumulator, key) => {\n    debugAssert(\n      !isNullOrUndefined(aliasMap[key]),\n      `'${key}' not present in aliasMap result`\n    );\n    accumulator[aliasMap[key]] = unmappedAggregateFields[key]!;\n    return accumulator;\n  }, {});\n\n  return remappedFields;\n}\n\nexport function newPersistentWriteStream(\n  datastore: Datastore,\n  queue: AsyncQueue,\n  listener: WriteStreamListener\n): PersistentWriteStream {\n  const datastoreImpl = debugCast(datastore, DatastoreImpl);\n  datastoreImpl.verifyInitialized();\n  return new PersistentWriteStream(\n    queue,\n    datastoreImpl.connection,\n    datastoreImpl.authCredentials,\n    datastoreImpl.appCheckCredentials,\n    datastoreImpl.serializer,\n    listener\n  );\n}\n\nexport function newPersistentWatchStream(\n  datastore: Datastore,\n  queue: AsyncQueue,\n  listener: WatchStreamListener\n): PersistentListenStream {\n  const datastoreImpl = debugCast(datastore, DatastoreImpl);\n  datastoreImpl.verifyInitialized();\n  return new PersistentListenStream(\n    queue,\n    datastoreImpl.connection,\n    datastoreImpl.authCredentials,\n    datastoreImpl.appCheckCredentials,\n    datastoreImpl.serializer,\n    listener\n  );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { _FirebaseService } from '@firebase/app';\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { cloneLongPollingOptions } from '../api/long_polling_options';\nimport { User } from '../auth/user';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { newConnection } from '../platform/connection';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { FirestoreSettingsImpl } from './settings';\n\nexport const LOG_TAG = 'ComponentProvider';\n\n// The components module manages the lifetime of dependencies of the Firestore\n// client. Dependencies can be lazily constructed and only one exists per\n// Firestore instance.\n\n/**\n * An interface implemented by FirebaseFirestore that provides compatibility\n * with the usage in this file.\n *\n * This interface mainly exists to remove a cyclic dependency.\n */\nexport interface FirestoreService extends _FirebaseService {\n  _authCredentials: CredentialsProvider<User>;\n  _appCheckCredentials: CredentialsProvider<string>;\n  _persistenceKey: string;\n  _databaseId: DatabaseId;\n  _terminated: boolean;\n\n  _freezeSettings(): FirestoreSettingsImpl;\n}\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\nconst datastoreInstances = new Map<FirestoreService, Datastore>();\n\n/**\n * Returns an initialized and started Datastore for the given Firestore\n * instance. Callers must invoke removeComponents() when the Firestore\n * instance is terminated.\n */\nexport function getDatastore(firestore: FirestoreService): Datastore {\n  if (firestore._terminated) {\n    throw new FirestoreError(\n      Code.FAILED_PRECONDITION,\n      'The client has already been terminated.'\n    );\n  }\n  if (!datastoreInstances.has(firestore)) {\n    logDebug(LOG_TAG, 'Initializing Datastore');\n    const databaseInfo = makeDatabaseInfo(\n      firestore._databaseId,\n      firestore.app.options.appId || '',\n      firestore._persistenceKey,\n      firestore.app.options.apiKey,\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  apiKey: string | undefined,\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    apiKey\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<TargetId, unknown>;\n\nexport const GC_DID_NOT_RUN: LruResults = {\n  didRun: false,\n  sequenceNumbersCollected: 0,\n  targetsRemoved: 0,\n  documentsRemoved: 0\n};\n\nexport const LRU_COLLECTION_DISABLED = -1;\nexport const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n\nexport class LruParams {\n  private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n  private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n  static withCacheSize(cacheSize: number): LruParams {\n    return new LruParams(\n      cacheSize,\n      LruParams.DEFAULT_COLLECTION_PERCENTILE,\n      LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n    );\n  }\n\n  static readonly DEFAULT: LruParams = new LruParams(\n    LRU_DEFAULT_CACHE_SIZE_BYTES,\n    LruParams.DEFAULT_COLLECTION_PERCENTILE,\n    LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n  );\n\n  static readonly DISABLED: LruParams = new LruParams(\n    LRU_COLLECTION_DISABLED,\n    0,\n    0\n  );\n\n  constructor(\n    // When we attempt to collect, we will only do so if the cache size is greater than this\n    // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n    readonly cacheSizeCollectionThreshold: number,\n    // The percentage of sequence numbers that we will attempt to collect\n    readonly percentileToCollect: number,\n    // A cap on the total number of sequence numbers that will be collected. This prevents\n    // us from collecting a huge number of sequence numbers if the cache has grown very large.\n    readonly maximumSequenceNumbersToCollect: number\n  ) {}\n}\n\nexport interface LruGarbageCollector {\n  readonly params: LruParams;\n\n  collect(\n    txn: PersistenceTransaction,\n    activeTargetIds: ActiveTargets\n  ): PersistencePromise<LruResults>;\n\n  /** Given a percentile of target to collect, returns the number of targets to collect. */\n  calculateTargetCount(\n    txn: PersistenceTransaction,\n    percentile: number\n  ): PersistencePromise<number>;\n\n  /** Returns the nth sequence number, counting in order from the smallest. */\n  nthSequenceNumber(\n    txn: PersistenceTransaction,\n    n: number\n  ): PersistencePromise<number>;\n\n  /**\n   * Removes documents that have a sequence number equal to or less than the\n   * upper bound and are not otherwise pinned.\n   */\n  removeOrphanedDocuments(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber\n  ): PersistencePromise<number>;\n\n  getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;\n\n  /**\n   * Removes targets with a sequence number equal to or less than the given\n   * upper bound, and removes document associations with those targets.\n   */\n  removeTargets(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber,\n    activeTargetIds: ActiveTargets\n  ): PersistencePromise<number>;\n}\n\n/**\n * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n  readonly didRun: boolean;\n  readonly sequenceNumbersCollected: number;\n  readonly targetsRemoved: number;\n  readonly documentsRemoved: number;\n}\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have\n * reference delegates that implement this interface. This interface defines the\n * operations that the LRU garbage collector needs from the persistence layer.\n */\nexport interface LruDelegate {\n  readonly garbageCollector: LruGarbageCollector;\n\n  /** Enumerates all the targets in the TargetCache. */\n  forEachTarget(\n    txn: PersistenceTransaction,\n    f: (target: TargetData) => void\n  ): PersistencePromise<void>;\n\n  getSequenceNumberCount(\n    txn: PersistenceTransaction\n  ): PersistencePromise<number>;\n\n  /**\n   * Enumerates sequence numbers for documents not associated with a target.\n   * Note that this may include duplicate sequence numbers.\n   */\n  forEachOrphanedDocumentSequenceNumber(\n    txn: PersistenceTransaction,\n    f: (sequenceNumber: ListenSequenceNumber) => void\n  ): PersistencePromise<void>;\n\n  /**\n   * Removes all targets that have a sequence number less than or equal to\n   * `upperBound`, and are not present in the `activeTargetIds` set.\n   *\n   * @returns the number of targets removed.\n   */\n  removeTargets(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber,\n    activeTargetIds: ActiveTargets\n  ): PersistencePromise<number>;\n\n  /**\n   * Removes all unreferenced documents from the cache that have a sequence\n   * number less than or equal to the given `upperBound`.\n   *\n   * @returns the number of documents removed.\n   */\n  removeOrphanedDocuments(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber\n  ): PersistencePromise<number>;\n\n  getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n  ActiveTargets,\n  GC_DID_NOT_RUN,\n  LRU_COLLECTION_DISABLED,\n  LruDelegate,\n  LruGarbageCollector,\n  LruParams,\n  LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n  [aSequence, aIndex]: BufferEntry,\n  [bSequence, bIndex]: BufferEntry\n): number {\n  const seqCmp = primitiveComparator(aSequence, bSequence);\n  if (seqCmp === 0) {\n    // This order doesn't matter, but we can bias against churn by sorting\n    // entries created earlier as less than newer entries.\n    return primitiveComparator(aIndex, bIndex);\n  } else {\n    return seqCmp;\n  }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n  private buffer: SortedSet<BufferEntry> = new SortedSet<BufferEntry>(\n    bufferEntryComparator\n  );\n\n  private previousIndex = 0;\n\n  constructor(private readonly maxElements: number) {}\n\n  private nextIndex(): number {\n    return ++this.previousIndex;\n  }\n\n  addElement(sequenceNumber: ListenSequenceNumber): void {\n    const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n    if (this.buffer.size < this.maxElements) {\n      this.buffer = this.buffer.add(entry);\n    } else {\n      const highestValue = this.buffer.last()!;\n      if (bufferEntryComparator(entry, highestValue) < 0) {\n        this.buffer = this.buffer.delete(highestValue).add(entry);\n      }\n    }\n  }\n\n  get maxValue(): ListenSequenceNumber {\n    // Guaranteed to be non-empty. If we decide we are not collecting any\n    // sequence numbers, nthSequenceNumber below short-circuits. If we have\n    // decided that we are collecting n sequence numbers, it's because n is some\n    // percentage of the existing sequence numbers. That means we should never\n    // be in a situation where we are collecting sequence numbers but don't\n    // actually have any.\n    return this.buffer.last()![0];\n  }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */\nexport class LruScheduler implements Scheduler {\n  private gcTask: DelayedOperation<void> | null;\n\n  constructor(\n    private readonly garbageCollector: LruGarbageCollector,\n    private readonly asyncQueue: AsyncQueue,\n    private readonly localStore: LocalStore\n  ) {\n    this.gcTask = null;\n  }\n\n  start(): void {\n    debugAssert(\n      this.gcTask === null,\n      'Cannot start an already started LruScheduler'\n    );\n    if (\n      this.garbageCollector.params.cacheSizeCollectionThreshold !==\n      LRU_COLLECTION_DISABLED\n    ) {\n      this.scheduleGC(INITIAL_GC_DELAY_MS);\n    }\n  }\n\n  stop(): void {\n    if (this.gcTask) {\n      this.gcTask.cancel();\n      this.gcTask = null;\n    }\n  }\n\n  get started(): boolean {\n    return this.gcTask !== null;\n  }\n\n  private scheduleGC(delay: number): void {\n    debugAssert(\n      this.gcTask === null,\n      'Cannot schedule GC while a task is pending'\n    );\n    logDebug(LOG_TAG, `Garbage collection scheduled in ${delay}ms`);\n    this.gcTask = this.asyncQueue.enqueueAfterDelay(\n      TimerId.LruGarbageCollection,\n      delay,\n      async () => {\n        this.gcTask = null;\n        try {\n          await this.localStore.collectGarbage(this.garbageCollector);\n        } catch (e) {\n          if (isIndexedDbTransactionError(e as Error)) {\n            logDebug(\n              LOG_TAG,\n              'Ignoring IndexedDB error during garbage collection: ',\n              e\n            );\n          } else {\n            await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n          }\n        }\n        await this.scheduleGC(REGULAR_GC_DELAY_MS);\n      }\n    );\n  }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */\nclass LruGarbageCollectorImpl implements LruGarbageCollector {\n  constructor(\n    private readonly delegate: LruDelegate,\n    readonly params: LruParams\n  ) {}\n\n  calculateTargetCount(\n    txn: PersistenceTransaction,\n    percentile: number\n  ): PersistencePromise<number> {\n    return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n      return Math.floor((percentile / 100.0) * targetCount);\n    });\n  }\n\n  nthSequenceNumber(\n    txn: PersistenceTransaction,\n    n: number\n  ): PersistencePromise<ListenSequenceNumber> {\n    if (n === 0) {\n      return PersistencePromise.resolve(ListenSequence.INVALID);\n    }\n\n    const buffer = new RollingSequenceNumberBuffer(n);\n    return this.delegate\n      .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n      .next(() => {\n        return this.delegate.forEachOrphanedDocumentSequenceNumber(\n          txn,\n          sequenceNumber => buffer.addElement(sequenceNumber)\n        );\n      })\n      .next(() => buffer.maxValue);\n  }\n\n  removeTargets(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber,\n    activeTargetIds: ActiveTargets\n  ): PersistencePromise<number> {\n    return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n  }\n\n  removeOrphanedDocuments(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber\n  ): PersistencePromise<number> {\n    return this.delegate.removeOrphanedDocuments(txn, upperBound);\n  }\n\n  collect(\n    txn: PersistenceTransaction,\n    activeTargetIds: ActiveTargets\n  ): PersistencePromise<LruResults> {\n    if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) {\n      logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n      return PersistencePromise.resolve(GC_DID_NOT_RUN);\n    }\n\n    return this.getCacheSize(txn).next(cacheSize => {\n      if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n        logDebug(\n          'LruGarbageCollector',\n          `Garbage collection skipped; Cache size ${cacheSize} ` +\n            `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n        );\n        return GC_DID_NOT_RUN;\n      } else {\n        return this.runGarbageCollection(txn, activeTargetIds);\n      }\n    });\n  }\n\n  getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n    return this.delegate.getCacheSize(txn);\n  }\n\n  private runGarbageCollection(\n    txn: PersistenceTransaction,\n    activeTargetIds: ActiveTargets\n  ): PersistencePromise<LruResults> {\n    let upperBoundSequenceNumber: number;\n    let sequenceNumbersToCollect: number, targetsRemoved: number;\n    // Timestamps for various pieces of the process\n    let countedTargetsTs: number,\n      foundUpperBoundTs: number,\n      removedTargetsTs: number,\n      removedDocumentsTs: number;\n    const startTs = Date.now();\n    return this.calculateTargetCount(txn, this.params.percentileToCollect)\n      .next(sequenceNumbers => {\n        // Cap at the configured max\n        if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n          logDebug(\n            'LruGarbageCollector',\n            'Capping sequence numbers to collect down ' +\n              `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n              `from ${sequenceNumbers}`\n          );\n          sequenceNumbersToCollect =\n            this.params.maximumSequenceNumbersToCollect;\n        } else {\n          sequenceNumbersToCollect = sequenceNumbers;\n        }\n        countedTargetsTs = Date.now();\n\n        return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n      })\n      .next(upperBound => {\n        upperBoundSequenceNumber = upperBound;\n        foundUpperBoundTs = Date.now();\n\n        return this.removeTargets(\n          txn,\n          upperBoundSequenceNumber,\n          activeTargetIds\n        );\n      })\n      .next(numTargetsRemoved => {\n        targetsRemoved = numTargetsRemoved;\n        removedTargetsTs = Date.now();\n\n        return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n      })\n      .next(documentsRemoved => {\n        removedDocumentsTs = Date.now();\n\n        if (getLogLevel() <= LogLevel.DEBUG) {\n          const desc =\n            'LRU Garbage Collection\\n' +\n            `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n            `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n            `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n            `\\tRemoved ${targetsRemoved} targets in ` +\n            `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n            `\\tRemoved ${documentsRemoved} documents in ` +\n            `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n            `Total Duration: ${removedDocumentsTs - startTs}ms`;\n          logDebug('LruGarbageCollector', desc);\n        }\n\n        return PersistencePromise.resolve<LruResults>({\n          didRun: true,\n          sequenceNumbersCollected: sequenceNumbersToCollect,\n          targetsRemoved,\n          documentsRemoved\n        });\n      });\n  }\n}\n\nexport function newLruGarbageCollector(\n  delegate: LruDelegate,\n  params: LruParams\n): LruGarbageCollector {\n  return new LruGarbageCollectorImpl(delegate, params);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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} 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<void> | 'notTerminated' = 'notTerminated';\n\n  /** @hideconstructor */\n  constructor(\n    public _authCredentials: CredentialsProvider<User>,\n    public _appCheckCredentials: CredentialsProvider<string>,\n    readonly _databaseId: DatabaseId,\n    readonly _app?: FirebaseApp\n  ) {}\n\n  /**\n   * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n   * instance.\n   */\n  get app(): FirebaseApp {\n    if (!this._app) {\n      throw new FirestoreError(\n        Code.FAILED_PRECONDITION,\n        \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n          'not available'\n      );\n    }\n    return this._app;\n  }\n\n  get _initialized(): boolean {\n    return this._settingsFrozen;\n  }\n\n  get _terminated(): boolean {\n    return this._terminateTask !== '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<void> {\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<void> {\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<void> {\n    removeComponents(this);\n    return Promise.resolve();\n  }\n}\n\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @returns A newly initialized `Firestore` instance.\n */\nexport function initializeFirestore(\n  app: FirebaseApp,\n  settings: FirestoreSettings\n): Firestore;\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized `Firestore` instance.\n * @beta\n */\nexport function initializeFirestore(\n  app: FirebaseApp,\n  settings: FirestoreSettings,\n  databaseId?: string\n): Firestore;\nexport function initializeFirestore(\n  app: FirebaseApp,\n  settings: FirestoreSettings,\n  databaseId?: string\n): Firestore {\n  if (!databaseId) {\n    databaseId = DEFAULT_DATABASE_NAME;\n  }\n  const provider = _getProvider(app, 'firestore/lite');\n\n  if (provider.isInitialized(databaseId)) {\n    throw new FirestoreError(\n      Code.FAILED_PRECONDITION,\n      'Firestore can only be initialized once per app.'\n    );\n  }\n\n  return provider.initialize({\n    options: settings,\n    instanceIdentifier: databaseId\n  });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n  appOrDatabaseId?: FirebaseApp | string,\n  optionalDatabaseId?: string\n): Firestore {\n  const app: FirebaseApp =\n    typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n  const databaseId =\n    typeof appOrDatabaseId === 'string'\n      ? appOrDatabaseId\n      : optionalDatabaseId || '(default)';\n  const db = _getProvider(app, 'firestore/lite').getImmediate({\n    identifier: databaseId\n  }) as Firestore;\n  if (!db._initialized) {\n    const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n    if (emulator) {\n      connectFirestoreEmulator(db, ...emulator);\n    }\n  }\n  return db;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */\nexport function connectFirestoreEmulator(\n  firestore: Firestore,\n  host: string,\n  port: number,\n  options: {\n    mockUserToken?: EmulatorMockTokenOptions | string;\n  } = {}\n): void {\n  firestore = cast(firestore, Firestore);\n  const 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  }\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<void> {\n  firestore = cast(firestore, Firestore);\n  _removeServiceInstance(firestore.app, 'firestore/lite');\n  return firestore._delete();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n  newQueryForCollectionGroup,\n  newQueryForPath,\n  Query as InternalQuery,\n  queryEquals\n} from '../core/query';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n  cast,\n  validateCollectionPath,\n  validateDocumentPath,\n  validateNonEmptyArgument\n} from '../util/input_validation';\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<T>`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue<T> =\n  | Partial<T>\n  | (T extends Primitive\n      ? T\n      : T extends {}\n      ? { [K in keyof T]?: PartialWithFieldValue<T[K]> | FieldValue }\n      : never);\n\n/**\n * Allows FieldValues to be passed in as a property value while maintaining\n * type safety.\n */\nexport type WithFieldValue<T> =\n  | T\n  | (T extends Primitive\n      ? T\n      : T extends {}\n      ? { [K in keyof T]: WithFieldValue<T[K]> | FieldValue }\n      : never);\n\n/**\n * Update data (for use with {@link (updateDoc:1)}) that consists of field paths\n * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots\n * reference nested fields within the document. FieldValues can be passed in\n * as property values.\n */\nexport type UpdateData<T> = T extends Primitive\n  ? T\n  : T extends {}\n  ? { [K in keyof T]?: UpdateData<T[K]> | FieldValue } & NestedUpdateFields<T>\n  : Partial<T>;\n/**\n * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link\n * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a `SetOptions` with `merge: true`.\n *\n * @param merge - Changes the behavior of a `setDoc()` call to only replace the\n * values specified in its data argument. Fields omitted from the `setDoc()`\n * call remain untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace\n * the specified field paths. Any field path that is not specified is ignored\n * and remains untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n */\nexport type SetOptions =\n  | {\n      readonly merge?: boolean;\n    }\n  | {\n      readonly mergeFields?: Array<string | FieldPath>;\n    };\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */\nexport class Query<\n  AppModelType = DocumentData,\n  DbModelType extends DocumentData = DocumentData\n> {\n  /** The type of this Firestore reference. */\n  readonly type: 'query' | 'collection' = 'query';\n\n  /**\n   * The `Firestore` instance for the Firestore database (useful for performing\n   * transactions, etc.).\n   */\n  readonly firestore: Firestore;\n\n  // This is the lite version of the Query class in the main SDK.\n\n  /** @hideconstructor protected */\n  constructor(\n    firestore: Firestore,\n    /**\n     * If provided, the `FirestoreDataConverter` associated with this instance.\n     */\n    readonly converter: FirestoreDataConverter<\n      AppModelType,\n      DbModelType\n    > | null,\n    readonly _query: InternalQuery\n  ) {\n    this.firestore = firestore;\n  }\n\n  /**\n   * Removes the current converter.\n   *\n   * @param converter - `null` removes the current converter.\n   * @returns A `Query<DocumentData, DocumentData>` that does not use a\n   * converter.\n   */\n  withConverter(converter: null): Query<DocumentData, DocumentData>;\n  /**\n   * Applies a custom data converter to this query, allowing you to use your own\n   * custom model objects with Firestore. When you call {@link getDocs} with\n   * the returned query, the provided converter will convert between Firestore\n   * data of type `NewDbModelType` and your custom type `NewAppModelType`.\n   *\n   * @param converter - Converts objects to and from Firestore.\n   * @returns A `Query` that uses the provided converter.\n   */\n  withConverter<\n    NewAppModelType,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n  ): Query<NewAppModelType, NewDbModelType>;\n  withConverter<\n    NewAppModelType,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n  ): Query<NewAppModelType, NewDbModelType> {\n    return new Query<NewAppModelType, NewDbModelType>(\n      this.firestore,\n      converter,\n      this._query\n    );\n  }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */\nexport class DocumentReference<\n  AppModelType = DocumentData,\n  DbModelType extends DocumentData = DocumentData\n> {\n  /** The type of this Firestore reference. */\n  readonly type = 'document';\n\n  /**\n   * The {@link Firestore} instance the document is in.\n   * This is useful for performing transactions, for example.\n   */\n  readonly firestore: Firestore;\n\n  /** @hideconstructor */\n  constructor(\n    firestore: Firestore,\n    /**\n     * If provided, the `FirestoreDataConverter` associated with this instance.\n     */\n    readonly converter: FirestoreDataConverter<\n      AppModelType,\n      DbModelType\n    > | null,\n    readonly _key: DocumentKey\n  ) {\n    this.firestore = firestore;\n  }\n\n  get _path(): ResourcePath {\n    return this._key.path;\n  }\n\n  /**\n   * The document's identifier within its collection.\n   */\n  get id(): string {\n    return this._key.path.lastSegment();\n  }\n\n  /**\n   * A string representing the path of the referenced document (relative\n   * to the root of the database).\n   */\n  get path(): string {\n    return this._key.path.canonicalString();\n  }\n\n  /**\n   * The collection this `DocumentReference` belongs to.\n   */\n  get parent(): CollectionReference<AppModelType, DbModelType> {\n    return new CollectionReference<AppModelType, DbModelType>(\n      this.firestore,\n      this.converter,\n      this._key.path.popLast()\n    );\n  }\n\n  /**\n   * Applies a custom data converter to this `DocumentReference`, allowing you\n   * to use your own custom model objects with Firestore. When you call {@link\n   * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`\n   * instance, the provided converter will convert between Firestore data of\n   * type `NewDbModelType` and your custom type `NewAppModelType`.\n   *\n   * @param converter - Converts objects to and from Firestore.\n   * @returns A `DocumentReference` that uses the provided converter.\n   */\n  withConverter<\n    NewAppModelType,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n  ): DocumentReference<NewAppModelType, NewDbModelType>;\n  /**\n   * Removes the current converter.\n   *\n   * @param converter - `null` removes the current converter.\n   * @returns A `DocumentReference<DocumentData, DocumentData>` that does not\n   * use a converter.\n   */\n  withConverter(converter: null): DocumentReference<DocumentData, DocumentData>;\n  withConverter<\n    NewAppModelType,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n  ): DocumentReference<NewAppModelType, NewDbModelType> {\n    return new DocumentReference<NewAppModelType, NewDbModelType>(\n      this.firestore,\n      converter,\n      this._key\n    );\n  }\n\n  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<NewAppModelType, NewDbModelType>\n  ): DocumentReference<NewAppModelType, NewDbModelType>;\n  static fromJSON<\n    NewAppModelType = DocumentData,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    firestore: Firestore,\n    json: object,\n    converter?: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n  ): DocumentReference<NewAppModelType, NewDbModelType> {\n    if (validateJSON(json, DocumentReference._jsonSchema)) {\n      return new DocumentReference<NewAppModelType, NewDbModelType>(\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<AppModelType, DbModelType> {\n  /** The type of this Firestore reference. */\n  readonly type = 'collection';\n\n  /** @hideconstructor */\n  constructor(\n    firestore: Firestore,\n    converter: FirestoreDataConverter<AppModelType, DbModelType> | null,\n    readonly _path: ResourcePath\n  ) {\n    super(firestore, converter, newQueryForPath(_path));\n  }\n\n  /** The collection's identifier. */\n  get id(): string {\n    return this._query.path.lastSegment();\n  }\n\n  /**\n   * A string representing the path of the referenced collection (relative\n   * to the root of the database).\n   */\n  get path(): string {\n    return this._query.path.canonicalString();\n  }\n\n  /**\n   * A reference to the containing `DocumentReference` if this is a\n   * subcollection. If this isn't a subcollection, the reference is null.\n   */\n  get parent(): DocumentReference<DocumentData, DocumentData> | null {\n    const parentPath = this._path.popLast();\n    if (parentPath.isEmpty()) {\n      return null;\n    } else {\n      return new DocumentReference(\n        this.firestore,\n        /* converter= */ null,\n        new DocumentKey(parentPath)\n      );\n    }\n  }\n\n  /**\n   * Applies a custom data converter to this `CollectionReference`, allowing you\n   * to use your own custom model objects with Firestore. When you call {@link\n   * addDoc} with the returned `CollectionReference` instance, the provided\n   * converter will convert between Firestore data of type `NewDbModelType` and\n   * your custom type `NewAppModelType`.\n   *\n   * @param converter - Converts objects to and from Firestore.\n   * @returns A `CollectionReference` that uses the provided converter.\n   */\n  withConverter<\n    NewAppModelType,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n  ): CollectionReference<NewAppModelType, NewDbModelType>;\n  /**\n   * Removes the current converter.\n   *\n   * @param converter - `null` removes the current converter.\n   * @returns A `CollectionReference<DocumentData, DocumentData>` that does not\n   * use a converter.\n   */\n  withConverter(\n    converter: null\n  ): CollectionReference<DocumentData, DocumentData>;\n  withConverter<\n    NewAppModelType,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n  ): CollectionReference<NewAppModelType, NewDbModelType> {\n    return new CollectionReference<NewAppModelType, NewDbModelType>(\n      this.firestore,\n      converter,\n      this._path\n    );\n  }\n}\n\nexport function isCollectionReference(\n  val: unknown\n): val is CollectionReference {\n  return val instanceof CollectionReference;\n}\n\n/**\n * Gets a `CollectionReference` instance that refers to the collection at\n * the specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n  firestore: Firestore,\n  path: string,\n  ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n  reference: CollectionReference<AppModelType, DbModelType>,\n  path: string,\n  ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  path: string,\n  ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n  parent:\n    | Firestore\n    | DocumentReference<AppModelType, DbModelType>\n    | CollectionReference<AppModelType, DbModelType>,\n  path: string,\n  ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData> {\n  parent = getModularInstance(parent);\n\n  validateNonEmptyArgument('collection', 'path', path);\n  if (parent instanceof Firestore) {\n    const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n    validateCollectionPath(absolutePath);\n    return new CollectionReference(parent, /* converter= */ null, absolutePath);\n  } else {\n    if (\n      !(parent instanceof DocumentReference) &&\n      !(parent instanceof CollectionReference)\n    ) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Expected first argument to collection() to be a CollectionReference, ' +\n          'a DocumentReference or FirebaseFirestore'\n      );\n    }\n    const absolutePath = parent._path.child(\n      ResourcePath.fromString(path, ...pathSegments)\n    );\n    validateCollectionPath(absolutePath);\n    return new CollectionReference(\n      parent.firestore,\n      /* converter= */ null,\n      absolutePath\n    );\n  }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */\nexport function collectionGroup(\n  firestore: Firestore,\n  collectionId: string\n): Query<DocumentData, DocumentData> {\n  firestore = cast(firestore, Firestore);\n\n  validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);\n  if (collectionId.indexOf('/') >= 0) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      `Invalid collection ID '${collectionId}' passed to function ` +\n        `collectionGroup(). Collection IDs must not contain '/'.`\n    );\n  }\n\n  return new Query(\n    firestore,\n    /* converter= */ null,\n    newQueryForCollectionGroup(collectionId)\n  );\n}\n\n/**\n * Gets a `DocumentReference` instance that refers to the document at the\n * specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n  firestore: Firestore,\n  path: string,\n  ...pathSegments: string[]\n): DocumentReference<DocumentData, DocumentData>;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path. If no path is specified, an\n * automatically-generated unique ID will be used for the returned\n * `DocumentReference`.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a document. Has to be omitted to use\n * auto-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<AppModelType, DbModelType extends DocumentData>(\n  reference: CollectionReference<AppModelType, DbModelType>,\n  path?: string,\n  ...pathSegments: string[]\n): DocumentReference<AppModelType, DbModelType>;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  path: string,\n  ...pathSegments: string[]\n): DocumentReference<DocumentData, DocumentData>;\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n  parent:\n    | Firestore\n    | CollectionReference<AppModelType, DbModelType>\n    | DocumentReference<AppModelType, DbModelType>,\n  path?: string,\n  ...pathSegments: string[]\n): DocumentReference<AppModelType, DbModelType> {\n  parent = getModularInstance(parent);\n\n  // We allow omission of 'pathString' but explicitly prohibit passing in both\n  // 'undefined' and 'null'.\n  if (arguments.length === 1) {\n    path = AutoId.newId();\n  }\n  validateNonEmptyArgument('doc', 'path', path);\n\n  if (parent instanceof Firestore) {\n    const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n    validateDocumentPath(absolutePath);\n    return new DocumentReference(\n      parent,\n      /* converter= */ null,\n      new DocumentKey(absolutePath)\n    );\n  } else {\n    if (\n      !(parent instanceof DocumentReference) &&\n      !(parent instanceof CollectionReference)\n    ) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Expected first argument to doc() to be a CollectionReference, ' +\n          'a DocumentReference or FirebaseFirestore'\n      );\n    }\n    const absolutePath = parent._path.child(\n      ResourcePath.fromString(path, ...pathSegments)\n    );\n    validateDocumentPath(absolutePath);\n    return new DocumentReference<AppModelType, DbModelType>(\n      parent.firestore,\n      parent instanceof CollectionReference ? parent.converter : null,\n      new DocumentKey(absolutePath)\n    );\n  }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function refEqual<AppModelType, DbModelType extends DocumentData>(\n  left:\n    | DocumentReference<AppModelType, DbModelType>\n    | CollectionReference<AppModelType, DbModelType>,\n  right:\n    | DocumentReference<AppModelType, DbModelType>\n    | CollectionReference<AppModelType, DbModelType>\n): boolean {\n  left = getModularInstance(left);\n  right = getModularInstance(right);\n\n  if (\n    (left instanceof DocumentReference ||\n      left instanceof CollectionReference) &&\n    (right instanceof DocumentReference || right instanceof CollectionReference)\n  ) {\n    return (\n      left.firestore === right.firestore &&\n      left.path === right.path &&\n      left.converter === right.converter\n    );\n  }\n  return false;\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function queryEqual<AppModelType, DbModelType extends DocumentData>(\n  left: Query<AppModelType, DbModelType>,\n  right: Query<AppModelType, DbModelType>\n): boolean {\n  left = getModularInstance(left);\n  right = getModularInstance(right);\n\n  if (left instanceof Query && right instanceof Query) {\n    return (\n      left.firestore === right.firestore &&\n      queryEquals(left._query, right._query) &&\n      left.converter === right.converter\n    );\n  }\n  return false;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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<T>(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<T>(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<A>(\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<T>(\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 * @returns True if arrays are equal.\n */\nexport function isArrayEqual<T extends { isEqual: (t: T) => 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 * @returns True if arrays are equal.\n */\nexport function isPrimitiveArrayEqual<T extends number | string>(\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 <code>{@link vector}</code>.\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 { ContextSettings, 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  NumericMaximumTransformOperation,\n  NumericMinimumTransformOperation,\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  isProtoValueSerializable\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<AppModelType>\n  ): WithFieldValue<DbModelType>;\n  toFirestore(\n    modelObject: PartialWithFieldValue<AppModelType>,\n    options: SetOptions\n  ): PartialWithFieldValue<DbModelType>;\n  fromFirestore(snapshot: unknown, options?: unknown): AppModelType;\n}\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n  constructor(\n    readonly data: ObjectValue,\n    readonly fieldMask: FieldMask | null,\n    readonly fieldTransforms: FieldTransform[]\n  ) {}\n\n  toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n    if (this.fieldMask !== null) {\n      return new PatchMutation(\n        key,\n        this.data,\n        this.fieldMask,\n        precondition,\n        this.fieldTransforms\n      );\n    } else {\n      return new SetMutation(\n        key,\n        this.data,\n        precondition,\n        this.fieldTransforms\n      );\n    }\n  }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n  constructor(\n    readonly data: ObjectValue,\n    // The fieldMask does not include document transforms.\n    readonly fieldMask: FieldMask,\n    readonly fieldTransforms: FieldTransform[]\n  ) {}\n\n  toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n    return new PatchMutation(\n      key,\n      this.data,\n      this.fieldMask,\n      precondition,\n      this.fieldTransforms\n    );\n  }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nexport const enum UserDataSource {\n  Set,\n  Update,\n  MergeSet,\n  /**\n   * Indicates the source is a where clause, cursor bound, arrayUnion()\n   * element, etc. Of note, isWrite(source) will return false.\n   */\n  Argument,\n  /**\n   * Indicates that the source is an Argument that may directly contain nested\n   * arrays (e.g. the operand of an `in` query).\n   */\n  ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n  switch (dataSource) {\n    case UserDataSource.Set: // fall through\n    case UserDataSource.MergeSet: // fall through\n    case UserDataSource.Update:\n      return true;\n    case UserDataSource.Argument:\n    case UserDataSource.ArrayArgument:\n      return false;\n    default:\n      throw fail(0x9c4b, 'Unexpected case for UserDataSource', {\n        dataSource\n      });\n  }\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContextImpl implements ParseContext {\n  readonly fieldTransforms: FieldTransform[];\n  readonly fieldMask: InternalFieldPath[];\n  /**\n   * Initializes a ParseContext with the given source and path.\n   *\n   * @param settings - The settings for the parser.\n   * @param databaseId - The database ID of the Firestore instance.\n   * @param serializer - The serializer to use to generate the Value proto.\n   * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n   * rather than throw.\n   * @param fieldTransforms - A mutable list of field transforms encountered\n   * while parsing the data.\n   * @param fieldMask - A mutable list of field paths encountered while parsing\n   * the data.\n   *\n   * TODO(b/34871131): We don't support array paths right now, so path can be\n   * null to indicate the context represents any location within an array (in\n   * which case certain features will not work and errors will be somewhat\n   * compromised).\n   */\n  constructor(\n    readonly settings: ContextSettings,\n    readonly databaseId: DatabaseId,\n    readonly serializer: JsonProtoSerializer,\n    readonly ignoreUndefinedProperties: boolean,\n    fieldTransforms?: FieldTransform[],\n    fieldMask?: InternalFieldPath[]\n  ) {\n    // Minor hack: If fieldTransforms is undefined, we assume this is an\n    // external call and we need to validate the entire path.\n    if (fieldTransforms === undefined) {\n      this.validatePath();\n    }\n    this.fieldTransforms = fieldTransforms || [];\n    this.fieldMask = fieldMask || [];\n  }\n\n  get path(): InternalFieldPath | undefined {\n    return this.settings.path;\n  }\n\n  get dataSource(): UserDataSource {\n    return this.settings.dataSource;\n  }\n\n  /** Returns a new context with the specified settings overwritten. */\n  contextWith(configuration: Partial<ContextSettings>): ParseContextImpl {\n    return new ParseContextImpl(\n      { ...this.settings, ...configuration },\n      this.databaseId,\n      this.serializer,\n      this.ignoreUndefinedProperties,\n      this.fieldTransforms,\n      this.fieldMask\n    );\n  }\n\n  childContextForField(field: string): ParseContextImpl {\n    const childPath = this.path?.child(field);\n    const context = this.contextWith({ path: childPath, arrayElement: false });\n    context.validatePathSegment(field);\n    return context;\n  }\n\n  childContextForFieldPath(field: InternalFieldPath): ParseContextImpl {\n    const childPath = this.path?.child(field);\n    const context = this.contextWith({ path: childPath, arrayElement: false });\n    context.validatePath();\n    return context;\n  }\n\n  childContextForArray(index: number): ParseContextImpl {\n    // TODO(b/34871131): We don't support array paths right now; so make path\n    // undefined.\n    return this.contextWith({ path: undefined, arrayElement: true });\n  }\n\n  createError(reason: string): FirestoreError {\n    return createError(\n      reason,\n      this.settings.methodName,\n      this.settings.hasConverter || false,\n      this.path,\n      this.settings.targetDoc\n    );\n  }\n\n  /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n  contains(fieldPath: InternalFieldPath): boolean {\n    return (\n      this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n      this.fieldTransforms.find(transform =>\n        fieldPath.isPrefixOf(transform.field)\n      ) !== undefined\n    );\n  }\n\n  private validatePath(): void {\n    // TODO(b/34871131): Remove null check once we have proper paths for fields\n    // within arrays.\n    if (!this.path) {\n      return;\n    }\n    for (let i = 0; i < this.path.length; i++) {\n      this.validatePathSegment(this.path.get(i));\n    }\n  }\n\n  private validatePathSegment(segment: string): void {\n    if (segment.length === 0) {\n      throw this.createError('Document fields must not be empty');\n    }\n    if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n      throw this.createError('Document fields cannot begin and end with \"__\"');\n    }\n  }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataReader {\n  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        (Number.isNaN(this._operand) && Number.isNaN(other._operand)))\n    );\n  }\n}\n\nexport class NumericMinimumFieldValueImpl extends FieldValue {\n  constructor(methodName: string, private readonly _operand: number) {\n    super(methodName);\n  }\n\n  _toFieldTransform(context: ParseContextImpl): FieldTransform {\n    const numericMinimum = new NumericMinimumTransformOperation(\n      context.serializer,\n      toNumber(context.serializer, this._operand)\n    );\n    return new FieldTransform(context.path!, numericMinimum);\n  }\n\n  isEqual(other: FieldValue): boolean {\n    return (\n      other instanceof NumericMinimumFieldValueImpl &&\n      (this._operand === other._operand ||\n        (Number.isNaN(this._operand) && Number.isNaN(other._operand)))\n    );\n  }\n}\n\nexport class NumericMaximumFieldValueImpl extends FieldValue {\n  constructor(methodName: string, private readonly _operand: number) {\n    super(methodName);\n  }\n\n  _toFieldTransform(context: ParseContextImpl): FieldTransform {\n    const numericMaximum = new NumericMaximumTransformOperation(\n      context.serializer,\n      toNumber(context.serializer, this._operand)\n    );\n    return new FieldTransform(context.path!, numericMaximum);\n  }\n\n  isEqual(other: FieldValue): boolean {\n    return (\n      other instanceof NumericMaximumFieldValueImpl &&\n      (this._operand === other._operand ||\n        (Number.isNaN(this._operand) && Number.isNaN(other._operand)))\n    );\n  }\n}\n\n/** Parse update data from an update() call. */\nexport function parseUpdateData(\n  userDataReader: UserDataReader,\n  methodName: string,\n  targetDoc: DocumentKey,\n  input: unknown\n): ParsedUpdateData {\n  const context = userDataReader.createContext(\n    UserDataSource.Update,\n    methodName,\n    targetDoc\n  );\n  validatePlainObject('Data must be an object, but it was:', context, input);\n\n  const fieldMaskPaths: InternalFieldPath[] = [];\n  const updateData = ObjectValue.empty();\n  forEach(input as Dict<unknown>, (key, value) => {\n    const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);\n\n    // For Compat types, we have to \"extract\" the underlying types before\n    // performing validation.\n    value = getModularInstance(value);\n\n    const childContext = context.childContextForFieldPath(path);\n    if (value instanceof DeleteFieldValueImpl) {\n      // Add it to the field mask, but don't add anything to updateData.\n      fieldMaskPaths.push(path);\n    } else {\n      const parsedValue = parseData(value, childContext);\n      if (parsedValue != null) {\n        fieldMaskPaths.push(path);\n        updateData.set(path, parsedValue);\n      }\n    }\n  });\n\n  const mask = new FieldMask(fieldMaskPaths);\n  return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */\nexport function parseUpdateVarargs(\n  userDataReader: UserDataReader,\n  methodName: string,\n  targetDoc: DocumentKey,\n  field: string | PublicFieldPath | Compat<PublicFieldPath>,\n  value: unknown,\n  moreFieldsAndValues: unknown[]\n): ParsedUpdateData {\n  const context = userDataReader.createContext(\n    UserDataSource.Update,\n    methodName,\n    targetDoc\n  );\n  const keys = [fieldPathFromArgument(methodName, field, targetDoc)];\n  const values = [value];\n\n  if (moreFieldsAndValues.length % 2 !== 0) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      `Function ${methodName}() needs to be called with an even number ` +\n        'of arguments that alternate between field names and values.'\n    );\n  }\n\n  for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n    keys.push(\n      fieldPathFromArgument(\n        methodName,\n        moreFieldsAndValues[i] as string | PublicFieldPath\n      )\n    );\n    values.push(moreFieldsAndValues[i + 1]);\n  }\n\n  const fieldMaskPaths: InternalFieldPath[] = [];\n  const updateData = ObjectValue.empty();\n\n  // We iterate in reverse order to pick the last value for a field if the\n  // user specified the field multiple times.\n  for (let i = keys.length - 1; i >= 0; --i) {\n    if (!fieldMaskContains(fieldMaskPaths, keys[i])) {\n      const path = keys[i];\n      let value = values[i];\n\n      // For Compat types, we have to \"extract\" the underlying types before\n      // performing validation.\n      value = getModularInstance(value);\n\n      const childContext = context.childContextForFieldPath(path);\n      if (value instanceof DeleteFieldValueImpl) {\n        // Add it to the field mask, but don't add anything to updateData.\n        fieldMaskPaths.push(path);\n      } else {\n        const parsedValue = parseData(value, childContext);\n        if (parsedValue != null) {\n          fieldMaskPaths.push(path);\n          updateData.set(path, parsedValue);\n        }\n      }\n    }\n  }\n\n  const mask = new FieldMask(fieldMaskPaths);\n  return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */\nexport function parseQueryValue(\n  userDataReader: UserDataReader,\n  methodName: string,\n  input: unknown,\n  allowArrays = false\n): ProtoValue {\n  const context = userDataReader.createContext(\n    allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n    methodName\n  );\n  const parsed = parseData(input, context);\n  debugAssert(parsed != null, 'Parsed data should not be null.');\n  debugAssert(\n    context.fieldTransforms.length === 0,\n    'Field transforms should have been disallowed.'\n  );\n  return parsed;\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\nexport function parseData(\n  input: unknown,\n  context: ParseContext,\n  options?: { preferIntegers: boolean }\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, options);\n    }\n  }\n}\n\nexport function parseObject(\n  obj: Dict<unknown>,\n  context: ParseContext\n): { mapValue: ProtoMapValue } {\n  const fields: Dict<ProtoValue> = {};\n\n  if (isEmpty(obj)) {\n    // If we encounter an empty object, we explicitly add it to the update\n    // mask to ensure that the server creates a map entry.\n    if (context.path && context.path.length > 0) {\n      context.fieldMask.push(context.path);\n    }\n  } else {\n    forEach(obj, (key: string, val: unknown) => {\n      const parsedValue = parseData(val, context.childContextForField(key));\n      if (parsedValue != null) {\n        fields[key] = parsedValue;\n      }\n    });\n  }\n\n  return { mapValue: { fields } };\n}\n\nfunction parseArray(array: unknown[], context: ParseContext): 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: ParseContext\n): void {\n  // Sentinels are only supported with writes, and not within arrays.\n  if (!isWrite(context.dataSource)) {\n    throw context.createError(\n      `${value._methodName}() can only be used with update() and set()`\n    );\n  }\n  if (!context.path) {\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 */\nexport function parseScalarValue(\n  value: unknown,\n  context: ParseContext,\n  options?: { preferIntegers: boolean }\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, options);\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 if (isProtoValueSerializable(value)) {\n    return value._toProto(context.serializer);\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 | number[],\n  context: ParseContext\n): { mapValue: ProtoMapValue } {\n  const values = value instanceof VectorValue ? value.toArray() : value;\n  const mapValue: ProtoMapValue = {\n    fields: {\n      [TYPE_KEY]: {\n        stringValue: VECTOR_VALUE_SENTINEL\n      },\n      [VECTOR_MAP_VECTORS_KEY]: {\n        arrayValue: {\n          values: values.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 */\nexport function 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    !isProtoValueSerializable(input)\n  );\n}\n\nfunction validatePlainObject(\n  message: string,\n  context: ParseContext,\n  input: unknown\n): asserts input is Dict<unknown> {\n  if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n    const description = valueDescription(input);\n    if (description === 'an object') {\n      // Massage the error if it was an object.\n      throw context.createError(message + ' a custom object');\n    } else {\n      throw context.createError(message + ' ' + description);\n    }\n  }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n  methodName: string,\n  path: string | PublicFieldPath | Compat<PublicFieldPath>,\n  targetDoc?: DocumentKey\n): InternalFieldPath {\n  // If required, replace the FieldPath Compat class with 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\nexport interface UserData {\n  _readUserData(context: ParseContext): void;\n}\n\nexport function isUserData(value: unknown): value is UserData {\n  return typeof (value as UserData)._readUserData === 'function';\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 { ParseContext } from '../api/parse_context';\nimport { parseData } from '../lite-api/user_data_reader';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { isPlainObject } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\nexport type OptionsDefinitions = Record<string, OptionDefinition>;\nexport interface OptionDefinition {\n  serverName: string;\n  nestedOptions?: OptionsDefinitions;\n}\n\nexport class OptionsUtil {\n  constructor(private optionDefinitions: OptionsDefinitions) {}\n\n  private _getKnownOptions(\n    options: Record<string, unknown>,\n    context: ParseContext\n  ): ObjectValue {\n    const knownOptions: ObjectValue = ObjectValue.empty();\n\n    // SERIALIZE KNOWN OPTIONS\n    for (const knownOptionKey in this.optionDefinitions) {\n      if (this.optionDefinitions.hasOwnProperty(knownOptionKey)) {\n        const optionDefinition: OptionDefinition =\n          this.optionDefinitions[knownOptionKey];\n\n        if (knownOptionKey in options) {\n          const optionValue: unknown = options[knownOptionKey];\n          let protoValue: Value | undefined = undefined;\n\n          if (optionDefinition.nestedOptions && isPlainObject(optionValue)) {\n            const nestedUtil = new OptionsUtil(optionDefinition.nestedOptions);\n            protoValue = {\n              mapValue: {\n                fields: nestedUtil.getOptionsProto(context, optionValue)\n              }\n            };\n          } else if (optionValue) {\n            protoValue = parseData(optionValue, context) ?? undefined;\n          }\n\n          if (protoValue) {\n            knownOptions.set(\n              FieldPath.fromServerFormat(optionDefinition.serverName),\n              protoValue\n            );\n          }\n        }\n      }\n    }\n\n    return knownOptions;\n  }\n\n  getOptionsProto(\n    context: ParseContext,\n    knownOptions: Record<string, unknown>,\n    optionsOverride?: Record<string, unknown>\n  ): ApiClientObjectMap<Value> | undefined {\n    const result: ObjectValue = this._getKnownOptions(knownOptions, context);\n\n    // APPLY OPTIONS OVERRIDES\n    if (optionsOverride) {\n      const optionsMap = new Map(\n        mapToArray(optionsOverride, (value, key) => [\n          FieldPath.fromServerFormat(key),\n          value !== undefined ? parseData(value, context) : null\n        ])\n      );\n      result.setAll(optionsMap);\n    }\n\n    // Return MapValue from `result` or empty map value\n    return result.value.mapValue.fields ?? {};\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 {\n  ArrayValue as ProtoArrayValue,\n  Function as ProtoFunction,\n  LatLng as ProtoLatLng,\n  MapValue as ProtoMapValue,\n  Pipeline as ProtoPipeline,\n  Timestamp as ProtoTimestamp,\n  Value as ProtoValue\n} from '../protos/firestore_proto_api';\n\nimport { isPlainObject } from './input_validation';\n\n/* eslint @typescript-eslint/no-explicit-any: 0 */\n\nfunction isITimestamp(obj: any): obj is ProtoTimestamp {\n  if (typeof obj !== 'object' || obj === null) {\n    return false; // Must be a non-null object\n  }\n  if (\n    'seconds' in obj &&\n    (obj.seconds === null ||\n      typeof obj.seconds === 'number' ||\n      typeof obj.seconds === 'string') &&\n    'nanos' in obj &&\n    (obj.nanos === null || typeof obj.nanos === 'number')\n  ) {\n    return true;\n  }\n\n  return false;\n}\nfunction isILatLng(obj: any): obj is ProtoLatLng {\n  if (typeof obj !== 'object' || obj === null) {\n    return false; // Must be a non-null object\n  }\n  if (\n    'latitude' in obj &&\n    (obj.latitude === null || typeof obj.latitude === 'number') &&\n    'longitude' in obj &&\n    (obj.longitude === null || typeof obj.longitude === 'number')\n  ) {\n    return true;\n  }\n\n  return false;\n}\nfunction isIArrayValue(obj: any): obj is ProtoArrayValue {\n  if (typeof obj !== 'object' || obj === null) {\n    return false; // Must be a non-null object\n  }\n  if ('values' in obj && (obj.values === null || Array.isArray(obj.values))) {\n    return true;\n  }\n\n  return false;\n}\nfunction isIMapValue(obj: any): obj is ProtoMapValue {\n  if (typeof obj !== 'object' || obj === null) {\n    return false; // Must be a non-null object\n  }\n  if ('fields' in obj && (obj.fields === null || isPlainObject(obj.fields))) {\n    return true;\n  }\n\n  return false;\n}\nfunction isIFunction(obj: any): obj is ProtoFunction {\n  if (typeof obj !== 'object' || obj === null) {\n    return false; // Must be a non-null object\n  }\n  if (\n    'name' in obj &&\n    (obj.name === null || typeof obj.name === 'string') &&\n    'args' in obj &&\n    (obj.args === null || Array.isArray(obj.args))\n  ) {\n    return true;\n  }\n\n  return false;\n}\n\nfunction isIPipeline(obj: any): obj is ProtoPipeline {\n  if (typeof obj !== 'object' || obj === null) {\n    return false; // Must be a non-null object\n  }\n  if ('stages' in obj && (obj.stages === null || Array.isArray(obj.stages))) {\n    return true;\n  }\n\n  return false;\n}\n\nexport function isFirestoreValue(obj: any): obj is ProtoValue {\n  if (typeof obj !== 'object' || obj === null) {\n    return false; // Must be a non-null object\n  }\n\n  // Check optional properties and their types\n  if (\n    ('nullValue' in obj &&\n      (obj.nullValue === null || obj.nullValue === 'NULL_VALUE')) ||\n    ('booleanValue' in obj &&\n      (obj.booleanValue === null || typeof obj.booleanValue === 'boolean')) ||\n    ('integerValue' in obj &&\n      (obj.integerValue === null ||\n        typeof obj.integerValue === 'number' ||\n        typeof obj.integerValue === 'string')) ||\n    ('doubleValue' in obj &&\n      (obj.doubleValue === null || typeof obj.doubleValue === 'number')) ||\n    ('timestampValue' in obj &&\n      (obj.timestampValue === null || isITimestamp(obj.timestampValue))) ||\n    ('stringValue' in obj &&\n      (obj.stringValue === null || typeof obj.stringValue === 'string')) ||\n    ('bytesValue' in obj &&\n      (obj.bytesValue === null || obj.bytesValue instanceof Uint8Array)) ||\n    ('referenceValue' in obj &&\n      (obj.referenceValue === null ||\n        typeof obj.referenceValue === 'string')) ||\n    ('geoPointValue' in obj &&\n      (obj.geoPointValue === null || isILatLng(obj.geoPointValue))) ||\n    ('arrayValue' in obj &&\n      (obj.arrayValue === null || isIArrayValue(obj.arrayValue))) ||\n    ('mapValue' in obj &&\n      (obj.mapValue === null || isIMapValue(obj.mapValue))) ||\n    ('fieldReferenceValue' in obj &&\n      (obj.fieldReferenceValue === null ||\n        typeof obj.fieldReferenceValue === 'string')) ||\n    ('functionValue' in obj &&\n      (obj.functionValue === null || isIFunction(obj.functionValue))) ||\n    ('pipelineValue' in obj &&\n      (obj.pipelineValue === null || isIPipeline(obj.pipelineValue)))\n  ) {\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 { FieldValue } from './field_value';\nimport {\n  ArrayRemoveFieldValueImpl,\n  ArrayUnionFieldValueImpl,\n  DeleteFieldValueImpl,\n  NumericIncrementFieldValueImpl,\n  NumericMaximumFieldValueImpl,\n  NumericMinimumFieldValueImpl,\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 * 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 set the field to the numeric minimum of the\n * field's current and the given value.\n *\n * @param n - The value to compare to the existing field value.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function minimum(n: number): FieldValue {\n  return new NumericMinimumFieldValueImpl('minimum', n);\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 set the field to the numeric maximum of the\n * field's current and the given value.\n *\n * @param n - The value to compare to the existing field value.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function maximum(n: number): FieldValue {\n  return new NumericMaximumFieldValueImpl('maximum', 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 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 { ParseContext } from '../api/parse_context';\nimport { OptionsUtil } from '../core/options_util';\nimport {\n  DOCUMENT_KEY_NAME,\n  FieldPath as InternalFieldPath\n} from '../model/path';\nimport {\n  ApiClientObjectMap,\n  firestoreV1ApiClientInterfaces,\n  Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport {\n  JsonProtoSerializer,\n  ProtoValueSerializable,\n  toMapValue,\n  toPipelineValue,\n  toStringValue\n} from '../remote/serializer';\nimport { hardAssert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\nimport { isPlainObject } from '../util/input_validation';\nimport { isFirestoreValue } from '../util/proto';\nimport { isString } from '../util/types';\n\nimport { Bytes } from './bytes';\nimport { documentId as documentIdFieldPath, FieldPath } from './field_path';\nimport { vector } from './field_value_impl';\nimport { GeoPoint } from './geo_point';\nimport type { Pipeline } from './pipeline';\nimport { DocumentReference } from './reference';\nimport { Timestamp } from './timestamp';\nimport { fieldPathFromArgument, parseData, UserData } from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n *\n * An enumeration of the different types of expressions.\n */\nexport type ExpressionType =\n  | 'Field'\n  | 'Constant'\n  | 'Function'\n  | 'AggregateFunction'\n  | 'ListOfExpressions'\n  | 'AliasedExpression'\n  | 'Variable'\n  | 'PipelineValue';\n\n/**\n * Converts a value to an Expression, Returning either a Constant, MapFunction,\n * ArrayFunction, or the input itself (if it's already an expression).\n *\n * @private\n * @internal\n * @param value\n */\nfunction valueToDefaultExpr(value: unknown): Expression {\n  let result: Expression | undefined;\n  if (value instanceof Expression) {\n    return value;\n  } else if (isPlainObject(value)) {\n    result = _map(value as Record<string, unknown>, undefined);\n  } else if (value instanceof Array) {\n    result = array(value);\n  } else {\n    result = _constant(value, undefined);\n  }\n\n  return result;\n}\n\n/**\n * Converts a value to an Expression, Returning either a Constant, MapFunction,\n * ArrayFunction, or the input itself (if it's already an expression).\n *\n * @private\n * @internal\n * @param value\n */\nfunction vectorToExpr(value: VectorValue | number[] | Expression): Expression {\n  if (value instanceof Expression) {\n    return value;\n  } else if (value instanceof VectorValue) {\n    return constant(value);\n  } else if (Array.isArray(value)) {\n    return constant(vector(value));\n  } else {\n    throw new Error('Unsupported value: ' + typeof value);\n  }\n}\n\n/**\n * Converts a value to an Expression, Returning either a Constant, MapFunction,\n * ArrayFunction, or the input itself (if it's already an expression).\n * If the input is a string, it is assumed to be a field name, and a\n * field(value) is returned.\n *\n * @private\n * @internal\n * @param value\n */\nfunction fieldOrExpression(value: unknown): Expression {\n  if (isString(value)) {\n    const result = field(value);\n    return result;\n  } else {\n    return valueToDefaultExpr(value);\n  }\n}\n/**\n *\n * Represents an expression that can be evaluated to a value within the execution of a {@link\n * @firebase/firestore/pipelines#Pipeline}.\n *\n * Expressions are the building blocks for creating complex queries and transformations in\n * Firestore pipelines. They can represent:\n *\n * - **Field references:** Access values from document fields.\n * - **Literals:** Represent constant values (strings, numbers, booleans).\n * - **Function calls:** Apply functions to one or more expressions.\n *\n * The `Expression` class provides a fluent API for building expressions. You can chain together\n * method calls to create complex expressions.\n */\nexport abstract class Expression implements ProtoValueSerializable, UserData {\n  abstract readonly expressionType: ExpressionType;\n\n  abstract readonly _methodName?: string;\n\n  /**\n   * @private\n   * @internal\n   */\n  abstract _toProto(serializer: JsonProtoSerializer): ProtoValue;\n  _protoValueType = 'ProtoValue' as const;\n\n  /**\n   * @private\n   * @internal\n   */\n  abstract _readUserData(context: ParseContext): void;\n\n  /**\n   * Creates an expression that adds this expression to another expression.\n   *\n   * @example\n   * ```typescript\n   * // Add the value of the 'quantity' field and the 'reserve' field.\n   * field(\"quantity\").add(field(\"reserve\"));\n   * ```\n   *\n   * @param second - The expression or literal to add to this expression.\n   * @param others - Optional additional expressions or literals to add to this expression.\n   * @returns A new `Expression` representing the addition operation.\n   */\n  add(second: Expression | unknown): FunctionExpression {\n    return new FunctionExpression(\n      'add',\n      [this, valueToDefaultExpr(second)],\n      'add'\n    );\n  }\n\n  /**\n   * Wraps the expression in a [BooleanExpression].\n   *\n   * @returns A [BooleanExpression] representing the same expression.\n   */\n  asBoolean(): BooleanExpression {\n    if (this instanceof BooleanExpression) {\n      return this;\n    } else if (this instanceof Constant) {\n      return new BooleanConstant(this);\n    } else if (this instanceof Field) {\n      return new BooleanField(this);\n    } else if (this instanceof FunctionExpression) {\n      return new BooleanFunctionExpression(this);\n    } else {\n      throw new FirestoreError(\n        'invalid-argument',\n        `Conversion of type ${typeof this} to BooleanExpression not supported.`\n      );\n    }\n  }\n\n  /**\n   * Creates an expression that subtracts another expression from this expression.\n   *\n   * @example\n   * ```typescript\n   * // Subtract the 'discount' field from the 'price' field\n   * field(\"price\").subtract(field(\"discount\"));\n   * ```\n   *\n   * @param subtrahend - The expression to subtract from this expression.\n   * @returns A new `Expression` representing the subtraction operation.\n   */\n  subtract(subtrahend: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that subtracts a constant value from this expression.\n   *\n   * @example\n   * ```typescript\n   * // Subtract 20 from the value of the 'total' field\n   * field(\"total\").subtract(20);\n   * ```\n   *\n   * @param subtrahend - The constant value to subtract.\n   * @returns A new `Expression` representing the subtraction operation.\n   */\n  subtract(subtrahend: number): FunctionExpression;\n  subtract(subtrahend: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'subtract',\n      [this, valueToDefaultExpr(subtrahend)],\n      'subtract'\n    );\n  }\n\n  /**\n   * Creates an expression that multiplies this expression by another expression.\n   *\n   * @example\n   * ```typescript\n   * // Multiply the 'quantity' field by the 'price' field\n   * field(\"quantity\").multiply(field(\"price\"));\n   * ```\n   *\n   * @param second - The second expression or literal to multiply by.\n   * @param others - Optional additional expressions or literals to multiply by.\n   * @returns A new `Expression` representing the multiplication operation.\n   */\n  multiply(second: Expression | number): FunctionExpression {\n    return new FunctionExpression(\n      'multiply',\n      [this, valueToDefaultExpr(second)],\n      'multiply'\n    );\n  }\n\n  /**\n   * Creates an expression that divides this expression by another expression.\n   *\n   * @example\n   * ```typescript\n   * // Divide the 'total' field by the 'count' field\n   * field(\"total\").divide(field(\"count\"));\n   * ```\n   *\n   * @param divisor - The expression to divide by.\n   * @returns A new `Expression` representing the division operation.\n   */\n  divide(divisor: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that divides this expression by a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Divide the 'value' field by 10\n   * field(\"value\").divide(10);\n   * ```\n   *\n   * @param divisor - The constant value to divide by.\n   * @returns A new `Expression` representing the division operation.\n   */\n  divide(divisor: number): FunctionExpression;\n  divide(divisor: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'divide',\n      [this, valueToDefaultExpr(divisor)],\n      'divide'\n    );\n  }\n\n  /**\n   * Creates an expression that calculates the modulo (remainder) of dividing this expression by another expression.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the remainder of dividing the 'value' field by the 'divisor' field\n   * field(\"value\").mod(field(\"divisor\"));\n   * ```\n   *\n   * @param expression - The expression to divide by.\n   * @returns A new `Expression` representing the modulo operation.\n   */\n  mod(expression: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the remainder of dividing the 'value' field by 10\n   * field(\"value\").mod(10);\n   * ```\n   *\n   * @param value - The constant value to divide by.\n   * @returns A new `Expression` representing the modulo operation.\n   */\n  mod(value: number): FunctionExpression;\n  mod(other: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'mod',\n      [this, valueToDefaultExpr(other)],\n      'mod'\n    );\n  }\n\n  /**\n   * Creates an expression that checks if this expression is equal to another expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'age' field is equal to 21\n   * field(\"age\").equal(21);\n   * ```\n   *\n   * @param expression - The expression to compare for equality.\n   * @returns A new `Expression` representing the equality comparison.\n   */\n  equal(expression: Expression): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is equal to a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'city' field is equal to \"London\"\n   * field(\"city\").equal(\"London\");\n   * ```\n   *\n   * @param value - The constant value to compare for equality.\n   * @returns A new `Expression` representing the equality comparison.\n   */\n  equal(value: unknown): BooleanExpression;\n  equal(other: unknown): BooleanExpression {\n    return new FunctionExpression(\n      'equal',\n      [this, valueToDefaultExpr(other)],\n      'equal'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if this expression is not equal to another expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'status' field is not equal to \"completed\"\n   * field(\"status\").notEqual(\"completed\");\n   * ```\n   *\n   * @param expression - The expression to compare for inequality.\n   * @returns A new `Expression` representing the inequality comparison.\n   */\n  notEqual(expression: Expression): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is not equal to a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'country' field is not equal to \"USA\"\n   * field(\"country\").notEqual(\"USA\");\n   * ```\n   *\n   * @param value - The constant value to compare for inequality.\n   * @returns A new `Expression` representing the inequality comparison.\n   */\n  notEqual(value: unknown): BooleanExpression;\n  notEqual(other: unknown): BooleanExpression {\n    return new FunctionExpression(\n      'not_equal',\n      [this, valueToDefaultExpr(other)],\n      'notEqual'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if this expression is less than another expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'age' field is less than 'limit'\n   * field(\"age\").lessThan(field('limit'));\n   * ```\n   *\n   * @param experession - The expression to compare for less than.\n   * @returns A new `Expression` representing the less than comparison.\n   */\n  lessThan(experession: Expression): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is less than a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'price' field is less than 50\n   * field(\"price\").lessThan(50);\n   * ```\n   *\n   * @param value - The constant value to compare for less than.\n   * @returns A new `Expression` representing the less than comparison.\n   */\n  lessThan(value: unknown): BooleanExpression;\n  lessThan(other: unknown): BooleanExpression {\n    return new FunctionExpression(\n      'less_than',\n      [this, valueToDefaultExpr(other)],\n      'lessThan'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if this expression is less than or equal to another\n   * expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'quantity' field is less than or equal to 20\n   * field(\"quantity\").lessThan(constant(20));\n   * ```\n   *\n   * @param expression - The expression to compare for less than or equal to.\n   * @returns A new `Expression` representing the less than or equal to comparison.\n   */\n  lessThanOrEqual(expression: Expression): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is less than or equal to a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'score' field is less than or equal to 70\n   * field(\"score\").lessThan(70);\n   * ```\n   *\n   * @param value - The constant value to compare for less than or equal to.\n   * @returns A new `Expression` representing the less than or equal to comparison.\n   */\n  lessThanOrEqual(value: unknown): BooleanExpression;\n  lessThanOrEqual(other: unknown): BooleanExpression {\n    return new FunctionExpression(\n      'less_than_or_equal',\n      [this, valueToDefaultExpr(other)],\n      'lessThanOrEqual'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if this expression is greater than another expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'age' field is greater than the 'limit' field\n   * field(\"age\").greaterThan(field(\"limit\"));\n   * ```\n   *\n   * @param expression - The expression to compare for greater than.\n   * @returns A new `Expression` representing the greater than comparison.\n   */\n  greaterThan(expression: Expression): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is greater than a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'price' field is greater than 100\n   * field(\"price\").greaterThan(100);\n   * ```\n   *\n   * @param value - The constant value to compare for greater than.\n   * @returns A new `Expression` representing the greater than comparison.\n   */\n  greaterThan(value: unknown): BooleanExpression;\n  greaterThan(other: unknown): BooleanExpression {\n    return new FunctionExpression(\n      'greater_than',\n      [this, valueToDefaultExpr(other)],\n      'greaterThan'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if this expression is greater than or equal to another\n   * expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'quantity' field is greater than or equal to field 'requirement' plus 1\n   * field(\"quantity\").greaterThanOrEqual(field('requirement').add(1));\n   * ```\n   *\n   * @param expression - The expression to compare for greater than or equal to.\n   * @returns A new `Expression` representing the greater than or equal to comparison.\n   */\n  greaterThanOrEqual(expression: Expression): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is greater than or equal to a constant\n   * value.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'score' field is greater than or equal to 80\n   * field(\"score\").greaterThanOrEqual(80);\n   * ```\n   *\n   * @param value - The constant value to compare for greater than or equal to.\n   * @returns A new `Expression` representing the greater than or equal to comparison.\n   */\n  greaterThanOrEqual(value: unknown): BooleanExpression;\n  greaterThanOrEqual(other: unknown): BooleanExpression {\n    return new FunctionExpression(\n      'greater_than_or_equal',\n      [this, valueToDefaultExpr(other)],\n      'greaterThanOrEqual'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that concatenates an array expression with one or more other arrays.\n   *\n   * @example\n   * ```typescript\n   * // Combine the 'items' array with another array field.\n   * field(\"items\").arrayConcat(field(\"otherItems\"));\n   * ```\n   * @param secondArray - Second array expression or array literal to concatenate.\n   * @param otherArrays - Optional additional array expressions or array literals to concatenate.\n   * @returns A new `Expression` representing the concatenated array.\n   */\n  arrayConcat(\n    secondArray: Expression | unknown[],\n    ...otherArrays: Array<Expression | unknown[]>\n  ): FunctionExpression {\n    const elements = [secondArray, ...otherArrays];\n    const exprValues = elements.map(value => valueToDefaultExpr(value));\n    return new FunctionExpression(\n      'array_concat',\n      [this, ...exprValues],\n      'arrayConcat'\n    );\n  }\n\n  /**\n   * Creates an expression that checks if an array contains a specific element.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'sizes' array contains the value from the 'selectedSize' field\n   * field(\"sizes\").arrayContains(field(\"selectedSize\"));\n   * ```\n   *\n   * @param expression - The element to search for in the array.\n   * @returns A new `Expression` representing the 'array_contains' comparison.\n   */\n  arrayContains(expression: Expression): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if an array contains a specific value.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'colors' array contains \"red\"\n   * field(\"colors\").arrayContains(\"red\");\n   * ```\n   *\n   * @param value - The element to search for in the array.\n   * @returns A new `Expression` representing the 'array_contains' comparison.\n   */\n  arrayContains(value: unknown): BooleanExpression;\n  arrayContains(element: unknown): BooleanExpression {\n    return new FunctionExpression(\n      'array_contains',\n      [this, valueToDefaultExpr(element)],\n      'arrayContains'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if an array contains all the specified elements.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'tags' array contains both the value in field \"tag1\" and the literal value \"tag2\"\n   * field(\"tags\").arrayContainsAll([field(\"tag1\"), \"tag2\"]);\n   * ```\n   *\n   * @param values - The elements to check for in the array.\n   * @returns A new `Expression` representing the 'array_contains_all' comparison.\n   */\n  arrayContainsAll(values: Array<Expression | unknown>): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if an array contains all the specified elements.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'tags' array contains both of the values from field \"tag1\" and the literal value \"tag2\"\n   * field(\"tags\").arrayContainsAll(array([field(\"tag1\"), \"tag2\"]));\n   * ```\n   *\n   * @param arrayExpression - The elements to check for in the array.\n   * @returns A new `Expression` representing the 'array_contains_all' comparison.\n   */\n  arrayContainsAll(arrayExpression: Expression): BooleanExpression;\n  arrayContainsAll(values: unknown[] | Expression): BooleanExpression {\n    const normalizedExpr = Array.isArray(values)\n      ? new ListOfExprs(values.map(valueToDefaultExpr), 'arrayContainsAll')\n      : values;\n    return new FunctionExpression(\n      'array_contains_all',\n      [this, normalizedExpr],\n      'arrayContainsAll'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if an array contains any of the specified elements.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'categories' array contains either values from field \"cate1\" or \"cate2\"\n   * field(\"categories\").arrayContainsAny([field(\"cate1\"), field(\"cate2\")]);\n   * ```\n   *\n   * @param values - The elements to check for in the array.\n   * @returns A new `Expression` representing the 'array_contains_any' comparison.\n   */\n  arrayContainsAny(values: Array<Expression | unknown>): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if an array contains any of the specified elements.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'groups' array contains either the value from the 'userGroup' field\n   * // or the value \"guest\"\n   * field(\"groups\").arrayContainsAny(array([field(\"userGroup\"), \"guest\"]));\n   * ```\n   *\n   * @param arrayExpression - The elements to check for in the array.\n   * @returns A new `Expression` representing the 'array_contains_any' comparison.\n   */\n  arrayContainsAny(arrayExpression: Expression): BooleanExpression;\n  arrayContainsAny(\n    values: Array<unknown | Expression> | Expression\n  ): BooleanExpression {\n    const normalizedExpr = Array.isArray(values)\n      ? new ListOfExprs(values.map(valueToDefaultExpr), 'arrayContainsAny')\n      : values;\n    return new FunctionExpression(\n      'array_contains_any',\n      [this, normalizedExpr],\n      'arrayContainsAny'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that reverses an array.\n   *\n   * @example\n   * ```typescript\n   * // Reverse the value of the 'myArray' field.\n   * field(\"myArray\").arrayReverse();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed array.\n   */\n  arrayReverse(): FunctionExpression {\n    return new FunctionExpression('array_reverse', [this]);\n  }\n\n  /**\n   * Creates an expression that calculates the length of an array.\n   *\n   * @example\n   * ```typescript\n   * // Get the number of items in the 'cart' array\n   * field(\"cart\").arrayLength();\n   * ```\n   *\n   * @returns A new `Expression` representing the length of the array.\n   */\n  arrayLength(): FunctionExpression {\n    return new FunctionExpression('array_length', [this], 'arrayLength');\n  }\n\n  /**\n   * Creates an expression that checks if this expression is equal to any of the provided values or\n   * expressions.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'category' field is either \"Electronics\" or value of field 'primaryType'\n   * field(\"category\").equalAny([\"Electronics\", field(\"primaryType\")]);\n   * ```\n   *\n   * @param values - The values or expressions to check against.\n   * @returns A new `Expression` representing the 'IN' comparison.\n   */\n  equalAny(values: Array<Expression | unknown>): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is equal to any of the provided values or\n   * expressions.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'category' field is either \"Electronics\" or value of field 'primaryType'\n   * field(\"category\").equalAny(array([\"Electronics\", field(\"primaryType\")]));\n   * ```\n   *\n   * @param arrayExpression - An expression that evaluates to an array of values to check against.\n   * @returns A new `Expression` representing the 'IN' comparison.\n   */\n  equalAny(arrayExpression: Expression): BooleanExpression;\n  equalAny(others: unknown[] | Expression): BooleanExpression {\n    const exprOthers = Array.isArray(others)\n      ? new ListOfExprs(others.map(valueToDefaultExpr), 'equalAny')\n      : others;\n    return new FunctionExpression(\n      'equal_any',\n      [this, exprOthers],\n      'equalAny'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if this expression is not equal to any of the provided values or\n   * expressions.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'status' field is neither \"pending\" nor the value of 'rejectedStatus'\n   * field(\"status\").notEqualAny([\"pending\", field(\"rejectedStatus\")]);\n   * ```\n   *\n   * @param values - The values or expressions to check against.\n   * @returns A new `Expression` representing the 'notEqualAny' comparison.\n   */\n  notEqualAny(values: Array<Expression | unknown>): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is not equal to any of the values in the evaluated expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses'\n   * field(\"status\").notEqualAny(field('rejectedStatuses'));\n   * ```\n   *\n   * @param arrayExpression - The values or expressions to check against.\n   * @returns A new `Expression` representing the 'notEqualAny' comparison.\n   */\n  notEqualAny(arrayExpression: Expression): BooleanExpression;\n  notEqualAny(others: unknown[] | Expression): BooleanExpression {\n    const exprOthers = Array.isArray(others)\n      ? new ListOfExprs(others.map(valueToDefaultExpr), 'notEqualAny')\n      : others;\n    return new FunctionExpression(\n      'not_equal_any',\n      [this, exprOthers],\n      'notEqualAny'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if a field exists in the document.\n   *\n   * @example\n   * ```typescript\n   * // Check if the document has a field named \"phoneNumber\"\n   * field(\"phoneNumber\").exists();\n   * ```\n   *\n   * @returns A new `Expression` representing the 'exists' check.\n   */\n  exists(): BooleanExpression {\n    return new FunctionExpression('exists', [this], 'exists').asBoolean();\n  }\n\n  /**\n   * Creates an expression that calculates the character length of a string in UTF-8.\n   *\n   * @example\n   * ```typescript\n   * // Get the character length of the 'name' field in its UTF-8 form.\n   * field(\"name\").charLength();\n   * ```\n   *\n   * @returns A new `Expression` representing the length of the string.\n   */\n  charLength(): FunctionExpression {\n    return new FunctionExpression('char_length', [this], 'charLength');\n  }\n\n  /**\n   * Creates an expression that performs a case-sensitive string comparison.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'title' field contains the word \"guide\" (case-sensitive)\n   * field(\"title\").like(\"%guide%\");\n   * ```\n   *\n   * @param pattern - The pattern to search for. You can use \"%\" as a wildcard character.\n   * @returns A new `Expression` representing the 'like' comparison.\n   */\n  like(pattern: string): BooleanExpression;\n\n  /**\n   * Creates an expression that performs a case-sensitive string comparison.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'title' field contains the word \"guide\" (case-sensitive)\n   * field(\"title\").like(\"%guide%\");\n   * ```\n   *\n   * @param pattern - The pattern to search for. You can use \"%\" as a wildcard character.\n   * @returns A new `Expression` representing the 'like' comparison.\n   */\n  like(pattern: Expression): BooleanExpression;\n  like(stringOrExpr: string | Expression): BooleanExpression {\n    return new FunctionExpression(\n      'like',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'like'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if a string contains a specified regular expression as a\n   * substring.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'description' field contains \"example\" (case-insensitive)\n   * field(\"description\").regexContains(\"(?i)example\");\n   * ```\n   *\n   * @param pattern - The regular expression to use for the search.\n   * @returns A new `Expression` representing the 'contains' comparison.\n   */\n  regexContains(pattern: string): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if a string contains a specified regular expression as a\n   * substring.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'description' field contains the regular expression stored in field 'regex'\n   * field(\"description\").regexContains(field(\"regex\"));\n   * ```\n   *\n   * @param pattern - The regular expression to use for the search.\n   * @returns A new `Expression` representing the 'contains' comparison.\n   */\n  regexContains(pattern: Expression): BooleanExpression;\n  regexContains(stringOrExpr: string | Expression): BooleanExpression {\n    return new FunctionExpression(\n      'regex_contains',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'regexContains'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that returns the first substring of a string expression that matches\n   * a specified regular expression.\n   *\n   * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n   *\n   * @example\n   * ```typescript\n   * // Extract the domain from an email address\n   * field(\"email\").regexFind(\"@.+\")\n   * ```\n   *\n   * @param pattern - The regular expression to search for.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function.\n   */\n  regexFind(pattern: string): FunctionExpression;\n\n  /**\n   * Creates an expression that returns the first substring of a string expression that matches\n   * a specified regular expression.\n   *\n   * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n   *\n   * @example\n   * ```typescript\n   * // Extract the domain from an email address\n   * field(\"email\").regexFind(field(\"domain\"))\n   * ```\n   *\n   * @param pattern - The regular expression to search for.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function.\n   */\n  regexFind(pattern: Expression): FunctionExpression;\n  regexFind(stringOrExpr: string | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'regex_find',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'regexFind'\n    );\n  }\n\n  /**\n   *\n   * Creates an expression that evaluates to a list of all substrings in this string expression that\n   * match a specified regular expression.\n   *\n   * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n   *\n   * @example\n   * ```typescript\n   * // Extract all hashtags from a post content field\n   * field(\"content\").regexFindAll(\"#[A-Za-z0-9_]+\")\n   * ```\n   *\n   * @param pattern - The regular expression to search for.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} that evaluates to an array of matched substrings.\n   */\n  regexFindAll(pattern: string): FunctionExpression;\n\n  /**\n   *\n   * Creates an expression that evaluates to a list of all substrings in this string expression that\n   * match a specified regular expression.\n   *\n   * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n   *\n   * @example\n   * ```typescript\n   * // Extract all names from a post content field\n   * field(\"content\").regexFindAll(field(\"names\"))\n   * ```\n   *\n   * @param pattern - The regular expression to search for.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} that evaluates to an array of matched substrings.\n   */\n  regexFindAll(pattern: Expression): FunctionExpression;\n  regexFindAll(stringOrExpr: string | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'regex_find_all',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'regexFindAll'\n    );\n  }\n\n  /**\n   * Creates an expression that checks if a string matches a specified regular expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'email' field matches a valid email pattern\n   * field(\"email\").regexMatch(\"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,}\");\n   * ```\n   *\n   * @param pattern - The regular expression to use for the match.\n   * @returns A new `Expression` representing the regular expression match.\n   */\n  regexMatch(pattern: string): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if a string matches a specified regular expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'email' field matches a regular expression stored in field 'regex'\n   * field(\"email\").regexMatch(field(\"regex\"));\n   * ```\n   *\n   * @param pattern - The regular expression to use for the match.\n   * @returns A new `Expression` representing the regular expression match.\n   */\n  regexMatch(pattern: Expression): BooleanExpression;\n  regexMatch(stringOrExpr: string | Expression): BooleanExpression {\n    return new FunctionExpression(\n      'regex_match',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'regexMatch'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if a string contains a specified substring.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'description' field contains \"example\".\n   * field(\"description\").stringContains(\"example\");\n   * ```\n   *\n   * @param substring - The substring to search for.\n   * @returns A new `Expression` representing the 'contains' comparison.\n   */\n  stringContains(substring: string): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if a string contains the string represented by another expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'description' field contains the value of the 'keyword' field.\n   * field(\"description\").stringContains(field(\"keyword\"));\n   * ```\n   *\n   * @param expr - The expression representing the substring to search for.\n   * @returns A new `Expression` representing the 'contains' comparison.\n   */\n  stringContains(expr: Expression): BooleanExpression;\n  stringContains(stringOrExpr: string | Expression): BooleanExpression {\n    return new FunctionExpression(\n      'string_contains',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'stringContains'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if a string starts with a given prefix.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'name' field starts with \"Mr.\"\n   * field(\"name\").startsWith(\"Mr.\");\n   * ```\n   *\n   * @param prefix - The prefix to check for.\n   * @returns A new `Expression` representing the 'starts with' comparison.\n   */\n  startsWith(prefix: string): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if a string starts with a given prefix (represented as an\n   * expression).\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'fullName' field starts with the value of the 'firstName' field\n   * field(\"fullName\").startsWith(field(\"firstName\"));\n   * ```\n   *\n   * @param prefix - The prefix expression to check for.\n   * @returns A new `Expression` representing the 'starts with' comparison.\n   */\n  startsWith(prefix: Expression): BooleanExpression;\n  startsWith(stringOrExpr: string | Expression): BooleanExpression {\n    return new FunctionExpression(\n      'starts_with',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'startsWith'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if a string ends with a given postfix.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'filename' field ends with \".txt\"\n   * field(\"filename\").endsWith(\".txt\");\n   * ```\n   *\n   * @param suffix - The postfix to check for.\n   * @returns A new `Expression` representing the 'ends with' comparison.\n   */\n  endsWith(suffix: string): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if a string ends with a given postfix (represented as an\n   * expression).\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'url' field ends with the value of the 'extension' field\n   * field(\"url\").endsWith(field(\"extension\"));\n   * ```\n   *\n   * @param suffix - The postfix expression to check for.\n   * @returns A new `Expression` representing the 'ends with' comparison.\n   */\n  endsWith(suffix: Expression): BooleanExpression;\n  endsWith(stringOrExpr: string | Expression): BooleanExpression {\n    return new FunctionExpression(\n      'ends_with',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'endsWith'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that converts a string to lowercase.\n   *\n   * @example\n   * ```typescript\n   * // Convert the 'name' field to lowercase\n   * field(\"name\").toLower();\n   * ```\n   *\n   * @returns A new `Expression` representing the lowercase string.\n   */\n  toLower(): FunctionExpression {\n    return new FunctionExpression('to_lower', [this], 'toLower');\n  }\n\n  /**\n   * Creates an expression that converts a string to uppercase.\n   *\n   * @example\n   * ```typescript\n   * // Convert the 'title' field to uppercase\n   * field(\"title\").toUpper();\n   * ```\n   *\n   * @returns A new `Expression` representing the uppercase string.\n   */\n  toUpper(): FunctionExpression {\n    return new FunctionExpression('to_upper', [this], 'toUpper');\n  }\n\n  /**\n   * Creates an expression that removes leading and trailing characters from a string or byte array.\n   *\n   * @example\n   * ```typescript\n   * // Trim whitespace from the 'userInput' field\n   * field(\"userInput\").trim();\n   *\n   * // Trim quotes from the 'userInput' field\n   * field(\"userInput\").trim('\"');\n   * ```\n   * @param valueToTrim - Optional This parameter is treated as a set of characters or bytes that will be\n   * trimmed from the input. If not specified, then whitespace will be trimmed.\n   * @returns A new `Expression` representing the trimmed string or byte array.\n   */\n  trim(valueToTrim?: string | Expression | Bytes): FunctionExpression {\n    const args: Expression[] = [this];\n    if (valueToTrim) {\n      args.push(valueToDefaultExpr(valueToTrim));\n    }\n    return new FunctionExpression('trim', args, 'trim');\n  }\n\n  /**\n   * Trims whitespace or a specified set of characters/bytes from the beginning of a string or byte array.\n   *\n   * @example\n   * ```typescript\n   * // Trim whitespace from the beginning of the 'userInput' field\n   * field(\"userInput\").ltrim();\n   *\n   * // Trim quotes from the beginning of the 'userInput' field\n   * field(\"userInput\").ltrim('\"');\n   * ```\n   *\n   * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim.\n   * If not specified, whitespace will be trimmed.\n   * @returns A new `Expression` representing the trimmed string.\n   */\n  ltrim(valueToTrim?: string | Expression | Bytes): FunctionExpression {\n    const args: Expression[] = [this];\n    if (valueToTrim) {\n      args.push(valueToDefaultExpr(valueToTrim));\n    }\n    return new FunctionExpression('ltrim', args, 'ltrim');\n  }\n\n  /**\n   * Trims whitespace or a specified set of characters/bytes from the end of a string or byte array.\n   *\n   * @example\n   * ```typescript\n   * // Trim whitespace from the end of the 'userInput' field\n   * field(\"userInput\").rtrim();\n   *\n   * // Trim quotes from the end of the 'userInput' field\n   * field(\"userInput\").rtrim('\"');\n   * ```\n   *\n   * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim.\n   * If not specified, whitespace will be trimmed.\n   * @returns A new `Expression` representing the trimmed string or byte array.\n   */\n  rtrim(valueToTrim?: string | Expression | Bytes): FunctionExpression {\n    const args: Expression[] = [this];\n    if (valueToTrim) {\n      args.push(valueToDefaultExpr(valueToTrim));\n    }\n    return new FunctionExpression('rtrim', args, 'rtrim');\n  }\n\n  /**\n   * Creates an expression that returns the data type of this expression's result, as a string.\n   *\n   * @remarks\n   * This is evaluated on the backend. This means:\n   * 1. Generic typed elements (like `array<string>`) evaluate strictly to the primitive `'array'`.\n   * 2. Any custom `FirestoreDataConverter` mappings are ignored.\n   * 3. For numeric values, the backend does not yield the JavaScript `\"number\"` type; it evaluates\n   *    precisely as `\"int64\"` or `\"float64\"`.\n   * 4. For date or timestamp objects, the backend evaluates to `\"timestamp\"`.\n   *\n   * @example\n   * ```typescript\n   * // Get the data type of the value in field 'title'\n   * field('title').type()\n   * ```\n   *\n   * @returns A new `Expression` representing the data type.\n   */\n  type(): FunctionExpression {\n    return new FunctionExpression('type', [this]);\n  }\n\n  /**\n   * Creates an expression that checks if the result of this expression is of the given type.\n   *\n   * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data.\n   * Supported values for `type` are:\n   * `'null'`, `'array'`, `'boolean'`, `'bytes'`, `'timestamp'`, `'geo_point'`, `'number'`,\n   * `'int32'`, `'int64'`, `'float64'`, `'decimal128'`, `'map'`, `'reference'`, `'string'`,\n   * `'vector'`, `'max_key'`, `'min_key'`, `'object_id'`, `'regex'`, `'request_timestamp'`.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'price' field is specifically an integer (not just 'number')\n   * field('price').isType('int64');\n   * ```\n   *\n   * @param type - The type to check for.\n   * @returns A new `BooleanExpression` that evaluates to true if the expression's result is of the given type, false otherwise.\n   */\n  isType(type: string): BooleanExpression {\n    return new FunctionExpression(\n      'is_type',\n      [this, constant(type)],\n      'isType'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that concatenates string expressions together.\n   *\n   * @example\n   * ```typescript\n   * // Combine the 'firstName', \" \", and 'lastName' fields into a single string\n   * field(\"firstName\").stringConcat(constant(\" \"), field(\"lastName\"));\n   * ```\n   *\n   * @param secondString - The additional expression or string literal to concatenate.\n   * @param otherStrings - Optional additional expressions or string literals to concatenate.\n   * @returns A new `Expression` representing the concatenated string.\n   */\n  stringConcat(\n    secondString: Expression | string,\n    ...otherStrings: Array<Expression | string>\n  ): FunctionExpression {\n    const elements = [secondString, ...otherStrings];\n    const exprs = elements.map(valueToDefaultExpr);\n    return new FunctionExpression(\n      'string_concat',\n      [this, ...exprs],\n      'stringConcat'\n    );\n  }\n\n  /**\n   * Creates an expression that finds the index of the first occurrence of a substring or byte sequence.\n   *\n   * @example\n   * ```typescript\n   * // Find the index of \"foo\" in the 'text' field\n   * field(\"text\").stringIndexOf(\"foo\");\n   * ```\n   *\n   * @param search - The substring or byte sequence to search for.\n   * @returns A new `Expression` representing the index of the first occurrence.\n   */\n  stringIndexOf(search: string | Expression | Bytes): FunctionExpression {\n    return new FunctionExpression(\n      'string_index_of',\n      [this, valueToDefaultExpr(search)],\n      'stringIndexOf'\n    );\n  }\n\n  /**\n   * Creates an expression that repeats a string or byte array a specified number of times.\n   *\n   * @example\n   * ```typescript\n   * // Repeat the 'label' field 3 times\n   * field(\"label\").stringRepeat(3);\n   * ```\n   *\n   * @param repetitions - The number of times to repeat the string or byte array.\n   * @returns A new `Expression` representing the repeated string or byte array.\n   */\n  stringRepeat(repetitions: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'string_repeat',\n      [this, valueToDefaultExpr(repetitions)],\n      'stringRepeat'\n    );\n  }\n\n  /**\n   * Creates an expression that replaces all occurrences of a substring or byte sequence with a replacement.\n   *\n   * @example\n   * ```typescript\n   * // Replace all occurrences of \"foo\" with \"bar\" in the 'text' field\n   * field(\"text\").stringReplaceAll(\"foo\", \"bar\");\n   * ```\n   *\n   * @param find - The substring or byte sequence to search for.\n   * @param replacement - The replacement string or byte sequence.\n   * @returns A new `Expression` representing the string or byte array with replacements.\n   */\n  stringReplaceAll(\n    find: string | Expression | Bytes,\n    replacement: string | Expression | Bytes\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'string_replace_all',\n      [this, valueToDefaultExpr(find), valueToDefaultExpr(replacement)],\n      'stringReplaceAll'\n    );\n  }\n\n  /**\n   * Creates an expression that replaces the first occurrence of a substring or byte sequence with a replacement.\n   *\n   * @example\n   * ```typescript\n   * // Replace the first occurrence of \"foo\" with \"bar\" in the 'text' field\n   * field(\"text\").stringReplaceOne(\"foo\", \"bar\");\n   * ```\n   *\n   * @param find - The substring or byte sequence to search for.\n   * @param replacement - The replacement string or byte sequence.\n   * @returns A new `Expression` representing the string or byte array with the replacement.\n   */\n  stringReplaceOne(\n    find: string | Expression | Bytes,\n    replacement: string | Expression | Bytes\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'string_replace_one',\n      [this, valueToDefaultExpr(find), valueToDefaultExpr(replacement)],\n      'stringReplaceOne'\n    );\n  }\n\n  /**\n   * Creates an expression that concatenates expression results together.\n   *\n   * @example\n   * ```typescript\n   * // Combine the 'firstName', ' ', and 'lastName' fields into a single value.\n   * field(\"firstName\").concat(constant(\" \"), field(\"lastName\"));\n   * ```\n   *\n   * @param second - The additional expression or literal to concatenate.\n   * @param others - Optional additional expressions or literals to concatenate.\n   * @returns A new `Expression` representing the concatenated value.\n   */\n  concat(\n    second: Expression | unknown,\n    ...others: Array<Expression | unknown>\n  ): FunctionExpression {\n    const elements = [second, ...others];\n    const exprs = elements.map(valueToDefaultExpr);\n    return new FunctionExpression('concat', [this, ...exprs], 'concat');\n  }\n\n  /**\n   * Creates an expression that reverses this string expression.\n   *\n   * @example\n   * ```typescript\n   * // Reverse the value of the 'myString' field.\n   * field(\"myString\").reverse();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.\n   */\n  reverse(): FunctionExpression {\n    return new FunctionExpression('reverse', [this], 'reverse');\n  }\n\n  /**\n   * Filters the array using a provided alias and predicate expression.\n   *\n   * @example\n   * ```typescript\n   * // Filter the 'items' array to only include those where the 'price' is greater than 10\n   * field(\"items\").arrayFilter('item', greaterThan(variable('item.price'), 10));\n   * ```\n   *\n   * @param alias - The variable name to use for each element.\n   * @param filter - The predicate boolean expression to filter by.\n   * @returns A new `Expression` representing the filtered array.\n   */\n  arrayFilter(alias: string, filter: BooleanExpression): FunctionExpression {\n    return new FunctionExpression(\n      'array_filter',\n      [this, valueToDefaultExpr(alias), filter],\n      'arrayFilter'\n    );\n  }\n\n  /**\n   * Creates an expression that applies a provided transformation to each element in an array.\n   *\n   * @example\n   * ```typescript\n   * // Transform the 'scores' array by multiplying each score by 10\n   * field(\"scores\").arrayTransform(\"score\", multiply(variable(\"score\"), 10));\n   * ```\n   *\n   * @param elementAlias - The variable name to use for each element.\n   * @param transform - The lambda expression used to transform the elements.\n   * @returns A new `Expression` representing the arrayTransform operation.\n   */\n  arrayTransform(\n    elementAlias: string,\n    transform: Expression\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'array_transform',\n      [this, valueToDefaultExpr(elementAlias), transform],\n      'arrayTransform'\n    );\n  }\n\n  /**\n   * Creates an expression that applies a provided transformation to each element in an array, providing the element's index to the transformation expression.\n   *\n   * @example\n   * ```typescript\n   * // Transform the 'scores' array by adding the index to each score\n   * field(\"scores\").arrayTransformWithIndex(\"score\", \"i\", add(variable(\"score\"), variable(\"i\")));\n   * ```\n   *\n   * @param elementAlias - The variable name to use for each element.\n   * @param indexAlias - The variable name to use for the current index.\n   * @param transform - The lambda expression used to transform the elements.\n   * @returns A new `Expression` representing the arrayTransformWithIndex operation.\n   */\n  arrayTransformWithIndex(\n    elementAlias: string,\n    indexAlias: string,\n    transform: Expression\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'array_transform',\n      [\n        this,\n        valueToDefaultExpr(elementAlias),\n        valueToDefaultExpr(indexAlias),\n        transform\n      ],\n      'arrayTransformWithIndex'\n    );\n  }\n\n  /**\n   * Returns a subset of the array.\n   *\n   * @example\n   * ```typescript\n   * // Get 5 elements from the 'items' array starting from index 2\n   * field(\"items\").arraySlice(2, 5);\n   *\n   * // Get n number of elements from the 'items' array starting from index 2\n   * field(\"items\").arraySlice(2, field(\"count\"));\n   * ```\n   *\n   * @param offset - The starting offset.\n   * @param length - The optional length of the slice.\n   * @returns A new `Expression` representing the sliced array.\n   */\n  arraySlice(\n    offset: number | Expression,\n    length?: number | Expression\n  ): FunctionExpression {\n    const args: Expression[] = [this, valueToDefaultExpr(offset)];\n    if (length !== undefined) {\n      args.push(valueToDefaultExpr(length));\n    }\n    return new FunctionExpression('array_slice', args, 'arraySlice');\n  }\n\n  /**\n   * Returns the first element of the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the first element of the 'myArray' field.\n   * field(\"myArray\").arrayFirst();\n   * ```\n   *\n   * @returns A new `Expression` representing the first element.\n   */\n  arrayFirst(): FunctionExpression {\n    return new FunctionExpression('array_first', [this], 'arrayFirst');\n  }\n\n  /**\n   * Returns the first `n` elements of the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the first 3 elements of the 'myArray' field.\n   * field(\"myArray\").arrayFirstN(3);\n   * ```\n   *\n   * @param n - The number of elements to return.\n   * @returns A new `Expression` representing the first `n` elements.\n   */\n  arrayFirstN(n: number): FunctionExpression;\n\n  /**\n   * Returns the first `n` elements of the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the first n elements of the 'myArray' field.\n   * field(\"myArray\").arrayFirstN(field(\"count\"));\n   * ```\n   *\n   * @param n - An expression evaluating to the number of elements to return.\n   * @returns A new `Expression` representing the first `n` elements.\n   */\n  arrayFirstN(n: Expression): FunctionExpression;\n  arrayFirstN(n: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'array_first_n',\n      [this, valueToDefaultExpr(n)],\n      'arrayFirstN'\n    );\n  }\n\n  /**\n   * Returns the last element of the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the last element of the 'myArray' field.\n   * field(\"myArray\").arrayLast();\n   * ```\n   *\n   * @returns A new `Expression` representing the last element.\n   */\n  arrayLast(): FunctionExpression {\n    return new FunctionExpression('array_last', [this], 'arrayLast');\n  }\n\n  /**\n   * Returns the last `n` elements of the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the last 3 elements of the 'myArray' field.\n   * field(\"myArray\").arrayLastN(3);\n   * ```\n   *\n   * @param n - The number of elements to return.\n   * @returns A new `Expression` representing the last `n` elements.\n   */\n  arrayLastN(n: number): FunctionExpression;\n\n  /**\n   * Returns the last `n` elements of the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the last n elements of the 'myArray' field.\n   * field(\"myArray\").arrayLastN(field(\"count\"));\n   * ```\n   *\n   * @param n - An expression evaluating to the number of elements to return.\n   * @returns A new `Expression` representing the last `n` elements.\n   */\n  arrayLastN(n: Expression): FunctionExpression;\n  arrayLastN(n: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'array_last_n',\n      [this, valueToDefaultExpr(n)],\n      'arrayLastN'\n    );\n  }\n\n  /**\n   * Returns the maximum value in the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the maximum value of the 'myArray' field.\n   * field(\"myArray\").arrayMaximum();\n   * ```\n   *\n   * @returns A new `Expression` representing the maximum value.\n   */\n  arrayMaximum(): FunctionExpression {\n    return new FunctionExpression('maximum', [this], 'arrayMaximum');\n  }\n\n  /**\n   * Returns the largest `n` elements of the array.\n   *\n   * Note: Returns the n largest non-null elements in the array, in descending\n   * order. This does not use a stable sort, meaning the order of equivalent\n   * elements is undefined.\n   *\n   * @example\n   * ```typescript\n   * // Get the largest 3 elements of the 'myArray' field.\n   * field(\"myArray\").arrayMaximumN(3);\n   * ```\n   *\n   * @param n - The number of elements to return.\n   * @returns A new `Expression` representing the largest `n` elements.\n   */\n  arrayMaximumN(n: number): FunctionExpression;\n\n  /**\n   * Returns the largest `n` elements of the array.\n   *\n   * Note: Returns the n largest non-null elements in the array, in descending\n   * order. This does not use a stable sort, meaning the order of equivalent\n   * elements is undefined.\n   *\n   * @example\n   * ```typescript\n   * // Get the largest n elements of the 'myArray' field.\n   * field(\"myArray\").arrayMaximumN(field(\"count\"));\n   * ```\n   *\n   * @param n - An expression evaluating to the number of elements to return.\n   * @returns A new `Expression` representing the largest `n` elements.\n   */\n  arrayMaximumN(n: Expression): FunctionExpression;\n  arrayMaximumN(n: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'maximum_n',\n      [this, valueToDefaultExpr(n)],\n      'arrayMaximumN'\n    );\n  }\n\n  /**\n   * Returns the minimum value in the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the minimum value of the 'myArray' field.\n   * field(\"myArray\").arrayMinimum();\n   * ```\n   *\n   * @returns A new `Expression` representing the minimum value.\n   */\n  arrayMinimum(): FunctionExpression {\n    return new FunctionExpression('minimum', [this], 'arrayMinimum');\n  }\n\n  /**\n   * Returns the smallest `n` elements of the array.\n   *\n   * Note: Returns the n smallest non-null elements in the array, in ascending\n   * order. This does not use a stable sort, meaning the order of equivalent\n   * elements is undefined.\n   *\n   * @example\n   * ```typescript\n   * // Get the smallest 3 elements of the 'myArray' field.\n   * field(\"myArray\").arrayMinimumN(3);\n   * ```\n   *\n   * @param n - The number of elements to return.\n   * @returns A new `Expression` representing the smallest `n` elements.\n   */\n  arrayMinimumN(n: number): FunctionExpression;\n\n  /**\n   * Returns the smallest `n` elements of the array.\n   *\n   * Note: Returns the n smallest non-null elements in the array, in ascending\n   * order. This does not use a stable sort, meaning the order of equivalent\n   * elements is undefined.\n   *\n   * @example\n   * ```typescript\n   * // Get the smallest n elements of the 'myArray' field.\n   * field(\"myArray\").arrayMinimumN(field(\"count\"));\n   * ```\n   *\n   * @param n - An expression evaluating to the number of elements to return.\n   * @returns A new `Expression` representing the smallest `n` elements.\n   */\n  arrayMinimumN(n: Expression): FunctionExpression;\n  arrayMinimumN(n: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'minimum_n',\n      [this, valueToDefaultExpr(n)],\n      'arrayMinimumN'\n    );\n  }\n\n  /**\n   * Returns the first index of the search value in the array, or -1 if not found.\n   *\n   * @example\n   * ```typescript\n   * // Get the first index of the value 3 in the 'myArray' field.\n   * field(\"myArray\").arrayIndexOf(3);\n   * ```\n   *\n   * @param search - The value to search for.\n   * @returns A new `Expression` representing the index.\n   */\n  arrayIndexOf(search: unknown): FunctionExpression;\n\n  /**\n   * Returns the first index of the search value in the array, or -1 if not found.\n   *\n   * @example\n   * ```typescript\n   * // Get the first index of the value in 'searchVal' field in the 'myArray' field.\n   * field(\"myArray\").arrayIndexOf(field(\"searchVal\"));\n   * ```\n   *\n   * @param search - An expression evaluating to the value to search for.\n   * @returns A new `Expression` representing the index.\n   */\n  arrayIndexOf(search: Expression): FunctionExpression;\n  arrayIndexOf(search: unknown | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'array_index_of',\n      [this, valueToDefaultExpr(search), valueToDefaultExpr('first')],\n      'arrayIndexOf'\n    );\n  }\n\n  /**\n   * Returns the last index of the search value in the array, or -1 if not found.\n   *\n   * @example\n   * ```typescript\n   * // Get the last index of the value 3 in the 'myArray' field.\n   * field(\"myArray\").arrayLastIndexOf(3);\n   * ```\n   *\n   * @param search - The value to search for.\n   * @returns A new `Expression` representing the index.\n   */\n  arrayLastIndexOf(search: unknown): FunctionExpression;\n\n  /**\n   * Returns the last index of the search value in the array, or -1 if not found.\n   *\n   * @example\n   * ```typescript\n   * // Get the last index of the value in 'searchVal' field in the 'myArray' field.\n   * field(\"myArray\").arrayLastIndexOf(field(\"searchVal\"));\n   * ```\n   *\n   * @param search - An expression evaluating to the value to search for.\n   * @returns A new `Expression` representing the index.\n   */\n  arrayLastIndexOf(search: Expression): FunctionExpression;\n  arrayLastIndexOf(search: unknown | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'array_index_of',\n      [this, valueToDefaultExpr(search), valueToDefaultExpr('last')],\n      'arrayLastIndexOf'\n    );\n  }\n\n  /**\n   * Returns all indices of the search value in the array.\n   *\n   * @example\n   * ```typescript\n   * // Get all indices of the value 3 in the 'myArray' field.\n   * field(\"myArray\").arrayIndexOfAll(3);\n   * ```\n   *\n   * @param search - The value to search for.\n   * @returns A new `Expression` representing the indices.\n   */\n  arrayIndexOfAll(search: unknown): FunctionExpression;\n\n  /**\n   * Returns all indices of the search value in the array.\n   *\n   * @example\n   * ```typescript\n   * // Get all indices of the value in 'searchVal' field in the 'myArray' field.\n   * field(\"myArray\").arrayIndexOfAll(field(\"searchVal\"));\n   * ```\n   *\n   * @param search - An expression evaluating to the value to search for.\n   * @returns A new `Expression` representing the indices.\n   */\n  arrayIndexOfAll(search: Expression): FunctionExpression;\n  arrayIndexOfAll(search: unknown | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'array_index_of_all',\n      [this, valueToDefaultExpr(search)],\n      'arrayIndexOfAll'\n    );\n  }\n\n  /**\n   * Creates an expression that calculates the length of this string expression in bytes.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the length of the 'myString' field in bytes.\n   * field(\"myString\").byteLength();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string in bytes.\n   */\n  byteLength(): FunctionExpression {\n    return new FunctionExpression('byte_length', [this], 'byteLength');\n  }\n\n  /**\n   * Creates an expression that computes the ceiling of a numeric value.\n   *\n   * @example\n   * ```typescript\n   * // Compute the ceiling of the 'price' field.\n   * field(\"price\").ceil();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ceiling of the numeric value.\n   */\n  ceil(): FunctionExpression {\n    return new FunctionExpression('ceil', [this]);\n  }\n\n  /**\n   * Creates an expression that computes the floor of a numeric value.\n   *\n   * @example\n   * ```typescript\n   * // Compute the floor of the 'price' field.\n   * field(\"price\").floor();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the floor of the numeric value.\n   */\n  floor(): FunctionExpression {\n    return new FunctionExpression('floor', [this]);\n  }\n\n  /**\n   * Creates an expression that computes the absolute value of a numeric value.\n   *\n   * @example\n   * ```typescript\n   * // Compute the absolute value of the 'price' field.\n   * field(\"price\").abs();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the absolute value of the numeric value.\n   */\n  abs(): FunctionExpression {\n    return new FunctionExpression('abs', [this]);\n  }\n\n  /**\n   * Creates an expression that computes e to the power of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Compute e to the power of the 'value' field.\n   * field(\"value\").exp();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the exp of the numeric value.\n   */\n  exp(): FunctionExpression {\n    return new FunctionExpression('exp', [this]);\n  }\n\n  /**\n   * Accesses a value from a map (object) field using the provided key.\n   *\n   * @example\n   * ```typescript\n   * // Get the 'city' value from the 'address' map field\n   * field(\"address\").mapGet(\"city\");\n   * ```\n   *\n   * @param subfield - The key to access in the map.\n   * @returns A new `Expression` representing the value associated with the given key in the map.\n   */\n  mapGet(subfield: string): FunctionExpression {\n    return new FunctionExpression(\n      'map_get',\n      [this, constant(subfield)],\n      'mapGet'\n    );\n  }\n\n  /**\n   * Creates an expression that returns a new map with the specified entries added or updated.\n   *\n   * @remarks\n   * Note that `mapSet` only performs shallow updates to the map. Setting a value to `null`\n   * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`.\n   *\n   * @example\n   * ```typescript\n   * // Set the 'city' to \"San Francisco\" in the 'address' map\n   * field(\"address\").mapSet(\"city\", \"San Francisco\");\n   * ```\n   *\n   * @param key - The key to set. Must be a string or a constant string expression.\n   * @param value - The value to set.\n   * @param moreKeyValues - Additional key-value pairs to set.\n   * @returns A new `Expression` representing the map with the entries set.\n   */\n  mapSet(\n    key: string | Expression,\n    value: unknown,\n    ...moreKeyValues: unknown[]\n  ): FunctionExpression {\n    const args = [\n      this,\n      valueToDefaultExpr(key),\n      valueToDefaultExpr(value),\n      ...moreKeyValues.map(valueToDefaultExpr)\n    ];\n    return new FunctionExpression('map_set', args, 'mapSet');\n  }\n\n  /**\n   * Creates an expression that returns the keys of a map.\n   *\n   * @remarks\n   * While the backend generally preserves insertion order, relying on the\n   * order of the output array is not guaranteed and should be avoided.\n   *\n   * @example\n   * ```typescript\n   * // Get the keys of the 'address' map\n   * field(\"address\").mapKeys();\n   * ```\n   *\n   * @returns A new `Expression` representing the keys of the map.\n   */\n  mapKeys(): FunctionExpression {\n    return new FunctionExpression('map_keys', [this], 'mapKeys');\n  }\n\n  /**\n   * Creates an expression that returns the values of a map.\n   *\n   * @remarks\n   * While the backend generally preserves insertion order, relying on the\n   * order of the output array is not guaranteed and should be avoided.\n   *\n   * @example\n   * ```typescript\n   * // Get the values of the 'address' map\n   * field(\"address\").mapValues();\n   * ```\n   *\n   * @returns A new `Expression` representing the values of the map.\n   */\n  mapValues(): FunctionExpression {\n    return new FunctionExpression('map_values', [this], 'mapValues');\n  }\n\n  /**\n   * Creates an expression that returns the entries of a map as an array of maps,\n   * where each map contains a `\"k\"` property for the key and a `\"v\"` property for the value.\n   * For example: `[{ k: \"key1\", v: \"value1\" }, ...]`.\n   *\n   * @example\n   * ```typescript\n   * // Get the entries of the 'address' map\n   * field(\"address\").mapEntries();\n   * ```\n   *\n   * @returns A new `Expression` representing the entries of the map.\n   */\n  mapEntries(): FunctionExpression {\n    return new FunctionExpression('map_entries', [this], 'mapEntries');\n  }\n\n  /**\n   * @public\n   * Creates an expression that returns the value of a field from the document that results from the evaluation of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Get the value of the \"city\" field in the \"address\" document.\n   * field(\"address\").getField(\"city\")\n   * ```\n   *\n   * @param key The field to access in the document.\n   * @returns A new `Expression` representing the value of the field in the document.\n   */\n  getField(key: string | Expression): Expression {\n    return new FunctionExpression(\n      'get_field',\n      [this, valueToDefaultExpr(key)],\n      'get_field'\n    );\n  }\n\n  /**\n   * Creates an aggregation that counts the number of stage inputs with valid evaluations of the\n   * expression or field.\n   *\n   * @example\n   * ```typescript\n   * // Count the total number of products\n   * field(\"productId\").count().as(\"totalProducts\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'count' aggregation.\n   */\n  count(): AggregateFunction {\n    return AggregateFunction._create('count', [this], 'count');\n  }\n\n  /**\n   * Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the total revenue from a set of orders\n   * field(\"orderAmount\").sum().as(\"totalRevenue\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'sum' aggregation.\n   */\n  sum(): AggregateFunction {\n    return AggregateFunction._create('sum', [this], 'sum');\n  }\n\n  /**\n   * Creates an aggregation that calculates the average (mean) of a numeric field across multiple\n   * stage inputs.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the average age of users\n   * field(\"age\").average().as(\"averageAge\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'average' aggregation.\n   */\n  average(): AggregateFunction {\n    return AggregateFunction._create('average', [this], 'average');\n  }\n\n  /**\n   * Creates an aggregation that finds the minimum value of a field across multiple stage inputs.\n   *\n   * @example\n   * ```typescript\n   * // Find the lowest price of all products\n   * field(\"price\").minimum().as(\"lowestPrice\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'minimum' aggregation.\n   */\n  minimum(): AggregateFunction {\n    return AggregateFunction._create('minimum', [this], 'minimum');\n  }\n\n  /**\n   * Creates an aggregation that finds the maximum value of a field across multiple stage inputs.\n   *\n   * @example\n   * ```typescript\n   * // Find the highest score in a leaderboard\n   * field(\"score\").maximum().as(\"highestScore\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'maximum' aggregation.\n   */\n  maximum(): AggregateFunction {\n    return AggregateFunction._create('maximum', [this], 'maximum');\n  }\n\n  /**\n   * Creates an aggregation that finds the first value of an expression across multiple stage inputs.\n   *\n   * @example\n   * ```typescript\n   * // Find the first value of the 'rating' field\n   * field(\"rating\").first().as(\"firstRating\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'first' aggregation.\n   */\n  first(): AggregateFunction {\n    return AggregateFunction._create('first', [this], 'first');\n  }\n\n  /**\n   * Creates an aggregation that finds the last value of an expression across multiple stage inputs.\n   *\n   * @example\n   * ```typescript\n   * // Find the last value of the 'rating' field\n   * field(\"rating\").last().as(\"lastRating\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'last' aggregation.\n   */\n  last(): AggregateFunction {\n    return AggregateFunction._create('last', [this], 'last');\n  }\n\n  /**\n   * Creates an aggregation that collects all values of an expression across multiple stage inputs\n   * into an array.\n   *\n   * @remarks\n   * If the expression resolves to an absent value, it is converted to `null`.\n   * The order of elements in the output array is not stable and shouldn't be relied upon.\n   *\n   * @example\n   * ```typescript\n   * // Collect all tags from books into an array\n   * field(\"tags\").arrayAgg().as(\"allTags\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'array_agg' aggregation.\n   */\n  arrayAgg(): AggregateFunction {\n    return AggregateFunction._create('array_agg', [this], 'arrayAgg');\n  }\n\n  /**\n   * Creates an aggregation that collects all distinct values of an expression across multiple stage\n   * inputs into an array.\n   *\n   * @remarks\n   * If the expression resolves to an absent value, it is converted to `null`.\n   * The order of elements in the output array is not stable and shouldn't be relied upon.\n   *\n   * @example\n   * ```typescript\n   * // Collect all distinct tags from books into an array\n   * field(\"tags\").arrayAggDistinct().as(\"allDistinctTags\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'array_agg_distinct' aggregation.\n   */\n  arrayAggDistinct(): AggregateFunction {\n    return AggregateFunction._create(\n      'array_agg_distinct',\n      [this],\n      'arrayAggDistinct'\n    );\n  }\n\n  /**\n   * Creates an aggregation that counts the number of distinct values of the expression or field.\n   *\n   * @example\n   * ```typescript\n   * // Count the distinct number of products\n   * field(\"productId\").countDistinct().as(\"distinctProducts\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'count_distinct' aggregation.\n   */\n  countDistinct(): AggregateFunction {\n    return AggregateFunction._create('count_distinct', [this], 'countDistinct');\n  }\n\n  /**\n   * Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering.\n   *\n   * @example\n   * ```typescript\n   * // Returns the larger value between the 'timestamp' field and the current timestamp.\n   * field(\"timestamp\").logicalMaximum(currentTimestamp());\n   * ```\n   *\n   * @param second - The second expression or literal to compare with.\n   * @param others - Optional additional expressions or literals to compare with.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical maximum operation.\n   */\n  logicalMaximum(\n    second: Expression | unknown,\n    ...others: Array<Expression | unknown>\n  ): FunctionExpression {\n    const values = [second, ...others];\n    return new FunctionExpression(\n      'maximum',\n      [this, ...values.map(valueToDefaultExpr)],\n      'logicalMaximum'\n    );\n  }\n\n  /**\n   * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering.\n   *\n   * @example\n   * ```typescript\n   * // Returns the smaller value between the 'timestamp' field and the current timestamp.\n   * field(\"timestamp\").logicalMinimum(currentTimestamp());\n   * ```\n   *\n   * @param second - The second expression or literal to compare with.\n   * @param others - Optional additional expressions or literals to compare with.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical minimum operation.\n   */\n  logicalMinimum(\n    second: Expression | unknown,\n    ...others: Array<Expression | unknown>\n  ): FunctionExpression {\n    const values = [second, ...others];\n    return new FunctionExpression(\n      'minimum',\n      [this, ...values.map(valueToDefaultExpr)],\n      'minimum'\n    );\n  }\n\n  /**\n   * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression.\n   *\n   * @example\n   * ```typescript\n   * // Get the vector length (dimension) of the field 'embedding'.\n   * field(\"embedding\").vectorLength();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the vector.\n   */\n  vectorLength(): FunctionExpression {\n    return new FunctionExpression('vector_length', [this], 'vectorLength');\n  }\n\n  /**\n   * Calculates the cosine distance between two vectors.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field\n   * field(\"userVector\").cosineDistance(field(\"itemVector\"));\n   * ```\n   *\n   * @param vectorExpression - The other vector (represented as an Expression) to compare against.\n   * @returns A new `Expression` representing the cosine distance between the two vectors.\n   */\n  cosineDistance(vectorExpression: Expression): FunctionExpression;\n  /**\n   * Calculates the Cosine distance between two vectors.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the Cosine distance between the 'location' field and a target location\n   * field(\"location\").cosineDistance(new VectorValue([37.7749, -122.4194]));\n   * ```\n   *\n   * @param vector - The other vector (as a VectorValue) to compare against.\n   * @returns A new `Expression` representing the Cosine* distance between the two vectors.\n   */\n  cosineDistance(vector: VectorValue | number[]): FunctionExpression;\n  cosineDistance(\n    other: Expression | VectorValue | number[]\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'cosine_distance',\n      [this, vectorToExpr(other)],\n      'cosineDistance'\n    );\n  }\n\n  /**\n   * Calculates the dot product between two vectors.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the dot product between a feature vector and a target vector\n   * field(\"features\").dotProduct([0.5, 0.8, 0.2]);\n   * ```\n   *\n   * @param vectorExpression - The other vector (as an array of numbers) to calculate with.\n   * @returns A new `Expression` representing the dot product between the two vectors.\n   */\n  dotProduct(vectorExpression: Expression): FunctionExpression;\n\n  /**\n   * Calculates the dot product between two vectors.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the dot product between a feature vector and a target vector\n   * field(\"features\").dotProduct(new VectorValue([0.5, 0.8, 0.2]));\n   * ```\n   *\n   * @param vector - The other vector (as an array of numbers) to calculate with.\n   * @returns A new `Expression` representing the dot product between the two vectors.\n   */\n  dotProduct(vector: VectorValue | number[]): FunctionExpression;\n  dotProduct(other: Expression | VectorValue | number[]): FunctionExpression {\n    return new FunctionExpression(\n      'dot_product',\n      [this, vectorToExpr(other)],\n      'dotProduct'\n    );\n  }\n\n  /**\n   * Calculates the Euclidean distance between two vectors.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the Euclidean distance between the 'location' field and a target location\n   * field(\"location\").euclideanDistance([37.7749, -122.4194]);\n   * ```\n   *\n   * @param vectorExpression - The other vector (as an array of numbers) to calculate with.\n   * @returns A new `Expression` representing the Euclidean distance between the two vectors.\n   */\n  euclideanDistance(vectorExpression: Expression): FunctionExpression;\n\n  /**\n   * Calculates the Euclidean distance between two vectors.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the Euclidean distance between the 'location' field and a target location\n   * field(\"location\").euclideanDistance(new VectorValue([37.7749, -122.4194]));\n   * ```\n   *\n   * @param vector - The other vector (as a VectorValue) to compare against.\n   * @returns A new `Expression` representing the Euclidean distance between the two vectors.\n   */\n  euclideanDistance(vector: VectorValue | number[]): FunctionExpression;\n  euclideanDistance(\n    other: Expression | VectorValue | number[]\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'euclidean_distance',\n      [this, vectorToExpr(other)],\n      'euclideanDistance'\n    );\n  }\n\n  /**\n   * Creates an expression that interprets this expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n   * and returns a timestamp.\n   *\n   * @example\n   * ```typescript\n   * // Interpret the 'microseconds' field as microseconds since epoch.\n   * field(\"microseconds\").unixMicrosToTimestamp();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n   */\n  unixMicrosToTimestamp(): FunctionExpression {\n    return new FunctionExpression(\n      'unix_micros_to_timestamp',\n      [this],\n      'unixMicrosToTimestamp'\n    );\n  }\n\n  /**\n   * Creates an expression that converts this timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n   *\n   * @example\n   * ```typescript\n   * // Convert the 'timestamp' field to microseconds since epoch.\n   * field(\"timestamp\").timestampToUnixMicros();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of microseconds since epoch.\n   */\n  timestampToUnixMicros(): FunctionExpression {\n    return new FunctionExpression(\n      'timestamp_to_unix_micros',\n      [this],\n      'timestampToUnixMicros'\n    );\n  }\n\n  /**\n   * Creates an expression that interprets this expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n   * and returns a timestamp.\n   *\n   * @example\n   * ```typescript\n   * // Interpret the 'milliseconds' field as milliseconds since epoch.\n   * field(\"milliseconds\").unixMillisToTimestamp();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n   */\n  unixMillisToTimestamp(): FunctionExpression {\n    return new FunctionExpression(\n      'unix_millis_to_timestamp',\n      [this],\n      'unixMillisToTimestamp'\n    );\n  }\n\n  /**\n   * Creates an expression that converts this timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n   *\n   * @example\n   * ```typescript\n   * // Convert the 'timestamp' field to milliseconds since epoch.\n   * field(\"timestamp\").timestampToUnixMillis();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of milliseconds since epoch.\n   */\n  timestampToUnixMillis(): FunctionExpression {\n    return new FunctionExpression(\n      'timestamp_to_unix_millis',\n      [this],\n      'timestampToUnixMillis'\n    );\n  }\n\n  /**\n   * Creates an expression that interprets this expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n   * and returns a timestamp.\n   *\n   * @example\n   * ```typescript\n   * // Interpret the 'seconds' field as seconds since epoch.\n   * field(\"seconds\").unixSecondsToTimestamp();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n   */\n  unixSecondsToTimestamp(): FunctionExpression {\n    return new FunctionExpression(\n      'unix_seconds_to_timestamp',\n      [this],\n      'unixSecondsToTimestamp'\n    );\n  }\n\n  /**\n   * Creates an expression that converts this timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n   *\n   * @example\n   * ```typescript\n   * // Convert the 'timestamp' field to seconds since epoch.\n   * field(\"timestamp\").timestampToUnixSeconds();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of seconds since epoch.\n   */\n  timestampToUnixSeconds(): FunctionExpression {\n    return new FunctionExpression(\n      'timestamp_to_unix_seconds',\n      [this],\n      'timestampToUnixSeconds'\n    );\n  }\n\n  /**\n   * Creates an expression that adds a specified amount of time to this timestamp expression.\n   *\n   * @example\n   * ```typescript\n   * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field.\n   * field(\"timestamp\").timestampAdd(field(\"unit\"), field(\"amount\"));\n   * ```\n   *\n   * @param unit - The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'.\n   * @param amount - The expression evaluates to amount of the unit.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n   */\n  timestampAdd(unit: Expression, amount: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that adds a specified amount of time to this timestamp expression.\n   *\n   * @example\n   * ```typescript\n   * // Add 1 day to the 'timestamp' field.\n   * field(\"timestamp\").timestampAdd(\"day\", 1);\n   * ```\n   *\n   * @param unit - The unit of time to add (e.g., \"day\", \"hour\").\n   * @param amount - The amount of time to add.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n   */\n  timestampAdd(unit: TimeUnit, amount: number): FunctionExpression;\n  timestampAdd(\n    unit: Expression | TimeUnit,\n    amount: Expression | number\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'timestamp_add',\n      [this, valueToDefaultExpr(unit), valueToDefaultExpr(amount)],\n      'timestampAdd'\n    );\n  }\n\n  /**\n   * Creates an expression that subtracts a specified amount of time from this timestamp expression.\n   *\n   * @example\n   * ```typescript\n   * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field.\n   * field(\"timestamp\").timestampSubtract(field(\"unit\"), field(\"amount\"));\n   * ```\n   *\n   * @param unit - The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'.\n   * @param amount - The expression evaluates to amount of the unit.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n   */\n  timestampSubtract(unit: Expression, amount: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that subtracts a specified amount of time from this timestamp expression.\n   *\n   * @example\n   * ```typescript\n   * // Subtract 1 day from the 'timestamp' field.\n   * field(\"timestamp\").timestampSubtract(\"day\", 1);\n   * ```\n   *\n   * @param unit - The unit of time to subtract (e.g., \"day\", \"hour\").\n   * @param amount - The amount of time to subtract.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n   */\n  timestampSubtract(unit: TimeUnit, amount: number): FunctionExpression;\n  timestampSubtract(\n    unit: Expression | TimeUnit,\n    amount: Expression | number\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'timestamp_subtract',\n      [this, valueToDefaultExpr(unit), valueToDefaultExpr(amount)],\n      'timestampSubtract'\n    );\n  }\n\n  /**\n   * Creates an expression that calculates the difference between this timestamp and another timestamp.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the difference determined by fields 'startTime' and 'unit'.\n   * field(\"endTime\").timestampDiff(field(\"startTime\"), field(\"unit\"));\n   * ```\n   *\n   * @param start - The expression evaluating to the starting timestamp.\n   * @param unit - The expression evaluates to a unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the difference as an integer.\n   */\n  timestampDiff(start: Expression, unit: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that calculates the difference between this timestamp and another timestamp.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the difference in days between 'endTime' and 'startTime' fields.\n   * field(\"endTime\").timestampDiff(\"startTime\", \"day\");\n   * ```\n   *\n   * @param start - The field name of the starting timestamp.\n   * @param unit - The unit of time for the difference (e.g., \"day\", \"hour\").\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the difference as an integer.\n   */\n  timestampDiff(start: string | Expression, unit: TimeUnit): FunctionExpression;\n  timestampDiff(\n    start: string | Expression,\n    unit: TimeUnit | Expression\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'timestamp_diff',\n      [this, fieldOrExpression(start), valueToDefaultExpr(unit)],\n      'timestampDiff'\n    );\n  }\n\n  /**\n   * Creates an expression that extracts a specified part from this timestamp expression.\n   *\n   * @example\n   * ```typescript\n   * // Extract the year from the 'createdAt' field.\n   * field('createdAt').timestampExtract('year')\n   * ```\n   *\n   * @param part - The part to extract from the timestamp (e.g., \"year\", \"month\", \"day\").\n   * @param timezone - The timezone to use for extraction. Valid values are from\n   * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1.\"\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the extracted part as an integer.\n   */\n  timestampExtract(\n    part: TimePart,\n    timezone?: string | Expression\n  ): FunctionExpression;\n\n  /**\n   * Creates an expression that extracts a specified part from this timestamp expression.\n   *\n   * @example\n   * ```typescript\n   * // Extract the part specified by the field 'extractionPart' from 'createdAt'.\n   * field('createdAt').timestampExtract(field('extractionPart'))\n   * ```\n   *\n   * @param part - The expression evaluating to the part to extract.\n   * @param timezone - The timezone to use for extraction. Valid values are from\n   * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1.\"\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the extracted part as an integer.\n   */\n  timestampExtract(\n    part: Expression,\n    timezone?: string | Expression\n  ): FunctionExpression;\n  timestampExtract(\n    part: TimePart | Expression,\n    timezone?: string | Expression\n  ): FunctionExpression {\n    const args = [this, valueToDefaultExpr(part)];\n    if (timezone) {\n      args.push(valueToDefaultExpr(timezone));\n    }\n    return new FunctionExpression(\n      'timestamp_extract',\n      args,\n      'timestampExtract'\n    );\n  }\n\n  /**\n   *\n   * Creates an expression that returns the document ID from a path.\n   *\n   * @example\n   * ```typescript\n   * // Get the document ID from a path.\n   * field(\"__path__\").documentId();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the documentId operation.\n   */\n  documentId(): FunctionExpression {\n    return new FunctionExpression('document_id', [this], 'documentId');\n  }\n\n  /**\n   *\n   * Creates an expression that returns the parent document reference of a document reference.\n   *\n   * @example\n   * ```typescript\n   * // Get the parent document reference of a document reference.\n   * field(\"__path__\").parent();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the parent operation.\n   */\n  parent(): FunctionExpression {\n    return new FunctionExpression('parent', [this], 'parent');\n  }\n\n  /**\n   *\n   * Creates an expression that returns a substring of the results of this expression.\n   *\n   * @param position - Index of the first character of the substring.\n   * @param length - Length of the substring. If not provided, the substring will\n   * end at the end of the input.\n   */\n  substring(position: number, length?: number): FunctionExpression;\n\n  /**\n   *\n   * Creates an expression that returns a substring of the results of this expression.\n   *\n   * @param position - An expression returning the index of the first character of the substring.\n   * @param length - An expression returning the length of the substring. If not provided the\n   * substring will end at the end of the input.\n   */\n  substring(position: Expression, length?: Expression): FunctionExpression;\n  substring(\n    position: Expression | number,\n    length?: Expression | number\n  ): FunctionExpression {\n    const positionExpr = valueToDefaultExpr(position);\n    if (length === undefined) {\n      return new FunctionExpression(\n        'substring',\n        [this, positionExpr],\n        'substring'\n      );\n    } else {\n      return new FunctionExpression(\n        'substring',\n        [this, positionExpr, valueToDefaultExpr(length)],\n        'substring'\n      );\n    }\n  }\n\n  /**\n   * Creates an expression that indexes into an array from the beginning or end\n   * and returns the element. If the offset exceeds the array length, an error is\n   * returned. A negative offset, starts from the end.\n   *\n   * @example\n   * ```typescript\n   * // Return the value in the 'tags' field array at index `1`.\n   * field('tags').arrayGet(1);\n   * ```\n   *\n   * @param offset - The index of the element to return.\n   * @returns A new `Expression` representing the 'arrayGet' operation.\n   */\n  arrayGet(offset: number): FunctionExpression;\n\n  /**\n   * Creates an expression that indexes into an array from the beginning or end\n   * and returns the element. If the offset exceeds the array length, an error is\n   * returned. A negative offset, starts from the end.\n   *\n   * @example\n   * ```typescript\n   * // Return the value in the tags field array at index specified by field\n   * // 'favoriteTag'.\n   * field('tags').arrayGet(field('favoriteTag'));\n   * ```\n   *\n   * @param offsetExpr - An `Expression` evaluating to the index of the element to return.\n   * @returns A new `Expression` representing the 'arrayGet' operation.\n   */\n  arrayGet(offsetExpr: Expression): FunctionExpression;\n  arrayGet(offset: Expression | number): FunctionExpression {\n    return new FunctionExpression(\n      'array_get',\n      [this, valueToDefaultExpr(offset)],\n      'arrayGet'\n    );\n  }\n\n  /**\n   *\n   * Creates an expression that checks if a given expression produces an error.\n   *\n   * @example\n   * ```typescript\n   * // Check if the result of a calculation is an error\n   * field(\"title\").arrayContains(1).isError();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#BooleanExpression} representing the 'isError' check.\n   */\n  isError(): BooleanExpression {\n    return new FunctionExpression('is_error', [this], 'isError').asBoolean();\n  }\n\n  /**\n   *\n   * Creates an expression that returns the result of the `catchExpr` argument\n   * if there is an error, else return the result of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Returns the first item in the title field arrays, or returns\n   * // the entire title field if the array is empty or the field is another type.\n   * field(\"title\").arrayGet(0).ifError(field(\"title\"));\n   * ```\n   *\n   * @param catchExpr - The catch expression that will be evaluated and\n   * returned if this expression produces an error.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n   */\n  ifError(catchExpr: Expression): FunctionExpression;\n\n  /**\n   *\n   * Creates an expression that returns the `catch` argument if there is an\n   * error, else return the result of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Returns the first item in the title field arrays, or returns\n   * // \"Default Title\"\n   * field(\"title\").arrayGet(0).ifError(\"Default Title\");\n   * ```\n   *\n   * @param catchValue - The value that will be returned if this expression\n   * produces an error.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n   */\n  ifError(catchValue: unknown): FunctionExpression;\n  ifError(catchValue: unknown): FunctionExpression | BooleanExpression {\n    const result = new FunctionExpression(\n      'if_error',\n      [this, valueToDefaultExpr(catchValue)],\n      'ifError'\n    );\n\n    return catchValue instanceof BooleanExpression\n      ? result.asBoolean()\n      : result;\n  }\n\n  /**\n   *\n   * Creates an expression that returns `true` if the result of this expression\n   * is absent. Otherwise, returns `false` even if the value is `null`.\n   *\n   * @example\n   * ```typescript\n   * // Check if the field `value` is absent.\n   * field(\"value\").isAbsent();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#BooleanExpression} representing the 'isAbsent' check.\n   */\n  isAbsent(): BooleanExpression {\n    return new FunctionExpression('is_absent', [this], 'isAbsent').asBoolean();\n  }\n\n  /**\n   *\n   * Creates an expression that removes a key from the map produced by evaluating this expression.\n   *\n   * @example\n   * ```\n   * // Removes the key 'baz' from the input map.\n   * map({foo: 'bar', baz: true}).mapRemove('baz');\n   * ```\n   *\n   * @param key - The name of the key to remove from the input map.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'mapRemove' operation.\n   */\n  mapRemove(key: string): FunctionExpression;\n  /**\n   *\n   * Creates an expression that removes a key from the map produced by evaluating this expression.\n   *\n   * @example\n   * ```\n   * // Removes the key 'baz' from the input map.\n   * map({foo: 'bar', baz: true}).mapRemove(constant('baz'));\n   * @example\n   * ```\n   *\n   * @param keyExpr - An expression that produces the name of the key to remove from the input map.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'mapRemove' operation.\n   */\n  mapRemove(keyExpr: Expression): FunctionExpression;\n  mapRemove(stringExpr: Expression | string): FunctionExpression {\n    return new FunctionExpression(\n      'map_remove',\n      [this, valueToDefaultExpr(stringExpr)],\n      'mapRemove'\n    );\n  }\n\n  /**\n   *\n   * Creates an expression that merges multiple map values.\n   *\n   * @example\n   * ```\n   * // Merges the map in the settings field with, a map literal, and a map in\n   * // that is conditionally returned by another expression\n   * field('settings').mapMerge({ enabled: true }, conditional(field('isAdmin'), { admin: true}, {})\n   * ```\n   *\n   * @param secondMap - A required second map to merge. Represented as a literal or\n   * an expression that returns a map.\n   * @param otherMaps - Optional additional maps to merge. Each map is represented\n   * as a literal or an expression that returns a map.\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'mapMerge' operation.\n   */\n  mapMerge(\n    secondMap: Record<string, unknown> | Expression,\n    ...otherMaps: Array<Record<string, unknown> | Expression>\n  ): FunctionExpression {\n    const secondMapExpr = valueToDefaultExpr(secondMap);\n    const otherMapExprs = otherMaps.map(valueToDefaultExpr);\n    return new FunctionExpression(\n      'map_merge',\n      [this, secondMapExpr, ...otherMapExprs],\n      'mapMerge'\n    );\n  }\n\n  /**\n   * Creates an expression that returns the value of this expression raised to the power of another expression.\n   *\n   * @example\n   * ```typescript\n   * // Raise the value of the 'base' field to the power of the 'exponent' field.\n   * field(\"base\").pow(field(\"exponent\"));\n   * ```\n   *\n   * @param exponent - The expression to raise this expression to the power of.\n   * @returns A new `Expression` representing the power operation.\n   */\n  pow(exponent: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that returns the value of this expression raised to the power of a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Raise the value of the 'base' field to the power of 2.\n   * field(\"base\").pow(2);\n   * ```\n   *\n   * @param exponent - The constant value to raise this expression to the power of.\n   * @returns A new `Expression` representing the power operation.\n   */\n  pow(exponent: number): FunctionExpression;\n  pow(exponent: number | Expression): FunctionExpression {\n    return new FunctionExpression('pow', [this, valueToDefaultExpr(exponent)]);\n  }\n\n  /**\n   * Creates an expression that truncates the numeric value to an integer.\n   *\n   * @example\n   * ```typescript\n   * // Truncate the 'rating' field\n   * field(\"rating\").trunc();\n   * ```\n   *\n   * @returns A new `Expression` representing the truncated value.\n   */\n  trunc(): FunctionExpression;\n\n  /**\n   * Creates an expression that truncates a numeric value to the specified number of decimal places.\n   *\n   * @example\n   * ```typescript\n   * // Truncate the value of the 'rating' field to two decimal places.\n   * field(\"rating\").trunc(2);\n   * ```\n   *\n   * @param decimalPlaces - A constant specifying the truncation precision in decimal places.\n   * @returns A new `Expression` representing the truncated value.\n   */\n  trunc(decimalPlaces: number): FunctionExpression;\n\n  /**\n   * Creates an expression that truncates a numeric value to the specified number of decimal places.\n   *\n   * @example\n   * ```typescript\n   * // Truncate the value of the 'rating' field to two decimal places.\n   * field(\"rating\").trunc(constant(2));\n   * ```\n   *\n   * @param decimalPlaces - An expression specifying the truncation precision in decimal places.\n   * @returns A new `Expression` representing the truncated value.\n   */\n  trunc(decimalPlaces: Expression): FunctionExpression;\n  trunc(decimalPlaces?: number | Expression): FunctionExpression {\n    if (decimalPlaces === undefined) {\n      return new FunctionExpression('trunc', [this]);\n    } else {\n      return new FunctionExpression(\n        'trunc',\n        [this, valueToDefaultExpr(decimalPlaces)],\n        'trunc'\n      );\n    }\n  }\n\n  /**\n   * Creates an expression that rounds a numeric value to the nearest whole number.\n   *\n   * @example\n   * ```typescript\n   * // Round the value of the 'price' field.\n   * field(\"price\").round();\n   * ```\n   *\n   * @returns A new `Expression` representing the rounded value.\n   */\n  round(): FunctionExpression;\n  /**\n   * Creates an expression that rounds a numeric value to the specified number of decimal places.\n   *\n   * @example\n   * ```typescript\n   * // Round the value of the 'price' field to two decimal places.\n   * field(\"price\").round(2);\n   * ```\n   *\n   * @param decimalPlaces - A constant specifying the rounding precision in decimal places.\n   *\n   * @returns A new `Expression` representing the rounded value.\n   */\n  round(decimalPlaces: number): FunctionExpression;\n  /**\n   * Creates an expression that rounds a numeric value to the specified number of decimal places.\n   *\n   * @example\n   * ```typescript\n   * // Round the value of the 'price' field to two decimal places.\n   * field(\"price\").round(constant(2));\n   * ```\n   *\n   * @param decimalPlaces - An expression specifying the rounding precision in decimal places.\n   *\n   * @returns A new `Expression` representing the rounded value.\n   */\n  round(decimalPlaces: Expression): FunctionExpression;\n  round(decimalPlaces?: number | Expression): FunctionExpression {\n    if (decimalPlaces === undefined) {\n      return new FunctionExpression('round', [this]);\n    } else {\n      return new FunctionExpression(\n        'round',\n        [this, valueToDefaultExpr(decimalPlaces)],\n        'round'\n      );\n    }\n  }\n\n  /**\n   * Creates an expression that returns the collection ID from a path.\n   *\n   * @example\n   * ```typescript\n   * // Get the collection ID from a path.\n   * field(\"__path__\").collectionId();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the collectionId operation.\n   */\n  collectionId(): FunctionExpression {\n    return new FunctionExpression('collection_id', [this]);\n  }\n\n  /**\n   * Creates an expression that calculates the length of a string, array, map, vector, or bytes.\n   *\n   * @example\n   * ```typescript\n   * // Get the length of the 'name' field.\n   * field(\"name\").length();\n   *\n   * // Get the number of items in the 'cart' array.\n   * field(\"cart\").length();\n   * ```\n   *\n   * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes.\n   */\n  length(): FunctionExpression {\n    return new FunctionExpression('length', [this]);\n  }\n\n  /**\n   * Creates an expression that computes the natural logarithm of a numeric value.\n   *\n   * @example\n   * ```typescript\n   * // Compute the natural logarithm of the 'value' field.\n   * field(\"value\").ln();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the natural logarithm of the numeric value.\n   */\n  ln(): FunctionExpression {\n    return new FunctionExpression('ln', [this]);\n  }\n\n  /**\n   * Creates an expression that computes the square root of a numeric value.\n   *\n   * @example\n   * ```typescript\n   * // Compute the square root of the 'value' field.\n   * field(\"value\").sqrt();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the square root of the numeric value.\n   */\n  sqrt(): FunctionExpression {\n    return new FunctionExpression('sqrt', [this]);\n  }\n\n  /**\n   * Creates an expression that reverses a string.\n   *\n   * @example\n   * ```typescript\n   * // Reverse the value of the 'myString' field.\n   * field(\"myString\").stringReverse();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.\n   */\n  stringReverse(): FunctionExpression {\n    return new FunctionExpression('string_reverse', [this]);\n  }\n\n  /**\n   * Creates an expression that returns the `elseValue` argument if this expression results in an absent value, else\n   * return the result of this expression evaluation.\n   *\n   * @example\n   * ```typescript\n   * // Returns the value of the optional field 'optional_field', or returns 'default_value'\n   * // if the field is absent.\n   * field(\"optional_field\").ifAbsent(\"default_value\")\n   * ```\n   *\n   * @param elseValue - The value that will be returned if this Expression evaluates to an absent value.\n   * @returns A new [Expression] representing the ifAbsent operation.\n   */\n  ifAbsent(elseValue: unknown): Expression;\n\n  /**\n   * Creates an expression that returns the `elseValue` argument if this expression results in an absent value, else\n   * return the result of this expression evaluation.\n   *\n   * @example\n   * ```typescript\n   * // Returns the value of the optional field 'optional_field', or if that is\n   * // absent, then returns the value of the field `default_field`.\n   * field(\"optional_field\").ifAbsent(field('default_field'))\n   * ```\n   *\n   * @param elseExpression - The Expression that will be evaluated if this Expression evaluates to an absent value.\n   * @returns A new [Expression] representing the ifAbsent operation.\n   */\n  ifAbsent(elseExpression: unknown): Expression;\n\n  ifAbsent(elseValueOrExpression: Expression | unknown): Expression {\n    return new FunctionExpression(\n      'if_absent',\n      [this, valueToDefaultExpr(elseValueOrExpression)],\n      'ifAbsent'\n    );\n  }\n\n  /**\n   * Creates an expression that returns the `elseValue` argument if this expression evaluates to null, else\n   * return the result of this expression evaluation.\n   *\n   * @remarks\n   * This function provides a fallback for both absent and explicit null values. In contrast,\n   * `ifAbsent()` only triggers for missing fields.\n   *\n   * @example\n   * ```typescript\n   * // Returns the user's preferred name, or if that is null, returns their full name.\n   * field(\"preferredName\").ifNull(field(\"fullName\"))\n   * ```\n   *\n   * @param elseExpression - The Expression that will be evaluated if this Expression evaluates to null.\n   * @returns A new `Expression` representing the ifNull operation.\n   */\n  ifNull(elseExpression: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that returns the `elseValue` argument if this expression evaluates to null, else\n   * return the result of this expression evaluation.\n   *\n   * @remarks\n   * This function provides a fallback for both absent and explicit null values. In contrast,\n   * `ifAbsent()` only triggers for missing fields.\n   *\n   * @example\n   * ```typescript\n   * // Returns the user's display name, or returns \"Anonymous\" if the field is null.\n   * field(\"displayName\").ifNull(\"Anonymous\")\n   * ```\n   *\n   * @param elseValue - The value that will be returned if this Expression evaluates to null.\n   * @returns A new `Expression` representing the ifNull operation.\n   */\n  ifNull(elseValue: unknown): FunctionExpression;\n  ifNull(elseValueOrExpression: Expression | unknown): FunctionExpression {\n    return new FunctionExpression(\n      'if_null',\n      [this, valueToDefaultExpr(elseValueOrExpression)],\n      'ifNull'\n    );\n  }\n\n  /**\n   * Creates an expression that returns the first non-null, non-absent argument, without evaluating\n   * the rest of the arguments. When all arguments are null or absent, returns the last argument.\n   *\n   * @example\n   * ```typescript\n   * // Returns the value of the first non-null, non-absent field among 'preferredName', 'fullName',\n   * // or the last argument if all previous fields are null.\n   * field(\"preferredName\").coalesce(field(\"fullName\"), \"Anonymous\");\n   * ```\n   *\n   * @param replacement - The value to use if this expression evaluates to null.\n   * @param others - Optional additional values to check if previous values are null.\n   * @returns A new `Expression` representing the coalesce operation.\n   */\n  coalesce(\n    replacement: Expression | unknown,\n    ...others: Array<Expression | unknown>\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'coalesce',\n      [\n        this,\n        valueToDefaultExpr(replacement),\n        ...others.map(valueToDefaultExpr)\n      ],\n      'coalesce'\n    );\n  }\n\n  /**\n   * Creates an expression that joins the elements of an array into a string.\n   *\n   * @example\n   * ```typescript\n   * // Join the elements of the 'tags' field with the delimiter from the 'separator' field.\n   * field(\"tags\").join(field(\"separator\"))\n   * ```\n   *\n   * @param delimiterExpression - The expression that evaluates to the delimiter string.\n   * @returns A new Expression representing the join operation.\n   */\n  join(delimiterExpression: Expression): Expression;\n\n  /**\n   * Creates an expression that joins the elements of an array field into a string.\n   *\n   * @example\n   * ```typescript\n   * // Join the elements of the 'tags' field with a comma and space.\n   * field(\"tags\").join(\", \")\n   * ```\n   *\n   * @param delimiter - The string to use as a delimiter.\n   * @returns A new Expression representing the join operation.\n   */\n  join(delimiter: string): Expression;\n\n  join(delimeterValueOrExpression: string | Expression): Expression {\n    return new FunctionExpression(\n      'join',\n      [this, valueToDefaultExpr(delimeterValueOrExpression)],\n      'join'\n    );\n  }\n\n  /**\n   * Creates an expression that computes the base-10 logarithm of a numeric value.\n   *\n   * @example\n   * ```typescript\n   * // Compute the base-10 logarithm of the 'value' field.\n   * field(\"value\").log10();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the base-10 logarithm of the numeric value.\n   */\n  log10(): FunctionExpression {\n    return new FunctionExpression('log10', [this]);\n  }\n\n  /**\n   * Creates an expression that computes the sum of the elements in an array.\n   *\n   * @example\n   * ```typescript\n   * // Compute the sum of the elements in the 'scores' field.\n   * field(\"scores\").arraySum();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the sum of the elements in the array.\n   */\n  arraySum(): FunctionExpression {\n    return new FunctionExpression('sum', [this]);\n  }\n\n  /**\n   * Creates an expression that splits the result of this expression into an\n   * array of substrings based on the provided delimiter.\n   *\n   * @example\n   * ```typescript\n   * // Split the 'scoresCsv' field on delimiter ','\n   * field('scoresCsv').split(',')\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function.\n   */\n  split(delimiter: string): FunctionExpression;\n\n  /**\n   * Creates an expression that splits the result of this expression into an\n   * array of substrings based on the provided delimiter.\n   *\n   * @example\n   * ```typescript\n   * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format\n   * field('scores').split(conditional(field('format').equal('csv'), constant(','), constant(':')))\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function.\n   */\n  split(delimiter: Expression): FunctionExpression;\n  split(delimiter: string | Expression): FunctionExpression {\n    return new FunctionExpression('split', [\n      this,\n      valueToDefaultExpr(delimiter)\n    ]);\n  }\n\n  /**\n   * Creates an expression that truncates a timestamp to a specified granularity.\n   *\n   * @example\n   * ```typescript\n   * // Truncate the 'createdAt' timestamp to the beginning of the day.\n   * field('createdAt').timestampTruncate('day')\n   * ```\n   *\n   * @param granularity - The granularity to truncate to.\n   * @param timezone - The timezone to use for truncation. Valid values are from\n   * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1\".\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the truncated timestamp.\n   */\n  timestampTruncate(\n    granularity: TimeGranularity,\n    timezone?: string | Expression\n  ): FunctionExpression;\n\n  /**\n   * Creates an expression that truncates a timestamp to a specified granularity.\n   *\n   * @example\n   * ```typescript\n   * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'.\n   * field('createdAt').timestampTruncate(field('granularity'))\n   * ```\n   *\n   * @param granularity - The granularity to truncate to.\n   * @param timezone - The timezone to use for truncation. Valid values are from\n   * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1\".\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the truncated timestamp.\n   */\n  timestampTruncate(\n    granularity: Expression,\n    timezone?: string | Expression\n  ): FunctionExpression;\n  timestampTruncate(\n    granularity: TimeGranularity | Expression,\n    timezone?: string | Expression\n  ): FunctionExpression {\n    const args = [this, valueToDefaultExpr(granularity)];\n    if (timezone) {\n      args.push(valueToDefaultExpr(timezone));\n    }\n    return new FunctionExpression('timestamp_trunc', args);\n  }\n\n  // TODO(search) enable with backend support\n  // /**\n  //  * Evaluates if the result of this `expression` is between\n  //  * the `lowerBound` (inclusive) and `upperBound` (inclusive).\n  //  *\n  //  * @example\n  //  * ```\n  //  * // Evaluate if the 'tireWidth' is between 2.2 and 2.4\n  //  * field('tireWidth').between(constant(2.2), constant(2.4))\n  //  *\n  //  * // This is functionally equivalent to\n  //  * and(field('tireWidth').greaterThanOrEqual(contant(2.2)), field('tireWidth').lessThanOrEqual(constant(2.4)))\n  //  * ```\n  //  *\n  //  * @param lowerBound - Lower bound (inclusive) of the range.\n  //  * @param upperBound - Upper bound (inclusive) of the range.\n  //  */\n  // between(lowerBound: Expression, upperBound: Expression): BooleanExpression;\n  //\n  // /**\n  //  * Evaluates if the result of this `expression` is between\n  //  * the `lowerBound` (inclusive) and `upperBound` (inclusive).\n  //  *\n  //  * @example\n  //  * ```\n  //  * // Evaluate if the 'tireWidth' is between 2.2 and 2.4\n  //  * field('tireWidth').between(2.2, 2.4)\n  //  *\n  //  * // This is functionally equivalent to\n  //  * and(field('tireWidth').greaterThanOrEqual(2.2), field('tireWidth').lessThanOrEqual(2.4))\n  //  * ```\n  //  *\n  //  * @param lowerBound - Lower bound (inclusive) of the range.\n  //  * @param upperBound - Upper bound (inclusive) of the range.\n  //  */\n  // between(lowerBound: unknown, upperBound: unknown): BooleanExpression;\n  //\n  // between(lowerBound: unknown, upperBound: unknown): BooleanExpression {\n  //   return new FunctionExpression('between', [\n  //     this,\n  //     valueToDefaultExpr(lowerBound),\n  //     valueToDefaultExpr(upperBound)\n  //   ]).asBoolean();\n  // }\n\n  // TODO(search) enable with backend support\n  // /**\n  //  * Evaluates to an HTML-formatted text snippet that renders terms matching\n  //  * the search query in `<b>bold</b>`.\n  //  *\n  //  * @remarks This Expression can only be used within a `search` stage.\n  //  *\n  //  * @param rquery Define the search query using the search domain-specific language (DSL).\n  //  */\n  // snippet(rquery: string): Expression;\n  //\n  // /**\n  //  * Evaluates to an HTML-formatted text snippet that renders terms matching\n  //  * the search query in `<b>bold</b>`.\n  //  *\n  //  * @remarks This Expression can only be used within a `search` stage.\n  //  *\n  //  * @param options Define how snippeting behaves.\n  //  */\n  // snippet(options: SnippetOptions): Expression;\n  //\n  // snippet(queryOrOptions: string | SnippetOptions): Expression {\n  //   const options: SnippetOptions = isString(queryOrOptions)\n  //     ? { rquery: queryOrOptions }\n  //     : queryOrOptions;\n  //   const rquery = options.rquery;\n  //   const internalOptions = {\n  //     maxSnippetWidth: options.maxSnippetWidth,\n  //     maxSnippets: options.maxSnippets,\n  //     separator: options.separator\n  //   };\n  //   return new SnippetExpression([this, constant(rquery)], internalOptions);\n  // }\n\n  // TODO(new-expression): Add new expression method definitions above this line\n\n  /**\n   * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in ascending order based on this expression.\n   *\n   * @example\n   * ```typescript\n   * // Sort documents by the 'name' field in ascending order\n   * firestore.pipeline().collection(\"users\")\n   *   .sort(field(\"name\").ascending());\n   * ```\n   *\n   * @returns A new `Ordering` for ascending sorting.\n   */\n  ascending(): Ordering {\n    return ascending(this);\n  }\n\n  /**\n   * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in descending order based on this expression.\n   *\n   * @example\n   * ```typescript\n   * // Sort documents by the 'createdAt' field in descending order\n   * firestore.pipeline().collection(\"users\")\n   *   .sort(field(\"createdAt\").descending());\n   * ```\n   *\n   * @returns A new `Ordering` for descending sorting.\n   */\n  descending(): Ordering {\n    return descending(this);\n  }\n\n  /**\n   * Assigns an alias to this expression.\n   *\n   * Aliases are useful for renaming fields in the output of a stage or for giving meaningful\n   * names to calculated values.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the total price and assign it the alias \"totalPrice\" and add it to the output.\n   * firestore.pipeline().collection(\"items\")\n   *   .addFields(field(\"price\").multiply(field(\"quantity\")).as(\"totalPrice\"));\n   * ```\n   *\n   * @param name - The alias to assign to this expression.\n   * @returns A new {@link @firebase/firestore/pipelines#AliasedExpression} that wraps this\n   *     expression and associates it with the provided alias.\n   */\n  as(name: string): AliasedExpression {\n    return new AliasedExpression(this, name, 'as');\n  }\n}\n\n/**\n * Specify time units for expressions.\n */\nexport type TimeUnit =\n  | 'microsecond'\n  | 'millisecond'\n  | 'second'\n  | 'minute'\n  | 'hour'\n  | 'day';\n\n/**\n * Specify time granularity for expressions.\n */\nexport type TimeGranularity =\n  | TimeUnit\n  | 'week'\n  | 'week(monday)'\n  | 'week(tuesday)'\n  | 'week(wednesday)'\n  | 'week(thursday)'\n  | 'week(friday)'\n  | 'week(saturday)'\n  | 'week(sunday)'\n  | 'isoweek'\n  | 'month'\n  | 'quarter'\n  | 'year'\n  | 'isoyear';\n\n/**\n * Specify time parts for `timestampExtract` expressions.\n */\nexport type TimePart = TimeGranularity | 'dayofweek' | 'dayofyear';\n\n/**\n *\n * An interface that represents a selectable expression.\n */\nexport interface Selectable {\n  selectable: true;\n  /**\n   * @private\n   * @internal\n   */\n  readonly alias: string;\n  /**\n   * @private\n   * @internal\n   */\n  readonly expr: Expression;\n}\n\n/**\n *\n * A class that represents an aggregate function.\n */\nexport class AggregateFunction implements ProtoValueSerializable, UserData {\n  exprType: ExpressionType = 'AggregateFunction';\n\n  /**\n   * @internal\n   */\n  _methodName?: string;\n\n  constructor(private name: string, private params: Expression[]) {}\n\n  /**\n   * @internal\n   * @private\n   */\n  static _create(\n    name: string,\n    params: Expression[],\n    methodName: string\n  ): AggregateFunction {\n    const af = new AggregateFunction(name, params);\n    af._methodName = methodName;\n\n    return af;\n  }\n\n  /**\n   * Assigns an alias to this AggregateFunction. The alias specifies the name that\n   * the aggregated value will have in the output document.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the average price of all items and assign it the alias \"averagePrice\".\n   * firestore.pipeline().collection(\"items\")\n   *   .aggregate(field(\"price\").average().as(\"averagePrice\"));\n   * ```\n   *\n   * @param name - The alias to assign to this AggregateFunction.\n   * @returns A new {@link @firebase/firestore/pipelines#AliasedAggregate} that wraps this\n   *     AggregateFunction and associates it with the provided alias.\n   */\n  as(name: string): AliasedAggregate {\n    return new AliasedAggregate(this, name, 'as');\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoValue {\n    return {\n      functionValue: {\n        name: this.name,\n        args: this.params.map(p => p._toProto(serializer))\n      }\n    };\n  }\n\n  _protoValueType = 'ProtoValue' as const;\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    context = this._methodName\n      ? context.contextWith({ methodName: this._methodName })\n      : context;\n    this.params.forEach(expr => {\n      return expr._readUserData(context);\n    });\n  }\n}\n\n/**\n *\n * An AggregateFunction with alias.\n */\nexport class AliasedAggregate implements UserData {\n  constructor(\n    readonly aggregate: AggregateFunction,\n    readonly alias: string,\n    readonly _methodName: string | undefined\n  ) {}\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    this.aggregate._readUserData(context);\n  }\n}\n\nexport class AliasedExpression implements Selectable, UserData {\n  exprType: ExpressionType = 'AliasedExpression';\n  selectable = true as const;\n\n  constructor(\n    readonly expr: Expression,\n    readonly alias: string,\n    readonly _methodName: string | undefined\n  ) {}\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    this.expr._readUserData(context);\n  }\n}\n\n/**\n * @internal\n */\nexport class ListOfExprs extends Expression implements UserData {\n  expressionType: ExpressionType = 'ListOfExpressions';\n\n  constructor(\n    public readonly exprs: Expression[],\n    readonly _methodName: string | undefined\n  ) {\n    super();\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoValue {\n    return {\n      arrayValue: {\n        values: this.exprs.map(p => p._toProto(serializer)!)\n      }\n    };\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    this.exprs.forEach((expr: Expression) => expr._readUserData(context));\n  }\n}\n\n/**\n *\n * Represents a reference to a field in a Firestore document, or outputs of a {@link @firebase/firestore/pipelines#Pipeline} stage.\n *\n * <p>Field references are used to access document field values in expressions and to specify fields\n * for sorting, filtering, and projecting data in Firestore pipelines.\n *\n * <p>You can create a `Field` instance using the static {@link @firebase/firestore/pipelines#field} method:\n *\n * @example\n * ```typescript\n * // Create a Field instance for the 'name' field\n * const nameField = field(\"name\");\n *\n * // Create a Field instance for a nested field 'address.city'\n * const cityField = field(\"address.city\");\n * ```\n */\nexport class Field extends Expression implements Selectable {\n  readonly expressionType: ExpressionType = 'Field';\n  selectable = true as const;\n\n  /**\n   * @internal\n   * @private\n   * @hideconstructor\n   * @param fieldPath\n   */\n  constructor(\n    private fieldPath: InternalFieldPath,\n    readonly _methodName: string | undefined\n  ) {\n    super();\n  }\n\n  get _fieldPath(): InternalFieldPath {\n    return this.fieldPath;\n  }\n\n  get fieldName(): string {\n    return this.fieldPath.canonicalString();\n  }\n\n  get alias(): string {\n    return this.fieldName;\n  }\n\n  get expr(): Expression {\n    return this;\n  }\n\n  // TODO(search) enable with backend support\n  // /**\n  //  * Perform a full-text search on this field.\n  //  *\n  //  * @remarks This Expression can only be used within a `search` stage.\n  //  *\n  //  * @param rquery Define the search query using the search domain-specific language (DSL).\n  //  */\n  // matches(rquery: string | Expression): BooleanExpression {\n  //   return new FunctionExpression(\n  //     'matches',\n  //     [this, valueToDefaultExpr(rquery)],\n  //     'matches'\n  //   ).asBoolean();\n  // }\n\n  /**\n   * @beta\n   * Evaluates to the distance in meters between the location specified\n   * by this field and the query location.\n   *\n   * @remarks This Expression can only be used within a `search` stage.\n   *\n   * @param location - Compute distance to this GeoPoint.\n   */\n  geoDistance(location: GeoPoint | Expression): Expression {\n    return new FunctionExpression(\n      'geo_distance',\n      [this, valueToDefaultExpr(location)],\n      'geoDistance'\n    );\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoValue {\n    return {\n      fieldReferenceValue: this.fieldPath.canonicalString()\n    };\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {}\n}\n\n/**\n * Creates a {@link @firebase/firestore/pipelines#Field} instance representing the field at the given path.\n *\n * The path can be a simple field name (e.g., \"name\") or a dot-separated path to a nested field\n * (e.g., \"address.city\").\n *\n * @example\n * ```typescript\n * // Create a Field instance for the 'title' field\n * const titleField = field(\"title\");\n *\n * // Create a Field instance for a nested field 'author.firstName'\n * const authorFirstNameField = field(\"author.firstName\");\n * ```\n *\n * @param name - The path to the field.\n * @returns A new {@link @firebase/firestore/pipelines#Field} instance representing the specified field.\n */\nexport function field(name: string): Field;\n\n/**\n * Creates a {@link @firebase/firestore/pipelines#Field} instance representing the field at the given path.\n *\n * @param path - A FieldPath specifying the field.\n * @returns A new {@link @firebase/firestore/pipelines#Field} instance representing the specified field.\n */\nexport function field(path: FieldPath): Field;\nexport function field(nameOrPath: string | FieldPath): Field {\n  return _field(nameOrPath, 'field');\n}\n\nexport function _field(\n  nameOrPath: string | FieldPath,\n  methodName: string | undefined\n): Field {\n  if (typeof nameOrPath === 'string') {\n    if (DOCUMENT_KEY_NAME === nameOrPath) {\n      return new Field(documentIdFieldPath()._internalPath, methodName);\n    }\n    return new Field(fieldPathFromArgument('field', nameOrPath), methodName);\n  } else {\n    return new Field(nameOrPath._internalPath, methodName);\n  }\n}\n\n/**\n * @internal\n *\n * Represents a constant value that can be used in a Firestore pipeline expression.\n *\n * You can create a `Constant` instance using the static {@link @firebase/firestore/pipelines#field} method:\n *\n * @example\n * ```typescript\n * // Create a Constant instance for the number 10\n * const ten = constant(10);\n *\n * // Create a Constant instance for the string \"hello\"\n * const hello = constant(\"hello\");\n * ```\n */\nexport class Constant extends Expression {\n  readonly expressionType: ExpressionType = 'Constant';\n\n  private _protoValue?: ProtoValue;\n\n  /**\n   * @private\n   * @internal\n   * @hideconstructor\n   * @param value - The value of the constant.\n   */\n  constructor(\n    public readonly value: unknown,\n    readonly _methodName: string | undefined\n  ) {\n    super();\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  static _fromProto(value: ProtoValue): Constant {\n    const result = new Constant(value, undefined);\n    result._protoValue = value;\n    return result;\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(_: JsonProtoSerializer): ProtoValue {\n    hardAssert(\n      this._protoValue !== undefined,\n      0x00ed,\n      'Value of this constant has not been serialized to proto value'\n    );\n    return this._protoValue;\n  }\n\n  _getValue(): ProtoValue {\n    return this._protoValue!;\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    context = this._methodName\n      ? context.contextWith({ methodName: this._methodName })\n      : context;\n    if (isFirestoreValue(this._protoValue)) {\n      return;\n    } else {\n      this._protoValue = parseData(this.value, context)!;\n    }\n  }\n}\n\n/**\n * Creates a `Constant` instance for a number value.\n *\n * @param value - The number value.\n * @returns A new `Constant` instance.\n */\nexport function constant(\n  value: number,\n  options?: { preferIntegers?: boolean }\n): Expression;\n\n/**\n * Creates a `Constant` instance for a string value.\n *\n * @param value - The string value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: string): Expression;\n\n/**\n * Creates a `BooleanExpression` instance for a boolean value.\n *\n * @param value - The boolean value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: boolean): BooleanExpression;\n\n/**\n * Creates a `Constant` instance for a null value.\n *\n * @param value - The null value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: null): Expression;\n\n/**\n * Creates a `Constant` instance for a GeoPoint value.\n *\n * @param value - The GeoPoint value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: GeoPoint): Expression;\n\n/**\n * Creates a `Constant` instance for a Timestamp value.\n *\n * @param value - The Timestamp value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: Timestamp): Expression;\n\n/**\n * Creates a `Constant` instance for a Date value.\n *\n * @param value - The Date value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: Date): Expression;\n\n/**\n * Creates a `Constant` instance for a Bytes value.\n *\n * @param value - The Bytes value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: Bytes): Expression;\n\n/**\n * Creates a `Constant` instance for a DocumentReference value.\n *\n * @param value - The DocumentReference value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: DocumentReference): Expression;\n\n/**\n * Creates a `Constant` instance for a Firestore proto value.\n * For internal use only.\n * @private\n * @internal\n * @param value - The Firestore proto value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: ProtoValue): Expression;\n\n/**\n * Creates a `Constant` instance for a VectorValue value.\n *\n * @param value - The VectorValue value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: VectorValue): Expression;\n\nexport function constant(\n  value: unknown,\n  options?: { preferIntegers?: boolean }\n): Expression | BooleanExpression {\n  return _constant(value, 'constant');\n}\n\n/**\n * @internal\n * @private\n * @param value\n * @param methodName\n */\nexport function _constant(\n  value: unknown,\n  methodName: string | undefined\n): Constant | BooleanExpression {\n  const c = new Constant(value, methodName);\n  if (typeof value === 'boolean') {\n    return new BooleanConstant(c);\n  } else {\n    return c;\n  }\n}\n\n/**\n * Internal only\n * @internal\n * @private\n */\nexport class MapValue extends Expression {\n  constructor(\n    private plainObject: Map<string, Expression>,\n    readonly _methodName: string | undefined\n  ) {\n    super();\n  }\n\n  expressionType: ExpressionType = 'Constant';\n\n  _readUserData(context: ParseContext): void {\n    context = this._methodName\n      ? context.contextWith({ methodName: this._methodName })\n      : context;\n    this.plainObject.forEach(expr => {\n      expr._readUserData(context);\n    });\n  }\n\n  _toProto(serializer: JsonProtoSerializer): ProtoValue {\n    return toMapValue(serializer, this.plainObject);\n  }\n}\n\n/**\n *\n * This class defines the base class for Firestore {@link @firebase/firestore/pipelines#Pipeline} functions, which can be evaluated within pipeline\n * execution.\n *\n * Typically, you would not use this class or its children directly. Use either the functions like {@link @firebase/firestore/pipelines#and}, {@link @firebase/firestore/pipelines#(equal:1)},\n * or the methods on {@link @firebase/firestore/pipelines#Expression} ({@link @firebase/firestore/pipelines#Expression.(equal:1)}, {@link @firebase/firestore/pipelines#Expression.(lessThan:1)}, etc.) to construct new Function instances.\n */\nexport class FunctionExpression extends Expression {\n  readonly expressionType: ExpressionType = 'Function';\n\n  constructor(name: string, params: Expression[]);\n\n  /**\n   * @hideconstructor\n   */\n  constructor(\n    name: string,\n    params: Expression[],\n    _methodName?: string,\n    options?: {}\n  );\n\n  /**\n   * @hideconstructor\n   */\n  constructor(\n    public readonly name: string,\n    public readonly params: Expression[],\n    methodName?: string,\n    options?: {}\n  ) {\n    super();\n\n    if (methodName !== undefined) {\n      this._methodName = methodName;\n    }\n    if (options !== undefined) {\n      this._options = options;\n    }\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _methodName: string | undefined;\n\n  /**\n   * @private\n   * @internal\n   */\n  private _options: {} | undefined;\n\n  /**\n   * @private\n   * @internal\n   */\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _optionsProto:\n    | ApiClientObjectMap<firestoreV1ApiClientInterfaces.Value>\n    | undefined = undefined;\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoValue {\n    const returnValue: ProtoValue = {\n      functionValue: {\n        name: this.name,\n        args: this.params.map(p => p._toProto(serializer))\n      }\n    };\n\n    if (this._optionsProto) {\n      returnValue.functionValue!.options = this._optionsProto;\n    }\n\n    return returnValue;\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    context = this._methodName\n      ? context.contextWith({ methodName: this._methodName })\n      : context;\n    this.params.forEach(expr => {\n      return expr._readUserData(context);\n    });\n    if (this._options) {\n      this._optionsProto = this._optionsUtil.getOptionsProto(\n        context,\n        this._options\n      );\n    }\n  }\n}\n\n/**\n *\n * An interface that represents a filter condition.\n */\nexport abstract class BooleanExpression extends Expression {\n  abstract get _expr(): Expression;\n\n  get _methodName(): string | undefined {\n    return this._expr._methodName;\n  }\n\n  /**\n   * Creates an aggregation that finds the count of input documents satisfying\n   * this boolean expression.\n   *\n   * @example\n   * ```typescript\n   * // Find the count of documents with a score greater than 90\n   * field(\"score\").greaterThan(90).countIf().as(\"highestScore\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'countIf' aggregation.\n   */\n  countIf(): AggregateFunction {\n    return AggregateFunction._create('count_if', [this], 'countIf');\n  }\n\n  /**\n   * Creates an expression that negates this boolean expression.\n   *\n   * @example\n   * ```typescript\n   * // Find documents where the 'tags' field does not contain 'completed'\n   * field(\"tags\").arrayContains(\"completed\").not();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the negated filter condition.\n   */\n  not(): BooleanExpression {\n    return new FunctionExpression('not', [this], 'not').asBoolean();\n  }\n\n  /**\n   * Creates a conditional expression that evaluates to the 'then' expression\n   * if `this` expression evaluates to `true`,\n   * or evaluates to the 'else' expression if `this` expressions evaluates `false`.\n   *\n   * @example\n   * ```typescript\n   * // If 'age' is greater than 18, return \"Adult\"; otherwise, return \"Minor\".\n   * field(\"age\").greaterThanOrEqual(18).conditional(constant(\"Adult\"), constant(\"Minor\"));\n   * ```\n   *\n   * @param thenExpr - The expression to evaluate if the condition is true.\n   * @param elseExpr - The expression to evaluate if the condition is false.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the conditional expression.\n   */\n  conditional(thenExpr: Expression, elseExpr: Expression): FunctionExpression {\n    return new FunctionExpression(\n      'conditional',\n      [this, thenExpr, elseExpr],\n      'conditional'\n    );\n  }\n\n  /**\n   *\n   * Creates an expression that returns the `catch` argument if there is an\n   * error, else return the result of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Create an expression that protects against a divide by zero error\n   * // but always returns a boolean expression.\n   * constant(50).divide(field('length')).greaterThan(1).ifError(constant(false));\n   * ```\n   *\n   * @param catchValue - The value that will be returned if this expression\n   * produces an error.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n   */\n  ifError(catchValue: BooleanExpression): BooleanExpression;\n\n  /**\n   *\n   * Creates an expression that returns the `catch` argument if there is an\n   * error, else return the result of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Create an expression that protects against a divide by zero error\n   * // but always returns a boolean expression.\n   * constant(50).divide(field('length')).greaterThan(1).ifError(false);\n   * ```\n   *\n   * @param catchValue - The value that will be returned if this expression\n   * produces an error.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n   */\n  ifError(catchValue: boolean): BooleanExpression;\n\n  /**\n   *\n   * Creates an expression that returns the `catch` argument if there is an\n   * error, else return the result of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Create an expression that protects against a divide by zero error.\n   * constant(50).divide(field('length')).greaterThan(1).ifError(constant(0));\n   * ```\n   *\n   * @param catchValue - The value that will be returned if this expression\n   * produces an error.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n   */\n  ifError(catchValue: Expression): FunctionExpression;\n\n  /**\n   *\n   * Creates an expression that returns the `catch` argument if there is an\n   * error, else return the result of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Create an expression that protects against a divide by zero error.\n   * constant(50).divide(field('length')).greaterThan(1).ifError(0);\n   * ```\n   *\n   * @param catchValue - The value that will be returned if this expression\n   * produces an error.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n   */\n  ifError(catchValue: unknown): FunctionExpression;\n  ifError(catchValue: unknown): unknown {\n    const normalizedCatchValue = valueToDefaultExpr(catchValue);\n    const expr = new FunctionExpression(\n      'if_error',\n      [this, normalizedCatchValue],\n      'ifError'\n    );\n\n    return normalizedCatchValue instanceof BooleanExpression\n      ? expr.asBoolean()\n      : expr;\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoValue {\n    return this._expr._toProto(serializer);\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    this._expr._readUserData(context);\n  }\n}\n\nexport class BooleanFunctionExpression extends BooleanExpression {\n  readonly expressionType: ExpressionType = 'Function';\n  constructor(readonly _expr: FunctionExpression) {\n    super();\n  }\n}\n\nexport class BooleanConstant extends BooleanExpression {\n  readonly expressionType: ExpressionType = 'Constant';\n  constructor(readonly _expr: Constant) {\n    super();\n  }\n\n  _getValue(): unknown {\n    return this._expr._getValue();\n  }\n}\n\nexport class BooleanField extends BooleanExpression {\n  readonly expressionType: ExpressionType = 'Field';\n  constructor(readonly _expr: Field) {\n    super();\n  }\n}\n\n/**\n * SnippetExpression extends from FunctionExpression because it\n * supports options and requires the options util.\n */\nexport class SnippetExpression extends FunctionExpression {\n  /**\n   * @private\n   * @internal\n   */\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({\n      maxSnippetWidth: {\n        serverName: 'max_snippet_width'\n      },\n      maxSnippets: {\n        serverName: 'max_snippets'\n      },\n      separator: {\n        serverName: 'separator'\n      }\n    });\n  }\n\n  /**\n   * @hideconstructor\n   */\n  constructor(params: Expression[], options?: {}) {\n    super('snippet', params, 'snippet', options);\n  }\n}\n\n/**\n * Creates an aggregation that counts the number of stage inputs where the provided\n * boolean expression evaluates to true.\n *\n * @example\n * ```typescript\n * // Count the number of documents where 'is_active' field equals true\n * countIf(field(\"is_active\").equal(true)).as(\"numActiveDocuments\");\n * ```\n *\n * @param booleanExpr - The boolean expression to evaluate on each input.\n * @returns A new `AggregateFunction` representing the 'countIf' aggregation.\n */\nexport function countIf(booleanExpr: BooleanExpression): AggregateFunction {\n  return booleanExpr.countIf();\n}\n\n/**\n * Creates an expression that indexes into an array from the beginning or end\n * and return the element. If the offset exceeds the array length, an error is\n * returned. A negative offset, starts from the end.\n *\n * @example\n * ```typescript\n * // Return the value in the tags field array at index 1.\n * arrayGet('tags', 1);\n * ```\n *\n * @param arrayField - The name of the array field.\n * @param offset - The index of the element to return.\n * @returns A new `Expression` representing the 'arrayGet' operation.\n */\nexport function arrayGet(\n  arrayField: string,\n  offset: number\n): FunctionExpression;\n\n/**\n * Creates an expression that indexes into an array from the beginning or end\n * and return the element. If the offset exceeds the array length, an error is\n * returned. A negative offset, starts from the end.\n *\n * @example\n * ```typescript\n * // Return the value in the tags field array at index specified by field\n * // 'favoriteTag'.\n * arrayGet('tags', field('favoriteTag'));\n * ```\n *\n * @param arrayField - The name of the array field.\n * @param offsetExpr - An `Expression` evaluating to the index of the element to return.\n * @returns A new `Expression` representing the 'arrayGet' operation.\n */\nexport function arrayGet(\n  arrayField: string,\n  offsetExpr: Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that indexes into an array from the beginning or end\n * and return the element. If the offset exceeds the array length, an error is\n * returned. A negative offset, starts from the end.\n *\n * @example\n * ```typescript\n * // Return the value in the tags field array at index 1.\n * arrayGet(field('tags'), 1);\n * ```\n *\n * @param arrayExpression - An `Expression` evaluating to an array.\n * @param offset - The index of the element to return.\n * @returns A new `Expression` representing the 'arrayGet' operation.\n */\nexport function arrayGet(\n  arrayExpression: Expression,\n  offset: number\n): FunctionExpression;\n\n/**\n * Creates an expression that indexes into an array from the beginning or end\n * and return the element. If the offset exceeds the array length, an error is\n * returned. A negative offset, starts from the end.\n *\n * @example\n * ```typescript\n * // Return the value in the tags field array at index specified by field\n * // 'favoriteTag'.\n * arrayGet(field('tags'), field('favoriteTag'));\n * ```\n *\n * @param arrayExpression - An `Expression` evaluating to an array.\n * @param offsetExpr - An `Expression` evaluating to the index of the element to return.\n * @returns A new `Expression` representing the 'arrayGet' operation.\n */\nexport function arrayGet(\n  arrayExpression: Expression,\n  offsetExpr: Expression\n): FunctionExpression;\nexport function arrayGet(\n  array: Expression | string,\n  offset: Expression | number\n): FunctionExpression {\n  return fieldOrExpression(array).arrayGet(valueToDefaultExpr(offset));\n}\n\n/**\n *\n * Creates an expression that checks if a given expression produces an error.\n *\n * @example\n * ```typescript\n * // Check if the result of a calculation is an error\n * isError(field(\"title\").arrayContains(1));\n * ```\n *\n * @param value - The expression to check.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'isError' check.\n */\nexport function isError(value: Expression): BooleanExpression {\n  return value.isError().asBoolean();\n}\n\n/**\n *\n * Creates an expression that returns the `catch` argument if there is an\n * error, else return the result of the `try` argument evaluation.\n *\n * This overload is useful when a BooleanExpression is required.\n *\n * @example\n * ```typescript\n * // Create an expression that protects against a divide by zero error\n * // but always returns a boolean expression.\n * ifError(constant(50).divide(field('length')).greaterThan(1), constant(false));\n * ```\n *\n * @param tryExpr - The try expression.\n * @param catchExpr - The catch expression that will be evaluated and\n * returned if the tryExpr produces an error.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n */\nexport function ifError(\n  tryExpr: BooleanExpression,\n  catchExpr: BooleanExpression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that returns the `catch` argument if there is an\n * error, else return the result of the `try` argument evaluation.\n *\n * @example\n * ```typescript\n * // Returns the first item in the title field arrays, or returns\n * // the entire title field if the array is empty or the field is another type.\n * ifError(field(\"title\").arrayGet(0), field(\"title\"));\n * ```\n *\n * @param tryExpr - The try expression.\n * @param catchExpr - The catch expression that will be evaluated and\n * returned if the tryExpr produces an error.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n */\nexport function ifError(\n  tryExpr: Expression,\n  catchExpr: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the `catch` argument if there is an\n * error, else return the result of the `try` argument evaluation.\n *\n * @example\n * ```typescript\n * // Returns the first item in the title field arrays, or returns\n * // \"Default Title\"\n * ifError(field(\"title\").arrayGet(0), \"Default Title\");\n * ```\n *\n * @param tryExpr - The try expression.\n * @param catchValue - The value that will be returned if the tryExpr produces an\n * error.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n */\nexport function ifError(\n  tryExpr: Expression,\n  catchValue: unknown\n): FunctionExpression;\n\nexport function ifError(\n  tryExpr: Expression,\n  catchValue: unknown\n): FunctionExpression | BooleanExpression {\n  if (\n    tryExpr instanceof BooleanExpression &&\n    catchValue instanceof BooleanExpression\n  ) {\n    return tryExpr.ifError(catchValue).asBoolean();\n  } else {\n    return tryExpr.ifError(valueToDefaultExpr(catchValue));\n  }\n}\n\n/**\n *\n * Creates an expression that returns `true` if a value is absent. Otherwise,\n * returns `false` even if the value is `null`.\n *\n * @example\n * ```typescript\n * // Check if the field `value` is absent.\n * isAbsent(field(\"value\"));\n * ```\n *\n * @param value - The expression to check.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'isAbsent' check.\n */\nexport function isAbsent(value: Expression): BooleanExpression;\n\n/**\n *\n * Creates an expression that returns `true` if a field is absent. Otherwise,\n * returns `false` even if the field value is `null`.\n *\n * @example\n * ```typescript\n * // Check if the field `value` is absent.\n * isAbsent(\"value\");\n * ```\n *\n * @param field - The field to check.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'isAbsent' check.\n */\nexport function isAbsent(field: string): BooleanExpression;\nexport function isAbsent(value: Expression | string): BooleanExpression {\n  return fieldOrExpression(value).isAbsent();\n}\n\n/**\n *\n * Creates an expression that removes a key from the map at the specified field name.\n *\n * @example\n * ```typescript\n * // Removes the key 'city' field from the map in the address field of the input document.\n * mapRemove('address', 'city');\n * ```\n *\n * @param mapField - The name of a field containing a map value.\n * @param key - The name of the key to remove from the input map.\n */\nexport function mapRemove(mapField: string, key: string): FunctionExpression;\n/**\n *\n * Creates an expression that removes a key from the map produced by evaluating an expression.\n *\n * @example\n * ```typescript\n * // Removes the key 'baz' from the input map.\n * mapRemove(map({foo: 'bar', baz: true}), 'baz');\n * ```\n *\n * @param mapExpr - An expression return a map value.\n * @param key - The name of the key to remove from the input map.\n */\nexport function mapRemove(mapExpr: Expression, key: string): FunctionExpression;\n/**\n *\n * Creates an expression that removes a key from the map at the specified field name.\n *\n * @example\n * ```typescript\n * // Removes the key 'city' field from the map in the address field of the input document.\n * mapRemove('address', constant('city'));\n * ```\n *\n * @param mapField - The name of a field containing a map value.\n * @param keyExpr - An expression that produces the name of the key to remove from the input map.\n */\nexport function mapRemove(\n  mapField: string,\n  keyExpr: Expression\n): FunctionExpression;\n/**\n *\n * Creates an expression that removes a key from the map produced by evaluating an expression.\n *\n * @example\n * ```typescript\n * // Removes the key 'baz' from the input map.\n * mapRemove(map({foo: 'bar', baz: true}), constant('baz'));\n * ```\n *\n * @param mapExpr - An expression return a map value.\n * @param keyExpr - An expression that produces the name of the key to remove from the input map.\n */\nexport function mapRemove(\n  mapExpr: Expression,\n  keyExpr: Expression\n): FunctionExpression;\n\nexport function mapRemove(\n  mapExpr: Expression | string,\n  stringExpr: Expression | string\n): FunctionExpression {\n  return fieldOrExpression(mapExpr).mapRemove(valueToDefaultExpr(stringExpr));\n}\n\n/**\n *\n * Creates an expression that merges multiple map values.\n *\n * @example\n * ```typescript\n * // Merges the map in the settings field with, a map literal, and a map in\n * // that is conditionally returned by another expression\n * mapMerge('settings', { enabled: true }, conditional(field('isAdmin'), { admin: true}, {})\n * ```\n *\n * @param mapField - Name of a field containing a map value that will be merged.\n * @param secondMap - A required second map to merge. Represented as a literal or\n * an expression that returns a map.\n * @param otherMaps - Optional additional maps to merge. Each map is represented\n * as a literal or an expression that returns a map.\n */\nexport function mapMerge(\n  mapField: string,\n  secondMap: Record<string, unknown> | Expression,\n  ...otherMaps: Array<Record<string, unknown> | Expression>\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that merges multiple map values.\n *\n * @example\n * ```typescript\n * // Merges the map in the settings field with, a map literal, and a map in\n * // that is conditionally returned by another expression\n * mapMerge(field('settings'), { enabled: true }, conditional(field('isAdmin'), { admin: true}, {})\n * ```\n *\n * @param firstMap - An expression or literal map value that will be merged.\n * @param secondMap - A required second map to merge. Represented as a literal or\n * an expression that returns a map.\n * @param otherMaps - Optional additional maps to merge. Each map is represented\n * as a literal or an expression that returns a map.\n */\nexport function mapMerge(\n  firstMap: Record<string, unknown> | Expression,\n  secondMap: Record<string, unknown> | Expression,\n  ...otherMaps: Array<Record<string, unknown> | Expression>\n): FunctionExpression;\n\nexport function mapMerge(\n  firstMap: string | Record<string, unknown> | Expression,\n  secondMap: Record<string, unknown> | Expression,\n  ...otherMaps: Array<Record<string, unknown> | Expression>\n): FunctionExpression {\n  const secondMapExpr = valueToDefaultExpr(secondMap);\n  const otherMapExprs = otherMaps.map(valueToDefaultExpr);\n  return fieldOrExpression(firstMap).mapMerge(secondMapExpr, ...otherMapExprs);\n}\n\n/**\n *\n * Creates an expression that returns the document ID from a path.\n *\n * @example\n * ```typescript\n * // Get the document ID from a path.\n * documentId(myDocumentReference);\n * ```\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the documentId operation.\n */\nexport function documentId(\n  documentPath: string | DocumentReference\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the document ID from a path.\n *\n * @example\n * ```typescript\n * // Get the document ID from a path.\n * documentId(field(\"__path__\"));\n * ```\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the documentId operation.\n */\nexport function documentId(documentPathExpr: Expression): FunctionExpression;\n\nexport function documentId(\n  documentPath: Expression | string | DocumentReference\n): FunctionExpression {\n  // @ts-ignore\n  const documentPathExpr = valueToDefaultExpr(documentPath);\n  return documentPathExpr.documentId();\n}\n\n/**\n *\n * Creates an expression that returns the parent document reference of a document reference.\n *\n * @example\n * ```typescript\n * // Get the parent document reference of a document reference.\n * parent(myDocumentReference);\n * ```\n *\n * @param documentPath - A string path or DocumentReference to get the parent from.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the parent operation.\n */\nexport function parent(\n  documentPath: string | DocumentReference\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the parent document reference of a document reference.\n *\n * @example\n * ```typescript\n * // Get the parent document reference of a document reference.\n * parent(field(\"__path__\"));\n * ```\n *\n * @param documentPathExpr - An Expression evaluating to a document reference.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the parent operation.\n */\nexport function parent(documentPathExpr: Expression): FunctionExpression;\n\nexport function parent(\n  documentPath: Expression | string | DocumentReference\n): FunctionExpression {\n  const documentPathExpr = valueToDefaultExpr(documentPath);\n  return documentPathExpr.parent();\n}\n\n/**\n *\n * Creates an expression that returns a substring of a string or byte array.\n *\n * @param field - The name of a field containing a string or byte array to compute the substring from.\n * @param position - Index of the first character of the substring.\n * @param length - Length of the substring.\n */\nexport function substring(\n  field: string,\n  position: number,\n  length?: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns a substring of a string or byte array.\n *\n * @param input - An expression returning a string or byte array to compute the substring from.\n * @param position - Index of the first character of the substring.\n * @param length - Length of the substring.\n */\nexport function substring(\n  input: Expression,\n  position: number,\n  length?: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns a substring of a string or byte array.\n *\n * @param field - The name of a field containing a string or byte array to compute the substring from.\n * @param position - An expression that returns the index of the first character of the substring.\n * @param length - An expression that returns the length of the substring.\n */\nexport function substring(\n  field: string,\n  position: Expression,\n  length?: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns a substring of a string or byte array.\n *\n * @param input - An expression returning a string or byte array to compute the substring from.\n * @param position - An expression that returns the index of the first character of the substring.\n * @param length - An expression that returns the length of the substring.\n */\nexport function substring(\n  input: Expression,\n  position: Expression,\n  length?: Expression\n): FunctionExpression;\n\nexport function substring(\n  field: Expression | string,\n  position: Expression | number,\n  length?: Expression | number\n): FunctionExpression {\n  const fieldExpr = fieldOrExpression(field);\n  const positionExpr = valueToDefaultExpr(position);\n  const lengthExpr =\n    length === undefined ? undefined : valueToDefaultExpr(length);\n  return fieldExpr.substring(positionExpr, lengthExpr);\n}\n\n/**\n *\n * Creates an expression that adds two expressions together.\n *\n * @example\n * ```typescript\n * // Add the value of the 'quantity' field and the 'reserve' field.\n * add(field(\"quantity\"), field(\"reserve\"));\n * ```\n *\n * @param first - The first expression to add.\n * @param second - The second expression or literal to add.\n * @param others - Optional other expressions or literals to add.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the addition operation.\n */\nexport function add(\n  first: Expression,\n  second: Expression | unknown\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that adds a field's value to an expression.\n *\n * @example\n * ```typescript\n * // Add the value of the 'quantity' field and the 'reserve' field.\n * add(\"quantity\", field(\"reserve\"));\n * ```\n *\n * @param fieldName - The name of the field containing the value to add.\n * @param second - The second expression or literal to add.\n * @param others - Optional other expressions or literals to add.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the addition operation.\n */\nexport function add(\n  fieldName: string,\n  second: Expression | unknown\n): FunctionExpression;\n\nexport function add(\n  first: Expression | string,\n  second: Expression | unknown\n): FunctionExpression {\n  return fieldOrExpression(first).add(valueToDefaultExpr(second));\n}\n\n/**\n *\n * Creates an expression that subtracts two expressions.\n *\n * @example\n * ```typescript\n * // Subtract the 'discount' field from the 'price' field\n * subtract(field(\"price\"), field(\"discount\"));\n * ```\n *\n * @param left - The expression to subtract from.\n * @param right - The expression to subtract.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the subtraction operation.\n */\nexport function subtract(\n  left: Expression,\n  right: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that subtracts a constant value from an expression.\n *\n * @example\n * ```typescript\n * // Subtract the constant value 2 from the 'value' field\n * subtract(field(\"value\"), 2);\n * ```\n *\n * @param expression - The expression to subtract from.\n * @param value - The constant value to subtract.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the subtraction operation.\n */\nexport function subtract(\n  expression: Expression,\n  value: unknown\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that subtracts an expression from a field's value.\n *\n * @example\n * ```typescript\n * // Subtract the 'discount' field from the 'price' field\n * subtract(\"price\", field(\"discount\"));\n * ```\n *\n * @param fieldName - The field name to subtract from.\n * @param expression - The expression to subtract.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the subtraction operation.\n */\nexport function subtract(\n  fieldName: string,\n  expression: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that subtracts a constant value from a field's value.\n *\n * @example\n * ```typescript\n * // Subtract 20 from the value of the 'total' field\n * subtract(\"total\", 20);\n * ```\n *\n * @param fieldName - The field name to subtract from.\n * @param value - The constant value to subtract.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the subtraction operation.\n */\nexport function subtract(fieldName: string, value: unknown): FunctionExpression;\nexport function subtract(\n  left: Expression | string,\n  right: Expression | unknown\n): FunctionExpression {\n  const normalizedLeft = typeof left === 'string' ? field(left) : left;\n  const normalizedRight = valueToDefaultExpr(right);\n  return normalizedLeft.subtract(normalizedRight);\n}\n\n/**\n *\n * Creates an expression that multiplies two expressions together.\n *\n * @example\n * ```typescript\n * // Multiply the 'quantity' field by the 'price' field\n * multiply(field(\"quantity\"), field(\"price\"));\n * ```\n *\n * @param first - The first expression to multiply.\n * @param second - The second expression or literal to multiply.\n * @param others - Optional additional expressions or literals to multiply.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the multiplication operation.\n */\nexport function multiply(\n  first: Expression,\n  second: Expression | unknown\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that multiplies a field's value by an expression.\n *\n * @example\n * ```typescript\n * // Multiply the 'quantity' field by the 'price' field\n * multiply(\"quantity\", field(\"price\"));\n * ```\n *\n * @param fieldName - The name of the field containing the value to add.\n * @param second - The second expression or literal to add.\n * @param others - Optional other expressions or literals to add.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the multiplication operation.\n */\nexport function multiply(\n  fieldName: string,\n  second: Expression | unknown\n): FunctionExpression;\n\nexport function multiply(\n  first: Expression | string,\n  second: Expression | unknown\n): FunctionExpression {\n  return fieldOrExpression(first).multiply(valueToDefaultExpr(second));\n}\n\n/**\n *\n * Creates an expression that divides two expressions.\n *\n * @example\n * ```typescript\n * // Divide the 'total' field by the 'count' field\n * divide(field(\"total\"), field(\"count\"));\n * ```\n *\n * @param left - The expression to be divided.\n * @param right - The expression to divide by.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the division operation.\n */\nexport function divide(left: Expression, right: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that divides an expression by a constant value.\n *\n * @example\n * ```typescript\n * // Divide the 'value' field by 10\n * divide(field(\"value\"), 10);\n * ```\n *\n * @param expression - The expression to be divided.\n * @param value - The constant value to divide by.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the division operation.\n */\nexport function divide(\n  expression: Expression,\n  value: unknown\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that divides a field's value by an expression.\n *\n * @example\n * ```typescript\n * // Divide the 'total' field by the 'count' field\n * divide(\"total\", field(\"count\"));\n * ```\n *\n * @param fieldName - The field name to be divided.\n * @param expressions - The expression to divide by.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the division operation.\n */\nexport function divide(\n  fieldName: string,\n  expressions: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that divides a field's value by a constant value.\n *\n * @example\n * ```typescript\n * // Divide the 'value' field by 10\n * divide(\"value\", 10);\n * ```\n *\n * @param fieldName - The field name to be divided.\n * @param value - The constant value to divide by.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the division operation.\n */\nexport function divide(fieldName: string, value: unknown): FunctionExpression;\nexport function divide(\n  left: Expression | string,\n  right: Expression | unknown\n): FunctionExpression {\n  const normalizedLeft = typeof left === 'string' ? field(left) : left;\n  const normalizedRight = valueToDefaultExpr(right);\n  return normalizedLeft.divide(normalizedRight);\n}\n\n/**\n *\n * Creates an expression that calculates the modulo (remainder) of dividing two expressions.\n *\n * @example\n * ```typescript\n * // Calculate the remainder of dividing 'field1' by 'field2'.\n * mod(field(\"field1\"), field(\"field2\"));\n * ```\n *\n * @param left - The dividend expression.\n * @param right - The divisor expression.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the modulo operation.\n */\nexport function mod(left: Expression, right: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that calculates the modulo (remainder) of dividing an expression by a constant.\n *\n * @example\n * ```typescript\n * // Calculate the remainder of dividing 'field1' by 5.\n * mod(field(\"field1\"), 5);\n * ```\n *\n * @param expression - The dividend expression.\n * @param value - The divisor constant.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the modulo operation.\n */\nexport function mod(expression: Expression, value: unknown): FunctionExpression;\n\n/**\n *\n * Creates an expression that calculates the modulo (remainder) of dividing a field's value by an expression.\n *\n * @example\n * ```typescript\n * // Calculate the remainder of dividing 'field1' by 'field2'.\n * mod(\"field1\", field(\"field2\"));\n * ```\n *\n * @param fieldName - The dividend field name.\n * @param expression - The divisor expression.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the modulo operation.\n */\nexport function mod(\n  fieldName: string,\n  expression: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that calculates the modulo (remainder) of dividing a field's value by a constant.\n *\n * @example\n * ```typescript\n * // Calculate the remainder of dividing 'field1' by 5.\n * mod(\"field1\", 5);\n * ```\n *\n * @param fieldName - The dividend field name.\n * @param value - The divisor constant.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the modulo operation.\n */\nexport function mod(fieldName: string, value: unknown): FunctionExpression;\nexport function mod(\n  left: Expression | string,\n  right: Expression | unknown\n): FunctionExpression {\n  const normalizedLeft = typeof left === 'string' ? field(left) : left;\n  const normalizedRight = valueToDefaultExpr(right);\n  return normalizedLeft.mod(normalizedRight);\n}\n\n/**\n *\n * Creates an expression that creates a Firestore map value from an input object.\n *\n * @example\n * ```typescript\n * // Create a map from the input object and reference the 'baz' field value from the input document.\n * map({foo: 'bar', baz: field('baz')}).as('data');\n * ```\n *\n * @param elements - The input map to evaluate in the expression.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the map function.\n */\nexport function map(elements: Record<string, unknown>): FunctionExpression {\n  return _map(elements, 'map');\n}\nexport function _map(\n  elements: Record<string, unknown>,\n  methodName: string | undefined\n): FunctionExpression {\n  const result: Expression[] = [];\n  for (const key in elements) {\n    if (Object.prototype.hasOwnProperty.call(elements, key)) {\n      const value = elements[key];\n      result.push(constant(key));\n      result.push(valueToDefaultExpr(value));\n    }\n  }\n  return new FunctionExpression('map', result, 'map');\n}\n\n/**\n * Internal use only\n * Converts a plainObject to a mapValue in the proto representation,\n * rather than a functionValue+map that is the result of the map(...) function.\n * This behaves different from constant(plainObject) because it\n * traverses the input object, converts values in the object to expressions,\n * and calls _readUserData on each of these expressions.\n * @private\n * @internal\n * @param plainObject\n */\nexport function _mapValue(plainObject: Record<string, unknown>): MapValue {\n  const result: Map<string, Expression> = new Map<string, Expression>();\n  for (const key in plainObject) {\n    if (Object.prototype.hasOwnProperty.call(plainObject, key)) {\n      const value = plainObject[key];\n      result.set(key, valueToDefaultExpr(value));\n    }\n  }\n  return new MapValue(result, undefined);\n}\n\n/**\n *\n * Creates an expression that creates a Firestore array value from an input array.\n *\n * @example\n * ```typescript\n * // Create an array value from the input array and reference the 'baz' field value from the input document.\n * array(['bar', field('baz')]).as('foo');\n * ```\n *\n * @param elements - The input array to evaluate in the expression.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the array function.\n */\nexport function array(elements: unknown[]): FunctionExpression {\n  return _array(elements, 'array');\n}\nexport function _array(\n  elements: unknown[],\n  methodName: string | undefined\n): FunctionExpression {\n  return new FunctionExpression(\n    'array',\n    elements.map(element => valueToDefaultExpr(element)),\n    methodName\n  );\n}\n\n/**\n *\n * Creates an expression that checks if two expressions are equal.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is equal to an expression\n * equal(field(\"age\"), field(\"minAge\").add(10));\n * ```\n *\n * @param left - The first expression to compare.\n * @param right - The second expression to compare.\n * @returns A new `Expression` representing the equality comparison.\n */\nexport function equal(left: Expression, right: Expression): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is equal to a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is equal to 21\n * equal(field(\"age\"), 21);\n * ```\n *\n * @param expression - The expression to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the equality comparison.\n */\nexport function equal(\n  expression: Expression,\n  value: unknown\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is equal to an expression.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is equal to the 'limit' field\n * equal(\"age\", field(\"limit\"));\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param expression - The expression to compare to.\n * @returns A new `Expression` representing the equality comparison.\n */\nexport function equal(\n  fieldName: string,\n  expression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is equal to a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'city' field is equal to string constant \"London\"\n * equal(\"city\", \"London\");\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the equality comparison.\n */\nexport function equal(fieldName: string, value: unknown): BooleanExpression;\nexport function equal(\n  left: Expression | string,\n  right: unknown\n): BooleanExpression {\n  const leftExpr = left instanceof Expression ? left : field(left);\n  const rightExpr = valueToDefaultExpr(right);\n  return leftExpr.equal(rightExpr);\n}\n\n/**\n *\n * Creates an expression that checks if two expressions are not equal.\n *\n * @example\n * ```typescript\n * // Check if the 'status' field is not equal to field 'finalState'\n * notEqual(field(\"status\"), field(\"finalState\"));\n * ```\n *\n * @param left - The first expression to compare.\n * @param right - The second expression to compare.\n * @returns A new `Expression` representing the inequality comparison.\n */\nexport function notEqual(\n  left: Expression,\n  right: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is not equal to a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'status' field is not equal to \"completed\"\n * notEqual(field(\"status\"), \"completed\");\n * ```\n *\n * @param expression - The expression to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the inequality comparison.\n */\nexport function notEqual(\n  expression: Expression,\n  value: unknown\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is not equal to an expression.\n *\n * @example\n * ```typescript\n * // Check if the 'status' field is not equal to the value of 'expectedStatus'\n * notEqual(\"status\", field(\"expectedStatus\"));\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param expression - The expression to compare to.\n * @returns A new `Expression` representing the inequality comparison.\n */\nexport function notEqual(\n  fieldName: string,\n  expression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is not equal to a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'country' field is not equal to \"USA\"\n * notEqual(\"country\", \"USA\");\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the inequality comparison.\n */\nexport function notEqual(fieldName: string, value: unknown): BooleanExpression;\nexport function notEqual(\n  left: Expression | string,\n  right: unknown\n): BooleanExpression {\n  const leftExpr = left instanceof Expression ? left : field(left);\n  const rightExpr = valueToDefaultExpr(right);\n  return leftExpr.notEqual(rightExpr);\n}\n\n/**\n *\n * Creates an expression that checks if the first expression is less than the second expression.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is less than 30\n * lessThan(field(\"age\"), field(\"limit\"));\n * ```\n *\n * @param left - The first expression to compare.\n * @param right - The second expression to compare.\n * @returns A new `Expression` representing the less than comparison.\n */\nexport function lessThan(\n  left: Expression,\n  right: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is less than a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is less than 30\n * lessThan(field(\"age\"), 30);\n * ```\n *\n * @param expression - The expression to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the less than comparison.\n */\nexport function lessThan(\n  expression: Expression,\n  value: unknown\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is less than an expression.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is less than the 'limit' field\n * lessThan(\"age\", field(\"limit\"));\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param expression - The expression to compare to.\n * @returns A new `Expression` representing the less than comparison.\n */\nexport function lessThan(\n  fieldName: string,\n  expression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is less than a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'price' field is less than 50\n * lessThan(\"price\", 50);\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the less than comparison.\n */\nexport function lessThan(fieldName: string, value: unknown): BooleanExpression;\nexport function lessThan(\n  left: Expression | string,\n  right: unknown\n): BooleanExpression {\n  const leftExpr = left instanceof Expression ? left : field(left);\n  const rightExpr = valueToDefaultExpr(right);\n  return leftExpr.lessThan(rightExpr);\n}\n\n/**\n *\n * Creates an expression that checks if the first expression is less than or equal to the second\n * expression.\n *\n * @example\n * ```typescript\n * // Check if the 'quantity' field is less than or equal to 20\n * lessThan(field(\"quantity\"), field(\"limit\"));\n * ```\n *\n * @param left - The first expression to compare.\n * @param right - The second expression to compare.\n * @returns A new `Expression` representing the less than or equal to comparison.\n */\nexport function lessThanOrEqual(\n  left: Expression,\n  right: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is less than or equal to a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'quantity' field is less than or equal to 20\n * lessThan(field(\"quantity\"), 20);\n * ```\n *\n * @param expression - The expression to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the less than or equal to comparison.\n */\nexport function lessThanOrEqual(\n  expression: Expression,\n  value: unknown\n): BooleanExpression;\n\n/**\n * Creates an expression that checks if a field's value is less than or equal to an expression.\n *\n * @example\n * ```typescript\n * // Check if the 'quantity' field is less than or equal to the 'limit' field\n * lessThan(\"quantity\", field(\"limit\"));\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param expression - The expression to compare to.\n * @returns A new `Expression` representing the less than or equal to comparison.\n */\nexport function lessThanOrEqual(\n  fieldName: string,\n  expression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is less than or equal to a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'score' field is less than or equal to 70\n * lessThan(\"score\", 70);\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the less than or equal to comparison.\n */\nexport function lessThanOrEqual(\n  fieldName: string,\n  value: unknown\n): BooleanExpression;\nexport function lessThanOrEqual(\n  left: Expression | string,\n  right: unknown\n): BooleanExpression {\n  const leftExpr = left instanceof Expression ? left : field(left);\n  const rightExpr = valueToDefaultExpr(right);\n  return leftExpr.lessThanOrEqual(rightExpr);\n}\n\n/**\n *\n * Creates an expression that checks if the first expression is greater than the second\n * expression.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is greater than 18\n * greaterThan(field(\"age\"), constant(9).add(9));\n * ```\n *\n * @param left - The first expression to compare.\n * @param right - The second expression to compare.\n * @returns A new `Expression` representing the greater than comparison.\n */\nexport function greaterThan(\n  left: Expression,\n  right: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is greater than a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is greater than 18\n * greaterThan(field(\"age\"), 18);\n * ```\n *\n * @param expression - The expression to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the greater than comparison.\n */\nexport function greaterThan(\n  expression: Expression,\n  value: unknown\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is greater than an expression.\n *\n * @example\n * ```typescript\n * // Check if the value of field 'age' is greater than the value of field 'limit'\n * greaterThan(\"age\", field(\"limit\"));\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param expression - The expression to compare to.\n * @returns A new `Expression` representing the greater than comparison.\n */\nexport function greaterThan(\n  fieldName: string,\n  expression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is greater than a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'price' field is greater than 100\n * greaterThan(\"price\", 100);\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the greater than comparison.\n */\nexport function greaterThan(\n  fieldName: string,\n  value: unknown\n): BooleanExpression;\nexport function greaterThan(\n  left: Expression | string,\n  right: unknown\n): BooleanExpression {\n  const leftExpr = left instanceof Expression ? left : field(left);\n  const rightExpr = valueToDefaultExpr(right);\n  return leftExpr.greaterThan(rightExpr);\n}\n\n/**\n *\n * Creates an expression that checks if the first expression is greater than or equal to the\n * second expression.\n *\n * @example\n * ```typescript\n * // Check if the 'quantity' field is greater than or equal to the field \"threshold\"\n * greaterThanOrEqual(field(\"quantity\"), field(\"threshold\"));\n * ```\n *\n * @param left - The first expression to compare.\n * @param right - The second expression to compare.\n * @returns A new `Expression` representing the greater than or equal to comparison.\n */\nexport function greaterThanOrEqual(\n  left: Expression,\n  right: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is greater than or equal to a constant\n * value.\n *\n * @example\n * ```typescript\n * // Check if the 'quantity' field is greater than or equal to 10\n * greaterThanOrEqual(field(\"quantity\"), 10);\n * ```\n *\n * @param expression - The expression to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the greater than or equal to comparison.\n */\nexport function greaterThanOrEqual(\n  expression: Expression,\n  value: unknown\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is greater than or equal to an expression.\n *\n * @example\n * ```typescript\n * // Check if the value of field 'age' is greater than or equal to the value of field 'limit'\n * greaterThanOrEqual(\"age\", field(\"limit\"));\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param value - The expression to compare to.\n * @returns A new `Expression` representing the greater than or equal to comparison.\n */\nexport function greaterThanOrEqual(\n  fieldName: string,\n  value: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is greater than or equal to a constant\n * value.\n *\n * @example\n * ```typescript\n * // Check if the 'score' field is greater than or equal to 80\n * greaterThanOrEqual(\"score\", 80);\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the greater than or equal to comparison.\n */\nexport function greaterThanOrEqual(\n  fieldName: string,\n  value: unknown\n): BooleanExpression;\nexport function greaterThanOrEqual(\n  left: Expression | string,\n  right: unknown\n): BooleanExpression {\n  const leftExpr = left instanceof Expression ? left : field(left);\n  const rightExpr = valueToDefaultExpr(right);\n  return leftExpr.greaterThanOrEqual(rightExpr);\n}\n\n/**\n *\n * Creates an expression that concatenates an array expression with other arrays.\n *\n * @example\n * ```typescript\n * // Combine the 'items' array with two new item arrays\n * arrayConcat(field(\"items\"), [field(\"newItems\"), field(\"otherItems\")]);\n * ```\n *\n * @param firstArray - The first array expression to concatenate to.\n * @param secondArray - The second array expression or array literal to concatenate to.\n * @param otherArrays - Optional additional array expressions or array literals to concatenate.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the concatenated array.\n */\nexport function arrayConcat(\n  firstArray: Expression,\n  secondArray: Expression | unknown[],\n  ...otherArrays: Array<Expression | unknown[]>\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that concatenates a field's array value with other arrays.\n *\n * @example\n * ```typescript\n * // Combine the 'items' array with two new item arrays\n * arrayConcat(\"items\", [field(\"newItems\"), field(\"otherItems\")]);\n * ```\n *\n * @param firstArrayField - The first array to concatenate to.\n * @param secondArray - The second array expression or array literal to concatenate to.\n * @param otherArrays - Optional additional array expressions or array literals to concatenate.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the concatenated array.\n */\nexport function arrayConcat(\n  firstArrayField: string,\n  secondArray: Expression | unknown[],\n  ...otherArrays: Array<Expression | unknown[]>\n): FunctionExpression;\n\nexport function arrayConcat(\n  firstArray: Expression | string,\n  secondArray: Expression | unknown[],\n  ...otherArrays: Array<Expression | unknown[]>\n): FunctionExpression {\n  const exprValues = otherArrays.map(element => valueToDefaultExpr(element));\n  return fieldOrExpression(firstArray).arrayConcat(\n    fieldOrExpression(secondArray),\n    ...exprValues\n  );\n}\n\n/**\n *\n * Creates an expression that checks if an array expression contains a specific element.\n *\n * @example\n * ```typescript\n * // Check if the 'colors' array contains the value of field 'selectedColor'\n * arrayContains(field(\"colors\"), field(\"selectedColor\"));\n * ```\n *\n * @param array - The array expression to check.\n * @param element - The element to search for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains' comparison.\n */\nexport function arrayContains(\n  array: Expression,\n  element: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an array expression contains a specific element.\n *\n * @example\n * ```typescript\n * // Check if the 'colors' array contains \"red\"\n * arrayContains(field(\"colors\"), \"red\");\n * ```\n *\n * @param array - The array expression to check.\n * @param element - The element to search for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains' comparison.\n */\nexport function arrayContains(\n  array: Expression,\n  element: unknown\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's array value contains a specific element.\n *\n * @example\n * ```typescript\n * // Check if the 'colors' array contains the value of field 'selectedColor'\n * arrayContains(\"colors\", field(\"selectedColor\"));\n * ```\n *\n * @param fieldName - The field name to check.\n * @param element - The element to search for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains' comparison.\n */\nexport function arrayContains(\n  fieldName: string,\n  element: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's array value contains a specific value.\n *\n * @example\n * ```typescript\n * // Check if the 'colors' array contains \"red\"\n * arrayContains(\"colors\", \"red\");\n * ```\n *\n * @param fieldName - The field name to check.\n * @param element - The element to search for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains' comparison.\n */\nexport function arrayContains(\n  fieldName: string,\n  element: unknown\n): BooleanExpression;\nexport function arrayContains(\n  array: Expression | string,\n  element: unknown\n): BooleanExpression {\n  const arrayExpr = fieldOrExpression(array);\n  const elementExpr = valueToDefaultExpr(element);\n  return arrayExpr.arrayContains(elementExpr);\n}\n\n/**\n *\n * Creates an expression that checks if an array expression contains any of the specified\n * elements.\n *\n * @example\n * ```typescript\n * // Check if the 'categories' array contains either values from field \"cate1\" or \"Science\"\n * arrayContainsAny(field(\"categories\"), [field(\"cate1\"), \"Science\"]);\n * ```\n *\n * @param array - The array expression to check.\n * @param values - The elements to check for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_any' comparison.\n */\nexport function arrayContainsAny(\n  array: Expression,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's array value contains any of the specified\n * elements.\n *\n * @example\n * ```typescript\n * // Check if the 'groups' array contains either the value from the 'userGroup' field\n * // or the value \"guest\"\n * arrayContainsAny(\"categories\", [field(\"cate1\"), \"Science\"]);\n * ```\n *\n * @param fieldName - The field name to check.\n * @param values - The elements to check for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_any' comparison.\n */\nexport function arrayContainsAny(\n  fieldName: string,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an array expression contains any of the specified\n * elements.\n *\n * @example\n * ```typescript\n * // Check if the 'categories' array contains either values from field \"cate1\" or \"Science\"\n * arrayContainsAny(field(\"categories\"), array([field(\"cate1\"), \"Science\"]));\n * ```\n *\n * @param array - The array expression to check.\n * @param values - An expression that evaluates to an array, whose elements to check for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_any' comparison.\n */\nexport function arrayContainsAny(\n  array: Expression,\n  values: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's array value contains any of the specified\n * elements.\n *\n * @example\n * ```typescript\n * // Check if the 'groups' array contains either the value from the 'userGroup' field\n * // or the value \"guest\"\n * arrayContainsAny(\"categories\", array([field(\"cate1\"), \"Science\"]));\n * ```\n *\n * @param fieldName - The field name to check.\n * @param values - An expression that evaluates to an array, whose elements to check for in the array field.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_any' comparison.\n */\nexport function arrayContainsAny(\n  fieldName: string,\n  values: Expression\n): BooleanExpression;\nexport function arrayContainsAny(\n  array: Expression | string,\n  values: unknown[] | Expression\n): BooleanExpression {\n  // @ts-ignore implementation accepts both types\n  return fieldOrExpression(array).arrayContainsAny(values);\n}\n\n/**\n *\n * Creates an expression that checks if an array expression contains all the specified elements.\n *\n * @example\n * ```typescript\n * // Check if the \"tags\" array contains all of the values: \"SciFi\", \"Adventure\", and the value from field \"tag1\"\n * arrayContainsAll(field(\"tags\"), [field(\"tag1\"), constant(\"SciFi\"), \"Adventure\"]);\n * ```\n *\n * @param array - The array expression to check.\n * @param values - The elements to check for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_all' comparison.\n */\nexport function arrayContainsAll(\n  array: Expression,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's array value contains all the specified values or\n * expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'tags' array contains both of the values from field 'tag1', the value \"SciFi\", and \"Adventure\"\n * arrayContainsAll(\"tags\", [field(\"tag1\"), \"SciFi\", \"Adventure\"]);\n * ```\n *\n * @param fieldName - The field name to check.\n * @param values - The elements to check for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_all' comparison.\n */\nexport function arrayContainsAll(\n  fieldName: string,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an array expression contains all the specified elements.\n *\n * @example\n * ```typescript\n * // Check if the \"tags\" array contains all of the values: \"SciFi\", \"Adventure\", and the value from field \"tag1\"\n * arrayContainsAll(field(\"tags\"), [field(\"tag1\"), constant(\"SciFi\"), \"Adventure\"]);\n * ```\n *\n * @param array - The array expression to check.\n * @param arrayExpression - The elements to check for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_all' comparison.\n */\nexport function arrayContainsAll(\n  array: Expression,\n  arrayExpression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's array value contains all the specified values or\n * expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'tags' array contains both of the values from field 'tag1', the value \"SciFi\", and \"Adventure\"\n * arrayContainsAll(\"tags\", [field(\"tag1\"), \"SciFi\", \"Adventure\"]);\n * ```\n *\n * @param fieldName - The field name to check.\n * @param arrayExpression - The elements to check for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_all' comparison.\n */\nexport function arrayContainsAll(\n  fieldName: string,\n  arrayExpression: Expression\n): BooleanExpression;\nexport function arrayContainsAll(\n  array: Expression | string,\n  values: unknown[] | Expression\n): BooleanExpression {\n  // @ts-ignore implementation accepts both types\n  return fieldOrExpression(array).arrayContainsAll(values);\n}\n\n/**\n *\n * Creates an expression that calculates the length of an array in a specified field.\n *\n * @example\n * ```typescript\n * // Get the number of items in field 'cart'\n * arrayLength('cart');\n * ```\n *\n * @param fieldName - The name of the field containing an array to calculate the length of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the array.\n */\nexport function arrayLength(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that calculates the length of an array expression.\n *\n * @example\n * ```typescript\n * // Get the number of items in the 'cart' array\n * arrayLength(field(\"cart\"));\n * ```\n *\n * @param array - The array expression to calculate the length of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the array.\n */\nexport function arrayLength(array: Expression): FunctionExpression;\nexport function arrayLength(array: Expression | string): FunctionExpression {\n  return fieldOrExpression(array).arrayLength();\n}\n\n/**\n *\n * Creates an expression that checks if an expression, when evaluated, is equal to any of the provided values or\n * expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'category' field is either \"Electronics\" or value of field 'primaryType'\n * equalAny(field(\"category\"), [constant(\"Electronics\"), field(\"primaryType\")]);\n * ```\n *\n * @param expression - The expression whose results to compare.\n * @param values - The values to check against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'IN' comparison.\n */\nexport function equalAny(\n  expression: Expression,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is equal to any of the provided values.\n *\n * @example\n * ```typescript\n * // Check if the 'category' field is set to a value in the disabledCategories field\n * equalAny(field(\"category\"), field('disabledCategories'));\n * ```\n *\n * @param expression - The expression whose results to compare.\n * @param arrayExpression - An expression that evaluates to an array, whose elements to check for equality to the input.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'IN' comparison.\n */\nexport function equalAny(\n  expression: Expression,\n  arrayExpression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is equal to any of the provided values or\n * expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'category' field is either \"Electronics\" or value of field 'primaryType'\n * equalAny(\"category\", [constant(\"Electronics\"), field(\"primaryType\")]);\n * ```\n *\n * @param fieldName - The field to compare.\n * @param values - The values to check against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'IN' comparison.\n */\nexport function equalAny(\n  fieldName: string,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is equal to any of the provided values or\n * expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'category' field is either \"Electronics\" or value of field 'primaryType'\n * equalAny(\"category\", [\"Electronics\", field(\"primaryType\")]);\n * ```\n *\n * @param fieldName - The field to compare.\n * @param arrayExpression - An expression that evaluates to an array, whose elements to check for equality to the input field.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'IN' comparison.\n */\nexport function equalAny(\n  fieldName: string,\n  arrayExpression: Expression\n): BooleanExpression;\nexport function equalAny(\n  element: Expression | string,\n  values: unknown[] | Expression\n): BooleanExpression {\n  // @ts-ignore implementation accepts both types\n  return fieldOrExpression(element).equalAny(values);\n}\n\n/**\n *\n * Creates an expression that checks if an expression is not equal to any of the provided values\n * or expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'status' field is neither \"pending\" nor the value of 'rejectedStatus'\n * notEqualAny(field(\"status\"), [\"pending\", field(\"rejectedStatus\")]);\n * ```\n *\n * @param element - The expression to compare.\n * @param values - The values to check against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'NOT IN' comparison.\n */\nexport function notEqualAny(\n  element: Expression,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is not equal to any of the provided values\n * or expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'status' field is neither \"pending\" nor the value of 'rejectedStatus'\n * notEqualAny(\"status\", [constant(\"pending\"), field(\"rejectedStatus\")]);\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param values - The values to check against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'NOT IN' comparison.\n */\nexport function notEqualAny(\n  fieldName: string,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is not equal to any of the provided values\n * or expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'status' field is neither \"pending\" nor the value of the field 'rejectedStatus'\n * notEqualAny(field(\"status\"), [\"pending\", field(\"rejectedStatus\")]);\n * ```\n *\n * @param element - The expression to compare.\n * @param arrayExpression - The values to check against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'NOT IN' comparison.\n */\nexport function notEqualAny(\n  element: Expression,\n  arrayExpression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is not equal to any of the values in the evaluated expression.\n *\n * @example\n * ```typescript\n * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses'\n * notEqualAny(\"status\", field(\"rejectedStatuses\"));\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param arrayExpression - The values to check against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'NOT IN' comparison.\n */\nexport function notEqualAny(\n  fieldName: string,\n  arrayExpression: Expression\n): BooleanExpression;\n\nexport function notEqualAny(\n  element: Expression | string,\n  values: unknown[] | Expression\n): BooleanExpression {\n  // @ts-ignore implementation accepts both types\n  return fieldOrExpression(element).notEqualAny(values);\n}\n\n/**\n *\n * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple BooleanExpressions.\n *\n * @example\n * ```typescript\n * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is \"London\",\n * // or 'status' is \"active\".\n * const condition = xor(\n *     greaterThan(\"age\", 18),\n *     equal(\"city\", \"London\"),\n *     equal(\"status\", \"active\"));\n * ```\n *\n * @param first - The first condition.\n * @param second - The second condition.\n * @param additionalConditions - Additional conditions to 'XOR' together.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical 'XOR' operation.\n */\nexport function xor(\n  first: BooleanExpression,\n  second: BooleanExpression,\n  ...additionalConditions: BooleanExpression[]\n): BooleanExpression {\n  return new FunctionExpression(\n    'xor',\n    [first, second, ...additionalConditions],\n    'xor'\n  ).asBoolean();\n}\n\n/**\n *\n * Creates a conditional expression that evaluates to a 'then' expression if a condition is true\n * and an 'else' expression if the condition is false.\n *\n * @example\n * ```typescript\n * // If 'age' is greater than 18, return \"Adult\"; otherwise, return \"Minor\".\n * conditional(\n *     greaterThan(\"age\", 18), constant(\"Adult\"), constant(\"Minor\"));\n * ```\n *\n * @param condition - The condition to evaluate.\n * @param thenExpr - The expression to evaluate if the condition is true.\n * @param elseExpr - The expression to evaluate if the condition is false.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the conditional expression.\n */\nexport function conditional(\n  condition: BooleanExpression,\n  thenExpr: Expression,\n  elseExpr: Expression\n): FunctionExpression {\n  return new FunctionExpression(\n    'conditional',\n    [condition, thenExpr, elseExpr],\n    'conditional'\n  );\n}\n\n/**\n *\n * Creates an expression that negates a filter condition.\n *\n * @example\n * ```typescript\n * // Find documents where the 'completed' field is NOT true\n * not(equal(\"completed\", true));\n * ```\n *\n * @param booleanExpr - The filter condition to negate.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the negated filter condition.\n */\nexport function not(booleanExpr: BooleanExpression): BooleanExpression {\n  return booleanExpr.not();\n}\n\n/**\n *\n * Creates an expression that returns the largest value between multiple input\n * expressions or literal values. Based on Firestore's value type ordering.\n *\n * @example\n * ```typescript\n * // Returns the largest value between the 'field1' field, the 'field2' field,\n * // and 1000\n * logicalMaximum(field(\"field1\"), field(\"field2\"), 1000);\n * ```\n *\n * @param first - The first operand expression.\n * @param second - The second expression or literal.\n * @param others - Optional additional expressions or literals.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical maximum operation.\n */\nexport function logicalMaximum(\n  first: Expression,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the largest value between multiple input\n * expressions or literal values. Based on Firestore's value type ordering.\n *\n * @example\n * ```typescript\n * // Returns the largest value between the 'field1' field, the 'field2' field,\n * // and 1000.\n * logicalMaximum(\"field1\", field(\"field2\"), 1000);\n * ```\n *\n * @param fieldName - The first operand field name.\n * @param second - The second expression or literal.\n * @param others - Optional additional expressions or literals.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical maximum operation.\n */\nexport function logicalMaximum(\n  fieldName: string,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\n\nexport function logicalMaximum(\n  first: Expression | string,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression {\n  return fieldOrExpression(first).logicalMaximum(\n    valueToDefaultExpr(second),\n    ...others.map(value => valueToDefaultExpr(value))\n  );\n}\n\n/**\n *\n * Creates an expression that returns the smallest value between multiple input\n * expressions and literal values. Based on Firestore's value type ordering.\n *\n * @example\n * ```typescript\n * // Returns the smallest value between the 'field1' field, the 'field2' field,\n * // and 1000.\n * logicalMinimum(field(\"field1\"), field(\"field2\"), 1000);\n * ```\n *\n * @param first - The first operand expression.\n * @param second - The second expression or literal.\n * @param others - Optional additional expressions or literals.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical minimum operation.\n */\nexport function logicalMinimum(\n  first: Expression,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the smallest value between a field's value\n * and other input expressions or literal values.\n * Based on Firestore's value type ordering.\n *\n * @example\n * ```typescript\n * // Returns the smallest value between the 'field1' field, the 'field2' field,\n * // and 1000.\n * logicalMinimum(\"field1\", field(\"field2\"), 1000);\n * ```\n *\n * @param fieldName - The first operand field name.\n * @param second - The second expression or literal.\n * @param others - Optional additional expressions or literals.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical minimum operation.\n */\nexport function logicalMinimum(\n  fieldName: string,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\n\nexport function logicalMinimum(\n  first: Expression | string,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression {\n  return fieldOrExpression(first).logicalMinimum(\n    valueToDefaultExpr(second),\n    ...others.map(value => valueToDefaultExpr(value))\n  );\n}\n\n/**\n *\n * Creates an expression that checks if a field exists.\n *\n * @example\n * ```typescript\n * // Check if the document has a field named \"phoneNumber\"\n * exists(field(\"phoneNumber\"));\n * ```\n *\n * @param value - An expression evaluates to the name of the field to check.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'exists' check.\n */\nexport function exists(value: Expression): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field exists.\n *\n * @example\n * ```typescript\n * // Check if the document has a field named \"phoneNumber\"\n * exists(\"phoneNumber\");\n * ```\n *\n * @param fieldName - The field name to check.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'exists' check.\n */\nexport function exists(fieldName: string): BooleanExpression;\nexport function exists(valueOrField: Expression | string): BooleanExpression {\n  return fieldOrExpression(valueOrField).exists();\n}\n\n/**\n *\n * Creates an expression that reverses a string.\n *\n * @example\n * ```typescript\n * // Reverse the value of the 'myString' field.\n * reverse(field(\"myString\"));\n * ```\n *\n * @param stringExpression - An expression evaluating to a string value, which will be reversed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.\n */\nexport function reverse(stringExpression: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that reverses a string value in the specified field.\n *\n * @example\n * ```typescript\n * // Reverse the value of the 'myString' field.\n * reverse(\"myString\");\n * ```\n *\n * @param field - The name of the field representing the string to reverse.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.\n */\nexport function reverse(field: string): FunctionExpression;\nexport function reverse(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).reverse();\n}\n\n/**\n *\n * Creates an expression that calculates the byte length of a string in UTF-8, or just the length of a Blob.\n *\n * @example\n * ```typescript\n * // Calculate the length of the 'myString' field in bytes.\n * byteLength(field(\"myString\"));\n * ```\n *\n * @param expr - The expression representing the string.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string in bytes.\n */\nexport function byteLength(expr: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob.\n *\n * @example\n * ```typescript\n * // Calculate the length of the 'myString' field in bytes.\n * byteLength(\"myString\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string in bytes.\n */\nexport function byteLength(fieldName: string): FunctionExpression;\nexport function byteLength(expr: Expression | string): FunctionExpression {\n  const normalizedExpr = fieldOrExpression(expr);\n  return normalizedExpr.byteLength();\n}\n\n/**\n * Creates an expression that reverses an array.\n *\n * @example\n * ```typescript\n * // Reverse the value of the 'myArray' field.\n * arrayReverse(\"myArray\");\n * ```\n *\n * @param fieldName - The name of the field to reverse.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed array.\n */\nexport function arrayReverse(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that reverses an array.\n *\n * @example\n * ```typescript\n * // Reverse the value of the 'myArray' field.\n * arrayReverse(field(\"myArray\"));\n * ```\n *\n * @param arrayExpression - An expression evaluating to an array value, which will be reversed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed array.\n */\nexport function arrayReverse(arrayExpression: Expression): FunctionExpression;\nexport function arrayReverse(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).arrayReverse();\n}\n\n/**\n * Creates an expression that computes e to the power of the expression's result.\n *\n * @example\n * ```typescript\n * // Compute e to the power of 2.\n * exp(constant(2));\n * ```\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the exp of the numeric value.\n */\nexport function exp(expression: Expression): FunctionExpression;\n\n/**\n * Creates an expression that computes e to the power of the expression's result.\n *\n * @example\n * ```typescript\n * // Compute e to the power of the 'value' field.\n * exp('value');\n * ```\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the exp of the numeric value.\n */\nexport function exp(fieldName: string): FunctionExpression;\n\nexport function exp(\n  expressionOrFieldName: Expression | string\n): FunctionExpression {\n  return fieldOrExpression(expressionOrFieldName).exp();\n}\n\n/**\n * Creates an expression that computes the ceiling of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the ceiling of the 'price' field.\n * ceil(\"price\");\n * ```\n *\n * @param fieldName - The name of the field to compute the ceiling of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ceiling of the numeric value.\n */\nexport function ceil(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that computes the ceiling of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the ceiling of the 'price' field.\n * ceil(field(\"price\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which the ceiling will be computed for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ceiling of the numeric value.\n */\nexport function ceil(expression: Expression): FunctionExpression;\nexport function ceil(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).ceil();\n}\n\n/**\n * Creates an expression that computes the floor of a numeric value.\n *\n * @param expr - The expression to compute the floor of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the floor of the numeric value.\n */\nexport function floor(expr: Expression): FunctionExpression;\n\n/**\n * Creates an expression that computes the floor of a numeric value.\n *\n * @param fieldName - The name of the field to compute the floor of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the floor of the numeric value.\n */\nexport function floor(fieldName: string): FunctionExpression;\nexport function floor(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).floor();\n}\n\n/**\n * Creates an aggregation that counts the number of distinct values of a field.\n *\n * @param expr - The expression or field to count distinct values of.\n * @returns A new `AggregateFunction` representing the 'count_distinct' aggregation.\n */\nexport function countDistinct(expr: Expression | string): AggregateFunction {\n  return fieldOrExpression(expr).countDistinct();\n}\n\n/**\n *\n * Creates an expression that calculates the character length of a string field in UTF8.\n *\n * @example\n * ```typescript\n * // Get the character length of the 'name' field in UTF-8.\n * charLength(\"name\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string.\n */\nexport function charLength(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that calculates the character length of a string expression in UTF-8.\n *\n * @example\n * ```typescript\n * // Get the character length of the 'name' field in UTF-8.\n * charLength(field(\"name\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to calculate the length of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string.\n */\nexport function charLength(stringExpression: Expression): FunctionExpression;\nexport function charLength(value: Expression | string): FunctionExpression {\n  const valueExpr = fieldOrExpression(value);\n  return valueExpr.charLength();\n}\n\n/**\n *\n * Creates an expression that performs a case-sensitive wildcard string comparison against a\n * field.\n *\n * @example\n * ```typescript\n * // Check if the 'title' field contains the string \"guide\"\n * like(\"title\", \"%guide%\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param pattern - The pattern to search for. You can use \"%\" as a wildcard character.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'like' comparison.\n */\nexport function like(fieldName: string, pattern: string): BooleanExpression;\n\n/**\n *\n * Creates an expression that performs a case-sensitive wildcard string comparison against a\n * field.\n *\n * @example\n * ```typescript\n * // Check if the 'title' field contains the string \"guide\"\n * like(\"title\", field(\"pattern\"));\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param pattern - The pattern to search for. You can use \"%\" as a wildcard character.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'like' comparison.\n */\nexport function like(fieldName: string, pattern: Expression): BooleanExpression;\n\n/**\n *\n * Creates an expression that performs a case-sensitive wildcard string comparison.\n *\n * @example\n * ```typescript\n * // Check if the 'title' field contains the string \"guide\"\n * like(field(\"title\"), \"%guide%\");\n * ```\n *\n * @param stringExpression - The expression representing the string to perform the comparison on.\n * @param pattern - The pattern to search for. You can use \"%\" as a wildcard character.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'like' comparison.\n */\nexport function like(\n  stringExpression: Expression,\n  pattern: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that performs a case-sensitive wildcard string comparison.\n *\n * @example\n * ```typescript\n * // Check if the 'title' field contains the string \"guide\"\n * like(field(\"title\"), field(\"pattern\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to perform the comparison on.\n * @param pattern - The pattern to search for. You can use \"%\" as a wildcard character.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'like' comparison.\n */\nexport function like(\n  stringExpression: Expression,\n  pattern: Expression\n): BooleanExpression;\nexport function like(\n  left: Expression | string,\n  pattern: Expression | string\n): BooleanExpression {\n  const leftExpr = fieldOrExpression(left);\n  const patternExpr = valueToDefaultExpr(pattern);\n  return leftExpr.like(patternExpr);\n}\n\n/**\n *\n * Creates an expression that checks if a string field contains a specified regular expression as\n * a substring.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains \"example\" (case-insensitive)\n * regexContains(\"description\", \"(?i)example\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param pattern - The regular expression to use for the search.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function regexContains(\n  fieldName: string,\n  pattern: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string field contains a specified regular expression as\n * a substring.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains \"example\" (case-insensitive)\n * regexContains(\"description\", field(\"pattern\"));\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param pattern - The regular expression to use for the search.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function regexContains(\n  fieldName: string,\n  pattern: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression contains a specified regular\n * expression as a substring.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains \"example\" (case-insensitive)\n * regexContains(field(\"description\"), \"(?i)example\");\n * ```\n *\n * @param stringExpression - The expression representing the string to perform the comparison on.\n * @param pattern - The regular expression to use for the search.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function regexContains(\n  stringExpression: Expression,\n  pattern: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression contains a specified regular\n * expression as a substring.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains \"example\" (case-insensitive)\n * regexContains(field(\"description\"), field(\"pattern\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to perform the comparison on.\n * @param pattern - The regular expression to use for the search.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function regexContains(\n  stringExpression: Expression,\n  pattern: Expression\n): BooleanExpression;\nexport function regexContains(\n  left: Expression | string,\n  pattern: Expression | string\n): BooleanExpression {\n  const leftExpr = fieldOrExpression(left);\n  const patternExpr = valueToDefaultExpr(pattern);\n  return leftExpr.regexContains(patternExpr);\n}\n\n/**\n *\n * Creates an expression that filters an array using a provided alias and predicate expression.\n *\n * @example\n * ```typescript\n * // Get a filtered array of the 'scores' field containing only elements greater than 50.\n * arrayFilter(\"scores\", \"score\", greaterThan(variable(\"score\"), 50));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param alias - The variable name to use for each element.\n * @param filter - The predicate boolean expression to evaluate for each element.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the filtered array.\n */\nexport function arrayFilter(\n  fieldName: string,\n  alias: string,\n  filter: BooleanExpression\n): FunctionExpression;\n\n/**\n * Creates an expression that filters an array using a provided alias and predicate expression.\n *\n * @example\n * ```typescript\n * // Filter \"scores\" to include only values greater than 50\n * arrayFilter(field(\"scores\"), \"score\", greaterThan(variable(\"score\"), 50));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param alias - The variable name to use for each element.\n * @param filter - The predicate boolean expression to filter by.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the filtered array.\n */\nexport function arrayFilter(\n  arrayExpression: Expression,\n  alias: string,\n  filter: BooleanExpression\n): FunctionExpression;\n\nexport function arrayFilter(\n  array: Expression | string,\n  alias: string,\n  filter: BooleanExpression\n): FunctionExpression {\n  return fieldOrExpression(array).arrayFilter(alias, filter);\n}\n\n/**\n * Creates an expression that applies a provided transformation to each element in an array.\n *\n * @example\n * ```typescript\n * // Transform \"scores\" array by multiplying each score by 10\n * arrayTransform(field(\"scores\"), \"score\", multiply(variable(\"score\"), 10));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param elementAlias - The variable name to use for each element.\n * @param transform - The lambda expression used to transform the elements.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the transformed array.\n */\nexport function arrayTransform(\n  arrayExpression: Expression,\n  elementAlias: string,\n  transform: Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that applies a provided transformation to each element in an array.\n *\n * @example\n * ```typescript\n * // Transform \"scores\" array by multiplying each score by 10\n * arrayTransform(\"scores\", \"score\", multiply(variable(\"score\"), 10));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param elementAlias - The variable name to use for each element.\n * @param transform - The expression used to transform the elements.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the transformed array.\n */\nexport function arrayTransform(\n  fieldName: string,\n  elementAlias: string,\n  transform: Expression\n): FunctionExpression;\nexport function arrayTransform(\n  array: Expression | string,\n  elementAlias: string,\n  transform: Expression\n): FunctionExpression {\n  return fieldOrExpression(array).arrayTransform(elementAlias, transform);\n}\n\n/**\n * Creates an expression that applies a provided transformation to each element in an array, providing the element's index to the transformation expression.\n *\n * @example\n * ```typescript\n * // Transform \"scores\" array by adding the index to each score\n * arrayTransformWithIndex(field(\"scores\"), \"score\", \"i\", add(variable(\"score\"), variable(\"i\")));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param elementAlias - The variable name to use for each element.\n * @param indexAlias - The variable name to use for the current index.\n * @param transform - The expression used to transform the elements.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the transformed array.\n */\nexport function arrayTransformWithIndex(\n  arrayExpression: Expression,\n  elementAlias: string,\n  indexAlias: string,\n  transform: Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that applies a provided transformation to each element in an array, providing the element's index to the transformation expression.\n *\n * @example\n * ```typescript\n * // Transform \"scores\" array by adding the index to each score\n * arrayTransformWithIndex(\"scores\", \"score\", \"i\", add(variable(\"score\"), variable(\"i\")));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param elementAlias - The variable name to use for each element.\n * @param indexAlias - The variable name to use for the current index.\n * @param transform - The lambda expression used to transform the elements.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the transformed array.\n */\nexport function arrayTransformWithIndex(\n  fieldName: string,\n  elementAlias: string,\n  indexAlias: string,\n  transform: Expression\n): FunctionExpression;\nexport function arrayTransformWithIndex(\n  array: Expression | string,\n  elementAlias: string,\n  indexAlias: string,\n  transform: Expression\n): FunctionExpression {\n  return fieldOrExpression(array).arrayTransformWithIndex(\n    elementAlias,\n    indexAlias,\n    transform\n  );\n}\n\n/**\n * Creates an expression that returns a slice of an array from `offset` with `length` elements.\n *\n * @example\n * ```typescript\n * // Get 5 elements from the 'items' array field starting from index 2\n * arraySlice(\"items\", 2, 5);\n *\n * // Get n elements from the 'items' array field starting from index 2\n * arraySlice(\"items\", 2, field(\"length\"));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param offset - The starting offset.\n * @param length - The optional length of the slice.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the sliced array.\n */\nexport function arraySlice(\n  fieldName: string,\n  offset: number | Expression,\n  length?: number | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that returns a slice of an array from `offset` with `length` elements.\n *\n * @example\n * ```typescript\n * // Get 5 elements from an array expression starting from index 2\n * arraySlice(field(\"items\"), 2, 5);\n *\n * // Get n elements from an array expression starting from index 2\n * arraySlice(field(\"items\"), 2, field(\"length\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param offset - The starting offset.\n * @param length - The optional length of the slice.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the sliced array.\n */\nexport function arraySlice(\n  arrayExpression: Expression,\n  offset: number | Expression,\n  length?: number | Expression\n): FunctionExpression;\nexport function arraySlice(\n  array: Expression | string,\n  offset: number | Expression,\n  length?: number | Expression\n): FunctionExpression {\n  return fieldOrExpression(array).arraySlice(offset, length);\n}\n\n/**\n * Creates an expression that returns the first element of an array.\n *\n * @example\n * ```typescript\n * // Get the first tag from the 'tags' array field\n * arrayFirst(\"tags\");\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the first element.\n */\nexport function arrayFirst(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first element of an array.\n *\n * @example\n * ```typescript\n * // Get the first tag from the 'tags' array field\n * arrayFirst(field(\"tags\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the first element.\n */\nexport function arrayFirst(arrayExpression: Expression): FunctionExpression;\nexport function arrayFirst(array: Expression | string): FunctionExpression {\n  return fieldOrExpression(array).arrayFirst();\n}\n\n/**\n *\n * Creates an expression that returns the first `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the first 3 tags from the 'tags' array field\n * arrayFirstN(\"tags\", 3);\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the first `n` elements.\n */\nexport function arrayFirstN(fieldName: string, n: number): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the first n tags from the 'tags' array field\n * arrayFirstN(\"tags\", field(\"count\"));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the first `n` elements.\n */\nexport function arrayFirstN(\n  fieldName: string,\n  n: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the first 3 elements from an array expression\n * arrayFirstN(field(\"tags\"), 3);\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the first `n` elements.\n */\nexport function arrayFirstN(\n  arrayExpression: Expression,\n  n: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the first n elements from an array expression\n * arrayFirstN(field(\"tags\"), field(\"count\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the first `n` elements.\n */\nexport function arrayFirstN(\n  arrayExpression: Expression,\n  n: Expression\n): FunctionExpression;\nexport function arrayFirstN(\n  array: Expression | string,\n  n: Expression | number\n): FunctionExpression {\n  return fieldOrExpression(array).arrayFirstN(valueToDefaultExpr(n));\n}\n\n/**\n *\n * Creates an expression that returns the last element of an array.\n *\n * @example\n * ```typescript\n * // Get the last tag from the 'tags' array field\n * arrayLast(\"tags\");\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the last element.\n */\nexport function arrayLast(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the last element of an array.\n *\n * @example\n * ```typescript\n * // Get the last tag from the 'tags' array field\n * arrayLast(field(\"tags\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the last element.\n */\nexport function arrayLast(arrayExpression: Expression): FunctionExpression;\nexport function arrayLast(array: Expression | string): FunctionExpression {\n  return fieldOrExpression(array).arrayLast();\n}\n\n/**\n *\n * Creates an expression that returns the last `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the last 3 tags from the 'tags' array field\n * arrayLastN(\"tags\", 3);\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the last `n` elements.\n */\nexport function arrayLastN(fieldName: string, n: number): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the last `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the last n tags from the 'tags' array field\n * arrayLastN(\"tags\", field(\"count\"));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the last `n` elements.\n */\nexport function arrayLastN(\n  fieldName: string,\n  n: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the last `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the last 3 elements from an array expression\n * arrayLastN(field(\"tags\"), 3);\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the last `n` elements.\n */\nexport function arrayLastN(\n  arrayExpression: Expression,\n  n: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the last `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the last n elements from an array expression\n * arrayLastN(field(\"tags\"), field(\"count\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the last `n` elements.\n */\nexport function arrayLastN(\n  arrayExpression: Expression,\n  n: Expression\n): FunctionExpression;\nexport function arrayLastN(\n  array: Expression | string,\n  n: Expression | number\n): FunctionExpression {\n  return fieldOrExpression(array).arrayLastN(valueToDefaultExpr(n));\n}\n\n/**\n *\n * Creates an expression that returns the maximum value in an array.\n *\n * @example\n * ```typescript\n * // Get the maximum value from the 'scores' array field\n * arrayMaximum(\"scores\");\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the maximum value.\n */\nexport function arrayMaximum(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the maximum value in an array.\n *\n * @example\n * ```typescript\n * // Get the maximum value from the 'scores' array field\n * arrayMaximum(field(\"scores\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the maximum value.\n */\nexport function arrayMaximum(arrayExpression: Expression): FunctionExpression;\nexport function arrayMaximum(array: Expression | string): FunctionExpression {\n  return fieldOrExpression(array).arrayMaximum();\n}\n\n/**\n *\n * Creates an expression that returns the largest `n` elements of an array.\n *\n * Note: Returns the n largest non-null elements in the array, in descending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the top 3 scores from the 'scores' array field\n * arrayMaximumN(\"scores\", 3);\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the largest `n` elements.\n */\nexport function arrayMaximumN(fieldName: string, n: number): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the largest `n` elements of an array.\n *\n * Note: Returns the n largest non-null elements in the array, in descending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the top n scores from the 'scores' array field\n * arrayMaximumN(\"scores\", field(\"count\"));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the largest `n` elements.\n */\nexport function arrayMaximumN(\n  fieldName: string,\n  n: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the largest `n` elements of an array.\n *\n * Note: Returns the n largest non-null elements in the array, in descending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the top 3 elements from an array expression\n * arrayMaximumN(field(\"scores\"), 3);\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the largest `n` elements.\n */\nexport function arrayMaximumN(\n  arrayExpression: Expression,\n  n: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the largest `n` elements of an array.\n *\n * Note: Returns the n largest non-null elements in the array, in descending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the top n elements from an array expression\n * arrayMaximumN(field(\"scores\"), field(\"count\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the largest `n` elements.\n */\nexport function arrayMaximumN(\n  arrayExpression: Expression,\n  n: Expression\n): FunctionExpression;\nexport function arrayMaximumN(\n  array: Expression | string,\n  n: Expression | number\n): FunctionExpression {\n  return fieldOrExpression(array).arrayMaximumN(valueToDefaultExpr(n));\n}\n\n/**\n *\n * Creates an expression that returns the minimum value in an array.\n *\n * @example\n * ```typescript\n * // Get the minimum value from the 'scores' array field\n * arrayMinimum(\"scores\");\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the minimum value.\n */\nexport function arrayMinimum(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the minimum value in an array.\n *\n * @example\n * ```typescript\n * // Get the minimum value from the 'scores' array field\n * arrayMinimum(field(\"scores\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the minimum value.\n */\nexport function arrayMinimum(arrayExpression: Expression): FunctionExpression;\nexport function arrayMinimum(array: Expression | string): FunctionExpression {\n  return fieldOrExpression(array).arrayMinimum();\n}\n\n/**\n *\n * Creates an expression that returns the smallest `n` elements of an array.\n *\n * Note: Returns the n smallest non-null elements in the array, in ascending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the bottom 3 scores from the 'scores' array field\n * arrayMinimumN(\"scores\", 3);\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the smallest `n` elements.\n */\nexport function arrayMinimumN(fieldName: string, n: number): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the smallest `n` elements of an array.\n *\n * Note: Returns the n smallest non-null elements in the array, in ascending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the bottom n scores from the 'scores' array field\n * arrayMinimumN(field(\"scores\"), field(\"count\"));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the smallest `n` elements.\n */\nexport function arrayMinimumN(\n  fieldName: string,\n  n: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the smallest `n` elements of an array.\n *\n * Note: Returns the n smallest non-null elements in the array, in ascending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the bottom 3 scores from the 'scores' array field\n * arrayMinimumN(field(\"scores\"), 3);\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the smallest `n` elements.\n */\nexport function arrayMinimumN(\n  arrayExpression: Expression,\n  n: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the smallest `n` elements of an array.\n *\n * Note: Returns the n smallest non-null elements in the array, in ascending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the bottom n scores from the 'scores' array field\n * arrayMinimumN(field(\"scores\"), field(\"count\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the smallest `n` elements.\n */\nexport function arrayMinimumN(\n  arrayExpression: Expression,\n  n: Expression\n): FunctionExpression;\nexport function arrayMinimumN(\n  array: Expression | string,\n  n: Expression | number\n): FunctionExpression {\n  return fieldOrExpression(array).arrayMinimumN(valueToDefaultExpr(n));\n}\n\n/**\n *\n * Creates an expression that returns the first index of the search value in an array.\n * Returns -1 if the value is not found.\n *\n * @example\n * ```typescript\n * // Get the index of \"politics\" in the 'tags' array field\n * arrayIndexOf(\"tags\", \"politics\");\n * ```\n *\n * @param fieldName - The name of the field containing the array to search.\n * @param search - The value to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the index.\n */\nexport function arrayIndexOf(\n  fieldName: string,\n  search: unknown | Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first index of the search value in an array.\n * Returns -1 if the value is not found.\n *\n * @example\n * ```typescript\n * // Get the index of \"politics\" in the 'tags' array field\n * arrayIndexOf(field(\"tags\"), \"politics\");\n * ```\n *\n * @param arrayExpression - The expression representing the array to search.\n * @param search - The value to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the index.\n */\nexport function arrayIndexOf(\n  arrayExpression: Expression,\n  search: unknown | Expression\n): FunctionExpression;\nexport function arrayIndexOf(\n  array: Expression | string,\n  search: unknown | Expression\n): FunctionExpression {\n  return fieldOrExpression(array).arrayIndexOf(valueToDefaultExpr(search));\n}\n\n/**\n *\n * Creates an expression that returns the last index of the search value in an array.\n * Returns -1 if the value is not found.\n *\n * @example\n * ```typescript\n * // Get the last index of \"politics\" in the 'tags' array field\n * arrayLastIndexOf(\"tags\", \"politics\");\n * ```\n *\n * @param fieldName - The name of the field containing the array to search.\n * @param search - The value to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the index.\n */\nexport function arrayLastIndexOf(\n  fieldName: string,\n  search: unknown | Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the last index of the search value in an array.\n * Returns -1 if the value is not found.\n *\n * @example\n * ```typescript\n * // Get the last index of \"politics\" in the 'tags' array field\n * arrayLastIndexOf(field(\"tags\"), \"politics\");\n * ```\n *\n * @param arrayExpression - The expression representing the array to search.\n * @param search - The value to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the index.\n */\nexport function arrayLastIndexOf(\n  arrayExpression: Expression,\n  search: unknown | Expression\n): FunctionExpression;\nexport function arrayLastIndexOf(\n  array: Expression | string,\n  search: unknown | Expression\n): FunctionExpression {\n  return fieldOrExpression(array).arrayLastIndexOf(valueToDefaultExpr(search));\n}\n\n/**\n *\n * Creates an expression that returns all indices of the search value in an array.\n *\n * @example\n * ```typescript\n * // Get all indices of 5 in the 'scores' array field\n * arrayIndexOfAll(\"scores\", 5);\n * ```\n *\n * @param fieldName - The name of the field containing the array to search.\n * @param search - The value to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the indices.\n */\nexport function arrayIndexOfAll(\n  fieldName: string,\n  search: unknown | Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns all indices of the search value in an array.\n *\n * @example\n * ```typescript\n * // Get all indices of 5 in the 'scores' array field\n * arrayIndexOfAll(field(\"scores\"), 5);\n * ```\n *\n * @param arrayExpression - The expression representing the array to search.\n * @param search - The value to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the indices.\n */\nexport function arrayIndexOfAll(\n  arrayExpression: Expression,\n  search: unknown | Expression\n): FunctionExpression;\nexport function arrayIndexOfAll(\n  array: Expression | string,\n  search: unknown | Expression\n): FunctionExpression {\n  return fieldOrExpression(array).arrayIndexOfAll(valueToDefaultExpr(search));\n}\n\n/**\n *\n * Creates an expression that returns the first substring of a string field that matches a\n * specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract the domain name from an email field\n * regexFind(\"email\", \"@[A-Za-z0-9.-]+\");\n * ```\n *\n * @param fieldName - The name of the field containing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function.\n */\nexport function regexFind(\n  fieldName: string,\n  pattern: string\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first substring of a string field that matches a\n * specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract a substring from 'email' based on a pattern stored in another field\n * regexFind(\"email\", field(\"pattern\"));\n * ```\n *\n * @param fieldName - The name of the field containing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function.\n */\nexport function regexFind(\n  fieldName: string,\n  pattern: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first substring of a string expression that matches\n * a specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract the domain from a lower-cased email address\n * regexFind(field(\"email\"), \"@[A-Za-z0-9.-]+\");\n * ```\n *\n * @param stringExpression - The expression representing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function.\n */\nexport function regexFind(\n  stringExpression: Expression,\n  pattern: string\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first substring of a string expression that matches\n * a specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract a substring based on a dynamic pattern field\n * regexFind(field(\"email\"), field(\"pattern\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function.\n */\nexport function regexFind(\n  stringExpression: Expression,\n  pattern: Expression\n): FunctionExpression;\nexport function regexFind(\n  left: Expression | string,\n  pattern: Expression | string\n): FunctionExpression {\n  const leftExpr = fieldOrExpression(left);\n  const patternExpr = valueToDefaultExpr(pattern);\n  return leftExpr.regexFind(patternExpr);\n}\n\n/**\n *\n * Creates an expression that evaluates to a list of all substrings in a string field that\n * match a specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract all hashtags from a post content field\n * regexFindAll(\"content\", \"#[A-Za-z0-9_]+\");\n * ```\n *\n * @param fieldName - The name of the field containing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#FunctionExpression} that evaluates to an array of matched substrings.\n */\nexport function regexFindAll(\n  fieldName: string,\n  pattern: string\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that evaluates to a list of all substrings in a string field that\n * match a specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract all matches from 'content' based on a pattern stored in another field\n * regexFindAll(\"content\", field(\"pattern\"));\n * ```\n *\n * @param fieldName - The name of the field containing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#FunctionExpression} that evaluates to an array of matched substrings.\n */\nexport function regexFindAll(\n  fieldName: string,\n  pattern: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that evaluates to a list of all substrings in a string expression\n * that match a specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract all mentions from a lower-cased comment\n * regexFindAll(field(\"comment\"), \"@[A-Za-z0-9_]+\");\n * ```\n *\n * @param stringExpression - The expression representing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#FunctionExpression} that evaluates to an array of matched substrings.\n */\nexport function regexFindAll(\n  stringExpression: Expression,\n  pattern: string\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that evaluates to a list of all substrings in a string expression\n * that match a specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract all matches based on a dynamic pattern expression\n * regexFindAll(field(\"comment\"), field(\"pattern\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#FunctionExpression} that evaluates to an array of matched substrings.\n */\nexport function regexFindAll(\n  stringExpression: Expression,\n  pattern: Expression\n): FunctionExpression;\nexport function regexFindAll(\n  left: Expression | string,\n  pattern: Expression | string\n): FunctionExpression {\n  const leftExpr = fieldOrExpression(left);\n  const patternExpr = valueToDefaultExpr(pattern);\n  return leftExpr.regexFindAll(patternExpr);\n}\n\n/**\n *\n * Creates an expression that checks if a string field matches a specified regular expression.\n *\n * @example\n * ```typescript\n * // Check if the 'email' field matches a valid email pattern\n * regexMatch(\"email\", \"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,}\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param pattern - The regular expression to use for the match.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression match.\n */\nexport function regexMatch(\n  fieldName: string,\n  pattern: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string field matches a specified regular expression.\n *\n * @example\n * ```typescript\n * // Check if the 'email' field matches a valid email pattern\n * regexMatch(\"email\", field(\"pattern\"));\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param pattern - The regular expression to use for the match.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression match.\n */\nexport function regexMatch(\n  fieldName: string,\n  pattern: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression matches a specified regular\n * expression.\n *\n * @example\n * ```typescript\n * // Check if the 'email' field matches a valid email pattern\n * regexMatch(field(\"email\"), \"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,}\");\n * ```\n *\n * @param stringExpression - The expression representing the string to match against.\n * @param pattern - The regular expression to use for the match.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression match.\n */\nexport function regexMatch(\n  stringExpression: Expression,\n  pattern: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression matches a specified regular\n * expression.\n *\n * @example\n * ```typescript\n * // Check if the 'email' field matches a valid email pattern\n * regexMatch(field(\"email\"), field(\"pattern\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to match against.\n * @param pattern - The regular expression to use for the match.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression match.\n */\nexport function regexMatch(\n  stringExpression: Expression,\n  pattern: Expression\n): BooleanExpression;\nexport function regexMatch(\n  left: Expression | string,\n  pattern: Expression | string\n): BooleanExpression {\n  const leftExpr = fieldOrExpression(left);\n  const patternExpr = valueToDefaultExpr(pattern);\n  return leftExpr.regexMatch(patternExpr);\n}\n\n/**\n *\n * Creates an expression that checks if a string field contains a specified substring.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains \"example\".\n * stringContains(\"description\", \"example\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param substring - The substring to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function stringContains(\n  fieldName: string,\n  substring: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string field contains a substring specified by an expression.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains the value of the 'keyword' field.\n * stringContains(\"description\", field(\"keyword\"));\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param substring - The expression representing the substring to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function stringContains(\n  fieldName: string,\n  substring: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression contains a specified substring.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains \"example\".\n * stringContains(field(\"description\"), \"example\");\n * ```\n *\n * @param stringExpression - The expression representing the string to perform the comparison on.\n * @param substring - The substring to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function stringContains(\n  stringExpression: Expression,\n  substring: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression contains a substring specified by another expression.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains the value of the 'keyword' field.\n * stringContains(field(\"description\"), field(\"keyword\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to perform the comparison on.\n * @param substring - The expression representing the substring to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function stringContains(\n  stringExpression: Expression,\n  substring: Expression\n): BooleanExpression;\nexport function stringContains(\n  left: Expression | string,\n  substring: Expression | string\n): BooleanExpression {\n  const leftExpr = fieldOrExpression(left);\n  const substringExpr = valueToDefaultExpr(substring);\n  return leftExpr.stringContains(substringExpr);\n}\n\n/**\n *\n * Creates an expression that checks if a field's value starts with a given prefix.\n *\n * @example\n * ```typescript\n * // Check if the 'name' field starts with \"Mr.\"\n * startsWith(\"name\", \"Mr.\");\n * ```\n *\n * @param fieldName - The field name to check.\n * @param prefix - The prefix to check for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'starts with' comparison.\n */\nexport function startsWith(\n  fieldName: string,\n  prefix: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value starts with a given prefix.\n *\n * @example\n * ```typescript\n * // Check if the 'fullName' field starts with the value of the 'firstName' field\n * startsWith(\"fullName\", field(\"firstName\"));\n * ```\n *\n * @param fieldName - The field name to check.\n * @param prefix - The expression representing the prefix.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'starts with' comparison.\n */\nexport function startsWith(\n  fieldName: string,\n  prefix: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression starts with a given prefix.\n *\n * @example\n * ```typescript\n * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with \"Mr.\"\n * startsWith(field(\"fullName\"), \"Mr.\");\n * ```\n *\n * @param stringExpression - The expression to check.\n * @param prefix - The prefix to check for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'starts with' comparison.\n */\nexport function startsWith(\n  stringExpression: Expression,\n  prefix: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression starts with a given prefix.\n *\n * @example\n * ```typescript\n * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with \"Mr.\"\n * startsWith(field(\"fullName\"), field(\"prefix\"));\n * ```\n *\n * @param stringExpression - The expression to check.\n * @param prefix - The prefix to check for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'starts with' comparison.\n */\nexport function startsWith(\n  stringExpression: Expression,\n  prefix: Expression\n): BooleanExpression;\nexport function startsWith(\n  expr: Expression | string,\n  prefix: Expression | string\n): BooleanExpression {\n  return fieldOrExpression(expr).startsWith(valueToDefaultExpr(prefix));\n}\n\n/**\n *\n * Creates an expression that checks if a field's value ends with a given postfix.\n *\n * @example\n * ```typescript\n * // Check if the 'filename' field ends with \".txt\"\n * endsWith(\"filename\", \".txt\");\n * ```\n *\n * @param fieldName - The field name to check.\n * @param suffix - The postfix to check for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ends with' comparison.\n */\nexport function endsWith(fieldName: string, suffix: string): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value ends with a given postfix.\n *\n * @example\n * ```typescript\n * // Check if the 'url' field ends with the value of the 'extension' field\n * endsWith(\"url\", field(\"extension\"));\n * ```\n *\n * @param fieldName - The field name to check.\n * @param suffix - The expression representing the postfix.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ends with' comparison.\n */\nexport function endsWith(\n  fieldName: string,\n  suffix: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression ends with a given postfix.\n *\n * @example\n * ```typescript\n * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with \"Jr.\"\n * endsWith(field(\"fullName\"), \"Jr.\");\n * ```\n *\n * @param stringExpression - The expression to check.\n * @param suffix - The postfix to check for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ends with' comparison.\n */\nexport function endsWith(\n  stringExpression: Expression,\n  suffix: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression ends with a given postfix.\n *\n * @example\n * ```typescript\n * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with \"Jr.\"\n * endsWith(field(\"fullName\"), constant(\"Jr.\"));\n * ```\n *\n * @param stringExpression - The expression to check.\n * @param suffix - The postfix to check for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ends with' comparison.\n */\nexport function endsWith(\n  stringExpression: Expression,\n  suffix: Expression\n): BooleanExpression;\nexport function endsWith(\n  expr: Expression | string,\n  suffix: Expression | string\n): BooleanExpression {\n  return fieldOrExpression(expr).endsWith(valueToDefaultExpr(suffix));\n}\n\n/**\n *\n * Creates an expression that converts a string field to lowercase.\n *\n * @example\n * ```typescript\n * // Convert the 'name' field to lowercase\n * toLower(\"name\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the lowercase string.\n */\nexport function toLower(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that converts a string expression to lowercase.\n *\n * @example\n * ```typescript\n * // Convert the 'name' field to lowercase\n * toLower(field(\"name\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to convert to lowercase.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the lowercase string.\n */\nexport function toLower(stringExpression: Expression): FunctionExpression;\nexport function toLower(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).toLower();\n}\n\n/**\n *\n * Creates an expression that converts a string field to uppercase.\n *\n * @example\n * ```typescript\n * // Convert the 'title' field to uppercase\n * toUpper(\"title\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the uppercase string.\n */\nexport function toUpper(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that converts a string expression to uppercase.\n *\n * @example\n * ```typescript\n * // Convert the 'title' field to uppercase\n * toUpper(field(\"title\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to convert to uppercase.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the uppercase string.\n */\nexport function toUpper(stringExpression: Expression): FunctionExpression;\nexport function toUpper(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).toUpper();\n}\n\n/**\n *\n * Creates an expression that removes leading and trailing whitespace from a string or byte array.\n *\n * @example\n * ```typescript\n * // Trim whitespace from the 'userInput' field\n * trim(\"userInput\");\n *\n * // Trim quotes from the 'userInput' field\n * trim(\"userInput\", '\"');\n * ```\n *\n * @param fieldName - The name of the field containing the string or byte array.\n * @param valueToTrim - Optional This parameter is treated as a set of characters or bytes that will be\n * trimmed from the input. If not specified, then whitespace will be trimmed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string.\n */\nexport function trim(\n  fieldName: string,\n  valueToTrim?: string | Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that removes leading and trailing characters from a string or byte array expression.\n *\n * @example\n * ```typescript\n * // Trim whitespace from the 'userInput' field\n * trim(field(\"userInput\"));\n *\n * // Trim quotes from the 'userInput' field\n * trim(field(\"userInput\"), '\"');\n * ```\n *\n * @param stringExpression - The expression representing the string or byte array to trim.\n * @param valueToTrim - Optional This parameter is treated as a set of characters or bytes that will be\n * trimmed from the input. If not specified, then whitespace will be trimmed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array.\n */\nexport function trim(\n  stringExpression: Expression,\n  valueToTrim?: string | Expression\n): FunctionExpression;\nexport function trim(\n  expr: Expression | string,\n  valueToTrim?: string | Expression\n): FunctionExpression {\n  return fieldOrExpression(expr).trim(valueToTrim);\n}\n\n/**\n * Trims whitespace or a specified set of characters/bytes from the beginning of a string or byte array.\n *\n * @example\n * ```typescript\n * // Trim whitespace from the beginning of the 'userInput' field\n * ltrim(field(\"userInput\"));\n *\n * // Trim quotes from the beginning of the 'userInput' field\n * ltrim(field(\"userInput\"), '\"');\n * ```\n *\n * @param fieldName - The name of the field containing the string or byte array.\n * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim.\n * If not specified, whitespace will be trimmed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array.\n */\nexport function ltrim(\n  fieldName: string,\n  valueToTrim?: string | Expression | Bytes\n): FunctionExpression;\n\n/**\n * Trims whitespace or a specified set of characters/bytes from the beginning of a string or byte array.\n *\n * @example\n * ```typescript\n * // Trim whitespace from the beginning of the 'userInput' field\n * ltrim(field(\"userInput\"));\n *\n * // Trim quotes from the beginning of the 'userInput' field\n * ltrim(field(\"userInput\"), '\"');\n * ```\n *\n * @param expression - The expression representing the string or byte array.\n * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim.\n * If not specified, whitespace will be trimmed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array.\n */\nexport function ltrim(\n  expression: Expression,\n  valueToTrim?: string | Expression | Bytes\n): FunctionExpression;\nexport function ltrim(\n  expr: Expression | string,\n  valueToTrim?: string | Expression | Bytes\n): FunctionExpression {\n  return fieldOrExpression(expr).ltrim(valueToTrim);\n}\n\n/**\n * Trims whitespace or a specified set of characters/bytes from the end of a string or byte array.\n *\n * @example\n * ```typescript\n * // Trim whitespace from the end of the 'userInput' field\n * rtrim(field(\"userInput\"));\n *\n * // Trim quotes from the end of the 'userInput' field\n * rtrim(field(\"userInput\"), '\"');\n * ```\n *\n * @param fieldName - The name of the field containing the string or byte array.\n * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim.\n * If not specified, whitespace will be trimmed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array.\n */\nexport function rtrim(\n  fieldName: string,\n  valueToTrim?: string | Expression | Bytes\n): FunctionExpression;\n\n/**\n * Trims whitespace or a specified set of characters/bytes from the end of a string or byte array.\n *\n * @example\n * ```typescript\n * // Trim whitespace from the end of the 'userInput' field\n * rtrim(field(\"userInput\"));\n *\n * // Trim quotes from the end of the 'userInput' field\n * rtrim(field(\"userInput\"), '\"');\n * ```\n *\n * @param expression - The expression representing the string or byte array.\n * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim.\n * If not specified, whitespace will be trimmed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array.\n */\nexport function rtrim(\n  expression: Expression,\n  valueToTrim?: string | Expression | Bytes\n): FunctionExpression;\nexport function rtrim(\n  expr: Expression | string,\n  valueToTrim?: string | Expression | Bytes\n): FunctionExpression {\n  return fieldOrExpression(expr).rtrim(valueToTrim);\n}\n\n/**\n * Creates an expression that returns the data type of the data in the specified field.\n *\n * @remarks\n * String inputs passed iteratively to this global function act as `field()` path lookups.\n * If you wish to pass a string literal value, it must be wrapped: `type(constant(\"my_string\"))`.\n *\n * @example\n * ```typescript\n * // Get the data type of the value in field 'title'\n * type('title')\n * ```\n *\n * @returns A new `Expression` representing the data type.\n */\nexport function type(fieldName: string): FunctionExpression;\n/**\n * Creates an expression that returns the data type of an expression's result.\n *\n * @example\n * ```typescript\n * // Get the data type of a conditional expression\n * type(conditional(exists('foo'), constant(1), constant(true)))\n * ```\n *\n * @returns A new `Expression` representing the data type.\n */\nexport function type(expression: Expression): FunctionExpression;\nexport function type(\n  fieldNameOrExpression: string | Expression\n): FunctionExpression {\n  return fieldOrExpression(fieldNameOrExpression).type();\n}\n\n/**\n * Creates an expression that checks if the value in the specified field is of the given type.\n *\n * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data.\n * Supported values for `type` are:\n * `'null'`, `'array'`, `'boolean'`, `'bytes'`, `'timestamp'`, `'geo_point'`, `'number'`,\n * `'int32'`, `'int64'`, `'float64'`, `'decimal128'`, `'map'`, `'reference'`, `'string'`,\n * `'vector'`, `'max_key'`, `'min_key'`, `'object_id'`, `'regex'`, `'request_timestamp'`.\n *\n * @example\n * ```typescript\n * // Check if the 'price' field is a floating point number (evaluating to true inside pipeline conditionals)\n * isType('price', 'float64');\n * ```\n *\n * @param fieldName - The name of the field to check.\n * @param type - The type to check for.\n * @returns A new `BooleanExpression` that evaluates to true if the field's value is of the given type, false otherwise.\n */\nexport function isType(fieldName: string, type: string): BooleanExpression;\n\n/**\n * Creates an expression that checks if the result of an expression is of the given type.\n *\n * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data.\n * Supported values for `type` are:\n * `'null'`, `'array'`, `'boolean'`, `'bytes'`, `'timestamp'`, `'geo_point'`, `'number'`,\n * `'int32'`, `'int64'`, `'float64'`, `'decimal128'`, `'map'`, `'reference'`, `'string'`,\n * `'vector'`, `'max_key'`, `'min_key'`, `'object_id'`, `'regex'`, `'request_timestamp'`.\n *\n * @example\n * ```typescript\n * // Check if the result of a calculation is a number\n * isType(add('count', 1), 'number')\n * ```\n *\n * @param expression - The expression to check.\n * @param type - The type to check for.\n * @returns A new `BooleanExpression` that evaluates to true if the expression's result is of the given type, false otherwise.\n */\nexport function isType(expression: Expression, type: string): BooleanExpression;\nexport function isType(\n  fieldNameOrExpression: string | Expression,\n  type: string\n): BooleanExpression {\n  return fieldOrExpression(fieldNameOrExpression).isType(type);\n}\n\n/**\n *\n * Creates an expression that concatenates string functions, fields or constants together.\n *\n * @example\n * ```typescript\n * // Combine the 'firstName', \" \", and 'lastName' fields into a single string\n * stringConcat(\"firstName\", \" \", field(\"lastName\"));\n * ```\n *\n * @param fieldName - The field name containing the initial string value.\n * @param secondString - An expression or string literal to concatenate.\n * @param otherStrings - Optional additional expressions or literals (typically strings) to concatenate.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the concatenated string.\n */\nexport function stringConcat(\n  fieldName: string,\n  secondString: Expression | string,\n  ...otherStrings: Array<Expression | string>\n): FunctionExpression;\n\n/**\n * Creates an expression that concatenates string expressions together.\n *\n * @example\n * ```typescript\n * // Combine the 'firstName', \" \", and 'lastName' fields into a single string\n * stringConcat(field(\"firstName\"), \" \", field(\"lastName\"));\n * ```\n *\n * @param firstString - The initial string expression to concatenate to.\n * @param secondString - An expression or string literal to concatenate.\n * @param otherStrings - Optional additional expressions or literals (typically strings) to concatenate.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the concatenated string.\n */\nexport function stringConcat(\n  firstString: Expression,\n  secondString: Expression | string,\n  ...otherStrings: Array<Expression | string>\n): FunctionExpression;\nexport function stringConcat(\n  first: string | Expression,\n  second: string | Expression,\n  ...elements: Array<string | Expression>\n): FunctionExpression {\n  return fieldOrExpression(first).stringConcat(\n    valueToDefaultExpr(second),\n    ...elements.map(valueToDefaultExpr)\n  );\n}\n\n/**\n * Creates an expression that finds the index of the first occurrence of a substring or byte sequence.\n *\n * @example\n * ```typescript\n * // Find the index of \"foo\" in the 'text' field\n * stringIndexOf(\"text\", \"foo\");\n * ```\n *\n * @param fieldName - The name of the field containing the string or byte array.\n * @param search - The substring or byte sequence to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the index of the first occurrence.\n */\nexport function stringIndexOf(\n  fieldName: string,\n  search: string | Expression | Bytes\n): FunctionExpression;\n\n/**\n * Creates an expression that finds the index of the first occurrence of a substring or byte sequence.\n *\n * @example\n * ```typescript\n * // Find the index of \"foo\" in the 'text' field\n * stringIndexOf(field(\"text\"), \"foo\");\n * ```\n *\n * @param expression - The expression representing the string or byte array.\n * @param search - The substring or byte sequence to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the index of the first occurrence.\n */\nexport function stringIndexOf(\n  expression: Expression,\n  search: string | Expression | Bytes\n): FunctionExpression;\nexport function stringIndexOf(\n  expr: Expression | string,\n  search: string | Expression | Bytes\n): FunctionExpression {\n  return fieldOrExpression(expr).stringIndexOf(search);\n}\n\n/**\n * Creates an expression that repeats a string or byte array a specified number of times.\n *\n * @example\n * ```typescript\n * // Repeat the 'label' field 3 times\n * stringRepeat(\"label\", 3);\n * ```\n *\n * @param fieldName - The name of the field containing the string or byte array.\n * @param repetitions - The number of times to repeat the string or byte array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the repeated string or byte array.\n */\nexport function stringRepeat(\n  fieldName: string,\n  repetitions: number | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that repeats a string or byte array a specified number of times.\n *\n * @example\n * ```typescript\n * // Repeat the 'label' field 3 times\n * stringRepeat(field(\"label\"), 3);\n * ```\n *\n * @param expression - The expression representing the string or byte array.\n * @param repetitions - The number of times to repeat the string or byte array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the repeated string or byte array.\n */\nexport function stringRepeat(\n  expression: Expression,\n  repetitions: number | Expression\n): FunctionExpression;\nexport function stringRepeat(\n  expr: Expression | string,\n  repetitions: number | Expression\n): FunctionExpression {\n  return fieldOrExpression(expr).stringRepeat(repetitions);\n}\n\n/**\n * Creates an expression that replaces all occurrences of a substring or byte sequence with a replacement.\n *\n * @example\n * ```typescript\n * // Replace all occurrences of \"foo\" with \"bar\" in the 'text' field\n * stringReplaceAll(\"text\", \"foo\", \"bar\");\n * ```\n *\n * @param fieldName - The name of the field containing the string or byte array.\n * @param find - The substring or byte sequence to search for.\n * @param replacement - The replacement string or byte sequence.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the string or byte array with replacements.\n */\nexport function stringReplaceAll(\n  fieldName: string,\n  find: string | Expression | Bytes,\n  replacement: string | Expression | Bytes\n): FunctionExpression;\n\n/**\n * Creates an expression that replaces all occurrences of a substring or byte sequence with a replacement.\n *\n * @example\n * ```typescript\n * // Replace all occurrences of \"foo\" with \"bar\" in the 'text' field\n * stringReplaceAll(field(\"text\"), \"foo\", \"bar\");\n * ```\n *\n * @param expression - The expression representing the string or byte array.\n * @param find - The substring or byte sequence to search for.\n * @param replacement - The replacement string or byte sequence.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the string or byte array with replacements.\n */\nexport function stringReplaceAll(\n  expression: Expression,\n  find: string | Expression | Bytes,\n  replacement: string | Expression | Bytes\n): FunctionExpression;\nexport function stringReplaceAll(\n  expr: Expression | string,\n  find: string | Expression | Bytes,\n  replacement: string | Expression | Bytes\n): FunctionExpression {\n  return fieldOrExpression(expr).stringReplaceAll(find, replacement);\n}\n\n/**\n * Creates an expression that replaces the first occurrence of a substring or byte sequence with a replacement.\n *\n * @example\n * ```typescript\n * // Replace the first occurrence of \"foo\" with \"bar\" in the 'text' field\n * stringReplaceOne(\"text\", \"foo\", \"bar\");\n * ```\n *\n * @param fieldName - The name of the field containing the string or byte array.\n * @param find - The substring or byte sequence to search for.\n * @param replacement - The replacement string or byte sequence.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the string or byte array with the replacement.\n */\nexport function stringReplaceOne(\n  fieldName: string,\n  find: string | Expression | Bytes,\n  replacement: string | Expression | Bytes\n): FunctionExpression;\n\n/**\n * Creates an expression that replaces the first occurrence of a substring or byte sequence with a replacement.\n *\n * @example\n * ```typescript\n * // Replace the first occurrence of \"foo\" with \"bar\" in the 'text' field\n * stringReplaceOne(field(\"text\"), \"foo\", \"bar\");\n * ```\n *\n * @param expression - The expression representing the string or byte array.\n * @param find - The substring or byte sequence to search for.\n * @param replacement - The replacement string or byte sequence.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the string or byte array with the replacement.\n */\nexport function stringReplaceOne(\n  expression: Expression,\n  find: string | Expression | Bytes,\n  replacement: string | Expression | Bytes\n): FunctionExpression;\nexport function stringReplaceOne(\n  expr: Expression | string,\n  find: string | Expression | Bytes,\n  replacement: string | Expression | Bytes\n): FunctionExpression {\n  return fieldOrExpression(expr).stringReplaceOne(find, replacement);\n}\n\n/**\n *\n * Accesses a value from a map (object) field using the provided key.\n *\n * @example\n * ```typescript\n * // Get the 'city' value from the 'address' map field\n * mapGet(\"address\", \"city\");\n * ```\n *\n * @param fieldName - The field name of the map field.\n * @param subField - The key to access in the map.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the value associated with the given key in the map.\n */\nexport function mapGet(fieldName: string, subField: string): FunctionExpression;\n\n/**\n *\n * Accesses a value from a map (object) expression using the provided key.\n *\n * @example\n * ```typescript\n * // Get the 'city' value from the 'address' map field\n * mapGet(field(\"address\"), \"city\");\n * ```\n *\n * @param mapExpression - The expression representing the map.\n * @param subField - The key to access in the map.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the value associated with the given key in the map.\n */\nexport function mapGet(\n  mapExpression: Expression,\n  subField: string\n): FunctionExpression;\nexport function mapGet(\n  fieldOrExpr: string | Expression,\n  subField: string\n): FunctionExpression {\n  return fieldOrExpression(fieldOrExpr).mapGet(subField);\n}\n\n/**\n * Creates an expression that returns a new map with the specified entries added or updated.\n *\n * @remarks\n * This only performs shallow updates to the map. Setting a value to `null`\n * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`.\n *\n * @example\n * ```typescript\n * // Set the 'city' to 'San Francisco' in the 'address' map field\n * mapSet(\"address\", \"city\", \"San Francisco\");\n * ```\n *\n * @param mapField - The map field to set entries in.\n * @param key - The key to set. Must be a string or a constant string expression.\n * @param value - The value to set.\n * @param moreKeyValues - Additional key-value pairs to set.\n * @returns A new `Expression` representing the map with the entries set.\n */\nexport function mapSet(\n  mapField: string,\n  key: string | Expression,\n  value: unknown,\n  ...moreKeyValues: unknown[]\n): FunctionExpression;\n\n/**\n * Creates an expression that returns a new map with the specified entries added or updated.\n *\n * @remarks\n * This only performs shallow updates to the map. Setting a value to `null`\n * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`.\n *\n * @example\n * ```typescript\n * // Set the 'city' to \"San Francisco\"\n * mapSet(map({\"state\": \"California\"}), \"city\", \"San Francisco\");\n * ```\n *\n * @param mapExpression - The expression representing the map.\n * @param key - The key to set. Must be a string or a constant string expression.\n * @param value - The value to set.\n * @param moreKeyValues - Additional key-value pairs to set.\n * @returns A new `Expression` representing the map with the entries set.\n */\nexport function mapSet(\n  mapExpression: Expression,\n  key: string | Expression,\n  value: unknown,\n  ...moreKeyValues: unknown[]\n): FunctionExpression;\nexport function mapSet(\n  fieldOrExpr: string | Expression,\n  key: string | Expression,\n  value: unknown,\n  ...moreKeyValues: unknown[]\n): FunctionExpression {\n  return fieldOrExpression(fieldOrExpr).mapSet(key, value, ...moreKeyValues);\n}\n\n/**\n * Creates an expression that returns the keys of a map.\n *\n * @remarks\n * While the backend generally preserves insertion order, relying on the\n * order of the output array is not guaranteed and should be avoided.\n *\n * @example\n * ```typescript\n * // Get the keys of the 'address' map field\n * mapKeys(\"address\");\n * ```\n *\n * @param mapField - The map field to get the keys of.\n * @returns A new `Expression` representing the keys of the map.\n */\nexport function mapKeys(mapField: string): FunctionExpression;\n\n/**\n * Creates an expression that returns the keys of a map.\n *\n * @remarks\n * While the backend generally preserves insertion order, relying on the\n * order of the output array is not guaranteed and should be avoided.\n *\n * @example\n * ```typescript\n * // Get the keys of the map expression\n * mapKeys(map({\"city\": \"San Francisco\"}));\n * ```\n *\n * @param mapExpression - The expression representing the map to get the keys of.\n * @returns A new `Expression` representing the keys of the map.\n */\nexport function mapKeys(mapExpression: Expression): FunctionExpression;\nexport function mapKeys(fieldOrExpr: string | Expression): FunctionExpression {\n  return fieldOrExpression(fieldOrExpr).mapKeys();\n}\n\n/**\n * Creates an expression that returns the values of a map.\n *\n * @remarks\n * While the backend generally preserves insertion order, relying on the\n * order of the output array is not guaranteed and should be avoided.\n *\n * @example\n * ```typescript\n * // Get the values of the 'address' map field\n * mapValues(\"address\");\n * ```\n *\n * @param mapField - The map field to get the values of.\n * @returns A new `Expression` representing the values of the map.\n */\nexport function mapValues(mapField: string): FunctionExpression;\n\n/**\n * Creates an expression that returns the values of a map.\n *\n * @remarks\n * While the backend generally preserves insertion order, relying on the\n * order of the output array is not guaranteed and should be avoided.\n *\n * @example\n * ```typescript\n * // Get the values of the map expression\n * mapValues(map({\"city\": \"San Francisco\"}));\n * ```\n *\n * @param mapExpression - The expression representing the map to get the values of.\n * @returns A new `Expression` representing the values of the map.\n */\nexport function mapValues(mapExpression: Expression): FunctionExpression;\nexport function mapValues(\n  fieldOrExpr: string | Expression\n): FunctionExpression {\n  return fieldOrExpression(fieldOrExpr).mapValues();\n}\n\n/**\n * Creates an expression that returns the entries of a map as an array of maps,\n * where each map contains a `\"k\"` property for the key and a `\"v\"` property for the value.\n * For example: `[{ k: \"key1\", v: \"value1\" }, ...]`.\n *\n * @remarks\n * While the backend generally preserves insertion order, relying on the\n * order of the output array is not guaranteed and should be avoided.\n *\n * @example\n * ```typescript\n * // Get the entries of the 'address' map field\n * mapEntries(\"address\");\n * ```\n *\n * @param mapField - The map field to get the entries of.\n * @returns A new `Expression` representing the entries of the map.\n */\nexport function mapEntries(mapField: string): FunctionExpression;\n\n/**\n * Creates an expression that returns the entries of a map as an array of maps,\n * where each map contains a `\"k\"` property for the key and a `\"v\"` property for the value.\n * For example: `[{ k: \"key1\", v: \"value1\" }, ...]`.\n *\n * @remarks\n * While the backend generally preserves insertion order, relying on the\n * order of the output array is not guaranteed and should be avoided.\n *\n * @example\n * ```typescript\n * // Get the entries of the map expression\n * mapEntries(map({\"city\": \"San Francisco\"}));\n * ```\n *\n * @param mapExpression - The expression representing the map to get the entries of.\n * @returns A new `Expression` representing the entries of the map.\n */\nexport function mapEntries(mapExpression: Expression): FunctionExpression;\nexport function mapEntries(\n  fieldOrExpr: string | Expression\n): FunctionExpression {\n  return fieldOrExpression(fieldOrExpr).mapEntries();\n}\n\n/**\n * @public\n * Creates an expression that returns the value of a field from a document that results from the evaluation of the expression.\n *\n * @example\n * ```typescript\n * // Get the value of the \"city\" field in the \"address\" document.\n * getField(field(\"address\"), \"city\")\n * ```\n *\n * @param key The field to access in the document.\n * @returns A new `Expression` representing the value of the field in the document.\n */\nexport function getField(expression: Expression, key: string): Expression;\n/**\n * @public\n * Creates an expression that returns the value of a field from a document that results from the evaluation of the expression.\n *\n * @example\n * ```typescript\n * // Get the value of the key resulting from the \"addressField\" variable in the \"address\" document.\n * getField(field(\"address\", variable(\"addressField\")),\n * ```\n *\n * @param key The expression representing the key to access in the document.\n * @returns A new `Expression` representing the value of the field in the document.\n */\nexport function getField(\n  expression: Expression,\n  keyExpr: Expression\n): Expression;\n/**\n * @public\n * Creates an expression that returns the value of a field from the document with the given field name.\n *\n * @example\n * ```typescript\n * // Get the value of the \"city\" field in the \"address\" document.\n * getField(\"address\", \"city\")\n * ```\n *\n * @param key The field to access in the document.\n * @returns A new `Expression` representing the value of the field in the document.\n */\nexport function getField(fieldName: string, key: string): Expression;\n/**\n * @public\n * Creates an expression that returns the value of a field from the document with the given field name.\n *\n * @example\n * ```typescript\n * // Get the value of the \"city\" field in the \"address\" document.\n * getField(\"address\", variable(\"addressField\"))\n * ```\n *\n * @param key The field to access in the document.\n * @returns A new `Expression` representing the value of the field in the document.\n */\nexport function getField(fieldName: string, keyExpr: Expression): Expression;\nexport function getField(\n  fieldOrExpr: string | Expression,\n  keyOrExpr: string | Expression\n): Expression {\n  return fieldOrExpression(fieldOrExpr).getField(keyOrExpr);\n}\n\n/**\n * Creates an aggregation that counts the total number of stage inputs.\n *\n * @example\n * ```typescript\n * // Count the total number of input documents\n * countAll().as(\"totalDocument\");\n * ```\n *\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'countAll' aggregation.\n */\nexport function countAll(): AggregateFunction {\n  return AggregateFunction._create('count', [], 'count');\n}\n\n/**\n *\n * Creates an aggregation that counts the number of stage inputs with valid evaluations of the\n * provided expression.\n *\n * @example\n * ```typescript\n * // Count the number of items where the price is greater than 10\n * count(field(\"price\").greaterThan(10)).as(\"expensiveItemCount\");\n * ```\n *\n * @param expression - The expression to count.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'count' aggregation.\n */\nexport function count(expression: Expression): AggregateFunction;\n\n/**\n * Creates an aggregation that counts the number of stage inputs where the input field exists.\n *\n * @example\n * ```typescript\n * // Count the total number of products\n * count(\"productId\").as(\"totalProducts\");\n * ```\n *\n * @param fieldName - The name of the field to count.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'count' aggregation.\n */\nexport function count(fieldName: string): AggregateFunction;\nexport function count(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).count();\n}\n\n/**\n *\n * Creates an aggregation that calculates the sum of values from an expression across multiple\n * stage inputs.\n *\n * @example\n * ```typescript\n * // Calculate the total revenue from a set of orders\n * sum(field(\"orderAmount\")).as(\"totalRevenue\");\n * ```\n *\n * @param expression - The expression to sum up.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'sum' aggregation.\n */\nexport function sum(expression: Expression): AggregateFunction;\n\n/**\n *\n * Creates an aggregation that calculates the sum of a field's values across multiple stage\n * inputs.\n *\n * @example\n * ```typescript\n * // Calculate the total revenue from a set of orders\n * sum(\"orderAmount\").as(\"totalRevenue\");\n * ```\n *\n * @param fieldName - The name of the field containing numeric values to sum up.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'sum' aggregation.\n */\nexport function sum(fieldName: string): AggregateFunction;\nexport function sum(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).sum();\n}\n\n/**\n *\n * Creates an aggregation that calculates the average (mean) of values from an expression across\n * multiple stage inputs.\n *\n * @example\n * ```typescript\n * // Calculate the average age of users\n * average(field(\"age\")).as(\"averageAge\");\n * ```\n *\n * @param expression - The expression representing the values to average.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'average' aggregation.\n */\nexport function average(expression: Expression): AggregateFunction;\n\n/**\n *\n * Creates an aggregation that calculates the average (mean) of a field's values across multiple\n * stage inputs.\n *\n * @example\n * ```typescript\n * // Calculate the average age of users\n * average(\"age\").as(\"averageAge\");\n * ```\n *\n * @param fieldName - The name of the field containing numeric values to average.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'average' aggregation.\n */\nexport function average(fieldName: string): AggregateFunction;\nexport function average(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).average();\n}\n\n/**\n *\n * Creates an aggregation that finds the minimum value of an expression across multiple stage\n * inputs.\n *\n * @example\n * ```typescript\n * // Find the lowest price of all products\n * minimum(field(\"price\")).as(\"lowestPrice\");\n * ```\n *\n * @param expression - The expression to find the minimum value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'minimum' aggregation.\n */\nexport function minimum(expression: Expression): AggregateFunction;\n\n/**\n *\n * Creates an aggregation that finds the minimum value of a field across multiple stage inputs.\n *\n * @example\n * ```typescript\n * // Find the lowest price of all products\n * minimum(\"price\").as(\"lowestPrice\");\n * ```\n *\n * @param fieldName - The name of the field to find the minimum value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'minimum' aggregation.\n */\nexport function minimum(fieldName: string): AggregateFunction;\nexport function minimum(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).minimum();\n}\n\n/**\n *\n * Creates an aggregation that finds the maximum value of an expression across multiple stage\n * inputs.\n *\n * @example\n * ```typescript\n * // Find the highest score in a leaderboard\n * maximum(field(\"score\")).as(\"highestScore\");\n * ```\n *\n * @param expression - The expression to find the maximum value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'maximum' aggregation.\n */\nexport function maximum(expression: Expression): AggregateFunction;\n\n/**\n *\n * Creates an aggregation that finds the maximum value of a field across multiple stage inputs.\n *\n * @example\n * ```typescript\n * // Find the highest score in a leaderboard\n * maximum(\"score\").as(\"highestScore\");\n * ```\n *\n * @param fieldName - The name of the field to find the maximum value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'maximum' aggregation.\n */\nexport function maximum(fieldName: string): AggregateFunction;\nexport function maximum(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).maximum();\n}\n\n/**\n * Creates an aggregation that finds the first value of an expression across multiple stage\n * inputs.\n *\n * @example\n * ```typescript\n * // Find the first value of the 'rating' field\n * first(field(\"rating\")).as(\"firstRating\");\n * ```\n *\n * @param expression - The expression to find the first value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'first' aggregation.\n */\nexport function first(expression: Expression): AggregateFunction;\n\n/**\n * Creates an aggregation that finds the first value of a field across multiple stage inputs.\n *\n * @example\n * ```typescript\n * // Find the first value of the 'rating' field\n * first(\"rating\").as(\"firstRating\");\n * ```\n *\n * @param fieldName - The name of the field to find the first value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'first' aggregation.\n */\nexport function first(fieldName: string): AggregateFunction;\nexport function first(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).first();\n}\n\n/**\n * Creates an aggregation that finds the last value of an expression across multiple stage\n * inputs.\n *\n * @example\n * ```typescript\n * // Find the last value of the 'rating' field\n * last(field(\"rating\")).as(\"lastRating\");\n * ```\n *\n * @param expression - The expression to find the last value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'last' aggregation.\n */\nexport function last(expression: Expression): AggregateFunction;\n\n/**\n * Creates an aggregation that finds the last value of a field across multiple stage inputs.\n *\n * @example\n * ```typescript\n * // Find the last value of the 'rating' field\n * last(\"rating\").as(\"lastRating\");\n * ```\n *\n * @param fieldName - The name of the field to find the last value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'last' aggregation.\n */\nexport function last(fieldName: string): AggregateFunction;\nexport function last(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).last();\n}\n\n/**\n * Creates an aggregation that collects all values of an expression across multiple stage\n * inputs into an array.\n *\n * @remarks\n * If the expression resolves to an absent value, it is converted to `null`.\n * The order of elements in the output array is not stable and shouldn't be relied upon.\n *\n * @example\n * ```typescript\n * // Collect all tags from books into an array\n * arrayAgg(field(\"tags\")).as(\"allTags\");\n * ```\n *\n * @param expression - The expression to collect values from.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'array_agg' aggregation.\n */\nexport function arrayAgg(expression: Expression): AggregateFunction;\n\n/**\n * Creates an aggregation that collects all values of a field across multiple stage inputs\n * into an array.\n *\n * @remarks\n * If the expression resolves to an absent value, it is converted to `null`.\n * The order of elements in the output array is not stable and shouldn't be relied upon.\n *\n * @example\n * ```typescript\n * // Collect all tags from books into an array\n * arrayAgg(\"tags\").as(\"allTags\");\n * ```\n *\n * @param fieldName - The name of the field to collect values from.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'array_agg' aggregation.\n */\nexport function arrayAgg(fieldName: string): AggregateFunction;\nexport function arrayAgg(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).arrayAgg();\n}\n\n/**\n * Creates an aggregation that collects all distinct values of an expression across multiple stage\n * inputs into an array.\n *\n * @remarks\n * If the expression resolves to an absent value, it is converted to `null`.\n * The order of elements in the output array is not stable and shouldn't be relied upon.\n *\n * @example\n * ```typescript\n * // Collect all distinct tags from books into an array\n * arrayAggDistinct(field(\"tags\")).as(\"allDistinctTags\");\n * ```\n *\n * @param expression - The expression to collect values from.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'array_agg_distinct' aggregation.\n */\nexport function arrayAggDistinct(expression: Expression): AggregateFunction;\n\n/**\n * Creates an aggregation that collects all distinct values of a field across multiple stage inputs\n * into an array.\n *\n * @remarks\n * If the expression resolves to an absent value, it is converted to `null`.\n * The order of elements in the output array is not stable and shouldn't be relied upon.\n *\n * @example\n * ```typescript\n * // Collect all distinct tags from books into an array\n * arrayAggDistinct(\"tags\").as(\"allDistinctTags\");\n * ```\n *\n * @param fieldName - The name of the field to collect values from.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'array_agg_distinct' aggregation.\n */\nexport function arrayAggDistinct(fieldName: string): AggregateFunction;\nexport function arrayAggDistinct(\n  value: Expression | string\n): AggregateFunction {\n  return fieldOrExpression(value).arrayAggDistinct();\n}\n\n/**\n *\n * Calculates the Cosine distance between a field's vector value and a literal vector value.\n *\n * @example\n * ```typescript\n * // Calculate the Cosine distance between the 'location' field and a target location\n * cosineDistance(\"location\", [37.7749, -122.4194]);\n * ```\n *\n * @param fieldName - The name of the field containing the first vector.\n * @param vector - The other vector (as an array of doubles) or {@link VectorValue} to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Cosine distance between the two vectors.\n */\nexport function cosineDistance(\n  fieldName: string,\n  vector: number[] | VectorValue\n): FunctionExpression;\n\n/**\n *\n * Calculates the Cosine distance between a field's vector value and a vector expression.\n *\n * @example\n * ```typescript\n * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field\n * cosineDistance(\"userVector\", field(\"itemVector\"));\n * ```\n *\n * @param fieldName - The name of the field containing the first vector.\n * @param vectorExpression - The other vector (represented as an `Expression`) to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the cosine distance between the two vectors.\n */\nexport function cosineDistance(\n  fieldName: string,\n  vectorExpression: Expression\n): FunctionExpression;\n\n/**\n *\n * Calculates the Cosine distance between a vector expression and a vector literal.\n *\n * @example\n * ```typescript\n * // Calculate the cosine distance between the 'location' field and a target location\n * cosineDistance(field(\"location\"), [37.7749, -122.4194]);\n * ```\n *\n * @param vectorExpression - The first vector (represented as an `Expression`) to compare against.\n * @param vector - The other vector (as an array of doubles or VectorValue) to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the cosine distance between the two vectors.\n */\nexport function cosineDistance(\n  vectorExpression: Expression,\n  vector: number[] | VectorValue\n): FunctionExpression;\n\n/**\n *\n * Calculates the Cosine distance between two vector expressions.\n *\n * @example\n * ```typescript\n * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field\n * cosineDistance(field(\"userVector\"), field(\"itemVector\"));\n * ```\n *\n * @param vectorExpression - The first vector (represented as an `Expression`) to compare against.\n * @param otherVectorExpression - The other vector (represented as an `Expression`) to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the cosine distance between the two vectors.\n */\nexport function cosineDistance(\n  vectorExpression: Expression,\n  otherVectorExpression: Expression\n): FunctionExpression;\nexport function cosineDistance(\n  expr: Expression | string,\n  other: Expression | number[] | VectorValue\n): FunctionExpression {\n  const expr1 = fieldOrExpression(expr);\n  const expr2 = vectorToExpr(other);\n  return expr1.cosineDistance(expr2);\n}\n\n/**\n *\n * Calculates the dot product between a field's vector value and a double array.\n *\n * @example\n * ```typescript\n * // Calculate the dot product distance between a feature vector and a target vector\n * dotProduct(\"features\", [0.5, 0.8, 0.2]);\n * ```\n *\n * @param fieldName - The name of the field containing the first vector.\n * @param vector - The other vector (as an array of doubles or VectorValue) to calculate with.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the dot product between the two vectors.\n */\nexport function dotProduct(\n  fieldName: string,\n  vector: number[] | VectorValue\n): FunctionExpression;\n\n/**\n *\n * Calculates the dot product between a field's vector value and a vector expression.\n *\n * @example\n * ```typescript\n * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2'\n * dotProduct(\"docVector1\", field(\"docVector2\"));\n * ```\n *\n * @param fieldName - The name of the field containing the first vector.\n * @param vectorExpression - The other vector (represented as an `Expression`) to calculate with.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the dot product between the two vectors.\n */\nexport function dotProduct(\n  fieldName: string,\n  vectorExpression: Expression\n): FunctionExpression;\n\n/**\n *\n * Calculates the dot product between a vector expression and a double array.\n *\n * @example\n * ```typescript\n * // Calculate the dot product between a feature vector and a target vector\n * dotProduct(field(\"features\"), [0.5, 0.8, 0.2]);\n * ```\n *\n * @param vectorExpression - The first vector (represented as an `Expression`) to calculate with.\n * @param vector - The other vector (as an array of doubles or VectorValue) to calculate with.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the dot product between the two vectors.\n */\nexport function dotProduct(\n  vectorExpression: Expression,\n  vector: number[] | VectorValue\n): FunctionExpression;\n\n/**\n *\n * Calculates the dot product between two vector expressions.\n *\n * @example\n * ```typescript\n * // Calculate the dot product between two document vectors: 'docVector1' and 'docVector2'\n * dotProduct(field(\"docVector1\"), field(\"docVector2\"));\n * ```\n *\n * @param vectorExpression - The first vector (represented as an `Expression`) to calculate with.\n * @param otherVectorExpression - The other vector (represented as an `Expression`) to calculate with.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the dot product between the two vectors.\n */\nexport function dotProduct(\n  vectorExpression: Expression,\n  otherVectorExpression: Expression\n): FunctionExpression;\nexport function dotProduct(\n  expr: Expression | string,\n  other: Expression | number[] | VectorValue\n): FunctionExpression {\n  const expr1 = fieldOrExpression(expr);\n  const expr2 = vectorToExpr(other);\n  return expr1.dotProduct(expr2);\n}\n\n/**\n *\n * Calculates the Euclidean distance between a field's vector value and a double array.\n *\n * @example\n * ```typescript\n * // Calculate the Euclidean distance between the 'location' field and a target location\n * euclideanDistance(\"location\", [37.7749, -122.4194]);\n * ```\n *\n * @param fieldName - The name of the field containing the first vector.\n * @param vector - The other vector (as an array of doubles or VectorValue) to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Euclidean distance between the two vectors.\n */\nexport function euclideanDistance(\n  fieldName: string,\n  vector: number[] | VectorValue\n): FunctionExpression;\n\n/**\n *\n * Calculates the Euclidean distance between a field's vector value and a vector expression.\n *\n * @example\n * ```typescript\n * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB'\n * euclideanDistance(\"pointA\", field(\"pointB\"));\n * ```\n *\n * @param fieldName - The name of the field containing the first vector.\n * @param vectorExpression - The other vector (represented as an `Expression`) to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Euclidean distance between the two vectors.\n */\nexport function euclideanDistance(\n  fieldName: string,\n  vectorExpression: Expression\n): FunctionExpression;\n\n/**\n *\n * Calculates the Euclidean distance between a vector expression and a double array.\n *\n * @example\n * ```typescript\n * // Calculate the Euclidean distance between the 'location' field and a target location\n *\n * euclideanDistance(field(\"location\"), [37.7749, -122.4194]);\n * ```\n *\n * @param vectorExpression - The first vector (represented as an `Expression`) to compare against.\n * @param vector - The other vector (as an array of doubles or VectorValue) to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Euclidean distance between the two vectors.\n */\nexport function euclideanDistance(\n  vectorExpression: Expression,\n  vector: number[] | VectorValue\n): FunctionExpression;\n\n/**\n *\n * Calculates the Euclidean distance between two vector expressions.\n *\n * @example\n * ```typescript\n * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB'\n * euclideanDistance(field(\"pointA\"), field(\"pointB\"));\n * ```\n *\n * @param vectorExpression - The first vector (represented as an `Expression`) to compare against.\n * @param otherVectorExpression - The other vector (represented as an `Expression`) to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Euclidean distance between the two vectors.\n */\nexport function euclideanDistance(\n  vectorExpression: Expression,\n  otherVectorExpression: Expression\n): FunctionExpression;\nexport function euclideanDistance(\n  expr: Expression | string,\n  other: Expression | number[] | VectorValue\n): FunctionExpression {\n  const expr1 = fieldOrExpression(expr);\n  const expr2 = vectorToExpr(other);\n  return expr1.euclideanDistance(expr2);\n}\n\n/**\n *\n * Creates an expression that calculates the length of a Firestore Vector.\n *\n * @example\n * ```typescript\n * // Get the vector length (dimension) of the field 'embedding'.\n * vectorLength(field(\"embedding\"));\n * ```\n *\n * @param vectorExpression - The expression representing the Firestore Vector.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the array.\n */\nexport function vectorLength(vectorExpression: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that calculates the length of a Firestore Vector represented by a field.\n *\n * @example\n * ```typescript\n * // Get the vector length (dimension) of the field 'embedding'.\n * vectorLength(\"embedding\");\n * ```\n *\n * @param fieldName - The name of the field representing the Firestore Vector.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the array.\n */\nexport function vectorLength(fieldName: string): FunctionExpression;\nexport function vectorLength(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).vectorLength();\n}\n\n/**\n *\n * Creates an expression that interprets an expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n * and returns a timestamp.\n *\n * @example\n * ```typescript\n * // Interpret the 'microseconds' field as microseconds since epoch.\n * unixMicrosToTimestamp(field(\"microseconds\"));\n * ```\n *\n * @param expr - The expression representing the number of microseconds since epoch.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n */\nexport function unixMicrosToTimestamp(expr: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that interprets a field's value as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n * and returns a timestamp.\n *\n * @example\n * ```typescript\n * // Interpret the 'microseconds' field as microseconds since epoch.\n * unixMicrosToTimestamp(\"microseconds\");\n * ```\n *\n * @param fieldName - The name of the field representing the number of microseconds since epoch.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n */\nexport function unixMicrosToTimestamp(fieldName: string): FunctionExpression;\nexport function unixMicrosToTimestamp(\n  expr: Expression | string\n): FunctionExpression {\n  return fieldOrExpression(expr).unixMicrosToTimestamp();\n}\n\n/**\n *\n * Creates an expression that converts a timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n *\n * @example\n * ```typescript\n * // Convert the 'timestamp' field to microseconds since epoch.\n * timestampToUnixMicros(field(\"timestamp\"));\n * ```\n *\n * @param expr - The expression representing the timestamp.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of microseconds since epoch.\n */\nexport function timestampToUnixMicros(expr: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that converts a timestamp field to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n *\n * @example\n * ```typescript\n * // Convert the 'timestamp' field to microseconds since epoch.\n * timestampToUnixMicros(\"timestamp\");\n * ```\n *\n * @param fieldName - The name of the field representing the timestamp.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of microseconds since epoch.\n */\nexport function timestampToUnixMicros(fieldName: string): FunctionExpression;\nexport function timestampToUnixMicros(\n  expr: Expression | string\n): FunctionExpression {\n  return fieldOrExpression(expr).timestampToUnixMicros();\n}\n\n/**\n *\n * Creates an expression that interprets an expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n * and returns a timestamp.\n *\n * @example\n * ```typescript\n * // Interpret the 'milliseconds' field as milliseconds since epoch.\n * unixMillisToTimestamp(field(\"milliseconds\"));\n * ```\n *\n * @param expr - The expression representing the number of milliseconds since epoch.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n */\nexport function unixMillisToTimestamp(expr: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that interprets a field's value as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n * and returns a timestamp.\n *\n * @example\n * ```typescript\n * // Interpret the 'milliseconds' field as milliseconds since epoch.\n * unixMillisToTimestamp(\"milliseconds\");\n * ```\n *\n * @param fieldName - The name of the field representing the number of milliseconds since epoch.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n */\nexport function unixMillisToTimestamp(fieldName: string): FunctionExpression;\nexport function unixMillisToTimestamp(\n  expr: Expression | string\n): FunctionExpression {\n  const normalizedExpr = fieldOrExpression(expr);\n  return normalizedExpr.unixMillisToTimestamp();\n}\n\n/**\n *\n * Creates an expression that converts a timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n *\n * @example\n * ```typescript\n * // Convert the 'timestamp' field to milliseconds since epoch.\n * timestampToUnixMillis(field(\"timestamp\"));\n * ```\n *\n * @param expr - The expression representing the timestamp.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of milliseconds since epoch.\n */\nexport function timestampToUnixMillis(expr: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that converts a timestamp field to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n *\n * @example\n * ```typescript\n * // Convert the 'timestamp' field to milliseconds since epoch.\n * timestampToUnixMillis(\"timestamp\");\n * ```\n *\n * @param fieldName - The name of the field representing the timestamp.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of milliseconds since epoch.\n */\nexport function timestampToUnixMillis(fieldName: string): FunctionExpression;\nexport function timestampToUnixMillis(\n  expr: Expression | string\n): FunctionExpression {\n  const normalizedExpr = fieldOrExpression(expr);\n  return normalizedExpr.timestampToUnixMillis();\n}\n\n/**\n *\n * Creates an expression that interprets an expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n * and returns a timestamp.\n *\n * @example\n * ```typescript\n * // Interpret the 'seconds' field as seconds since epoch.\n * unixSecondsToTimestamp(field(\"seconds\"));\n * ```\n *\n * @param expr - The expression representing the number of seconds since epoch.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n */\nexport function unixSecondsToTimestamp(expr: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that interprets a field's value as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n * and returns a timestamp.\n *\n * @example\n * ```typescript\n * // Interpret the 'seconds' field as seconds since epoch.\n * unixSecondsToTimestamp(\"seconds\");\n * ```\n *\n * @param fieldName - The name of the field representing the number of seconds since epoch.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n */\nexport function unixSecondsToTimestamp(fieldName: string): FunctionExpression;\nexport function unixSecondsToTimestamp(\n  expr: Expression | string\n): FunctionExpression {\n  const normalizedExpr = fieldOrExpression(expr);\n  return normalizedExpr.unixSecondsToTimestamp();\n}\n\n/**\n *\n * Creates an expression that converts a timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n *\n * @example\n * ```typescript\n * // Convert the 'timestamp' field to seconds since epoch.\n * timestampToUnixSeconds(field(\"timestamp\"));\n * ```\n *\n * @param expr - The expression representing the timestamp.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of seconds since epoch.\n */\nexport function timestampToUnixSeconds(expr: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that converts a timestamp field to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n *\n * @example\n * ```typescript\n * // Convert the 'timestamp' field to seconds since epoch.\n * timestampToUnixSeconds(\"timestamp\");\n * ```\n *\n * @param fieldName - The name of the field representing the timestamp.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of seconds since epoch.\n */\nexport function timestampToUnixSeconds(fieldName: string): FunctionExpression;\nexport function timestampToUnixSeconds(\n  expr: Expression | string\n): FunctionExpression {\n  const normalizedExpr = fieldOrExpression(expr);\n  return normalizedExpr.timestampToUnixSeconds();\n}\n\n/**\n *\n * Creates an expression that adds a specified amount of time to a timestamp.\n *\n * @example\n * ```typescript\n * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field.\n * timestampAdd(field(\"timestamp\"), field(\"unit\"), field(\"amount\"));\n * ```\n *\n * @param timestamp - The expression representing the timestamp.\n * @param unit - The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'.\n * @param amount - The expression evaluates to amount of the unit.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n */\nexport function timestampAdd(\n  timestamp: Expression,\n  unit: Expression,\n  amount: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that adds a specified amount of time to a timestamp.\n *\n * @example\n * ```typescript\n * // Add 1 day to the 'timestamp' field.\n * timestampAdd(field(\"timestamp\"), \"day\", 1);\n * ```\n *\n * @param timestamp - The expression representing the timestamp.\n * @param unit - The unit of time to add (e.g., \"day\", \"hour\").\n * @param amount - The amount of time to add.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n */\nexport function timestampAdd(\n  timestamp: Expression,\n  unit: TimeUnit,\n  amount: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that adds a specified amount of time to a timestamp represented by a field.\n *\n * @example\n * ```typescript\n * // Add 1 day to the 'timestamp' field.\n * timestampAdd(\"timestamp\", \"day\", 1);\n * ```\n *\n * @param fieldName - The name of the field representing the timestamp.\n * @param unit - The unit of time to add (e.g., \"day\", \"hour\").\n * @param amount - The amount of time to add.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n */\nexport function timestampAdd(\n  fieldName: string,\n  unit: TimeUnit,\n  amount: number\n): FunctionExpression;\nexport function timestampAdd(\n  timestamp: Expression | string,\n  unit: TimeUnit | Expression,\n  amount: Expression | number\n): FunctionExpression {\n  const normalizedTimestamp = fieldOrExpression(timestamp);\n  const normalizedUnit = valueToDefaultExpr(unit);\n  const normalizedAmount = valueToDefaultExpr(amount);\n  return normalizedTimestamp.timestampAdd(normalizedUnit, normalizedAmount);\n}\n\n/**\n *\n * Creates an expression that subtracts a specified amount of time from a timestamp.\n *\n * @example\n * ```typescript\n * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field.\n * timestampSubtract(field(\"timestamp\"), field(\"unit\"), field(\"amount\"));\n * ```\n *\n * @param timestamp - The expression representing the timestamp.\n * @param unit - The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'.\n * @param amount - The expression evaluates to amount of the unit.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n */\nexport function timestampSubtract(\n  timestamp: Expression,\n  unit: Expression,\n  amount: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that subtracts a specified amount of time from a timestamp.\n *\n * @example\n * ```typescript\n * // Subtract 1 day from the 'timestamp' field.\n * timestampSubtract(field(\"timestamp\"), \"day\", 1);\n * ```\n *\n * @param timestamp - The expression representing the timestamp.\n * @param unit - The unit of time to subtract (e.g., \"day\", \"hour\").\n * @param amount - The amount of time to subtract.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n */\nexport function timestampSubtract(\n  timestamp: Expression,\n  unit: TimeUnit,\n  amount: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that subtracts a specified amount of time from a timestamp represented by a field.\n *\n * @example\n * ```typescript\n * // Subtract 1 day from the 'timestamp' field.\n * timestampSubtract(\"timestamp\", \"day\", 1);\n * ```\n *\n * @param fieldName - The name of the field representing the timestamp.\n * @param unit - The unit of time to subtract (e.g., \"day\", \"hour\").\n * @param amount - The amount of time to subtract.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n */\nexport function timestampSubtract(\n  fieldName: string,\n  unit: TimeUnit,\n  amount: number\n): FunctionExpression;\nexport function timestampSubtract(\n  timestamp: Expression | string,\n  unit: TimeUnit | Expression,\n  amount: Expression | number\n): FunctionExpression {\n  const normalizedTimestamp = fieldOrExpression(timestamp);\n  const normalizedUnit = valueToDefaultExpr(unit);\n  const normalizedAmount = valueToDefaultExpr(amount);\n  return normalizedTimestamp.timestampSubtract(\n    normalizedUnit,\n    normalizedAmount\n  );\n}\n\n/**\n *\n * Creates an expression that evaluates to the current server timestamp.\n *\n * @example\n * ```typescript\n * // Get the current server timestamp\n * currentTimestamp()\n * ```\n *\n * @returns A new Expression representing the current server timestamp.\n */\nexport function currentTimestamp(): FunctionExpression {\n  return new FunctionExpression('current_timestamp', [], 'currentTimestamp');\n}\n\n/**\n *\n * Creates an expression that performs a logical 'AND' operation on multiple filter conditions.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is greater than 18 AND the 'city' field is \"London\" AND\n * // the 'status' field is \"active\"\n * const condition = and(greaterThan(\"age\", 18), equal(\"city\", \"London\"), equal(\"status\", \"active\"));\n * ```\n *\n * @param first - The first filter condition.\n * @param second - The second filter condition.\n * @param more - Additional filter conditions to 'AND' together.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical 'AND' operation.\n */\nexport function and(\n  first: BooleanExpression,\n  second: BooleanExpression,\n  ...more: BooleanExpression[]\n): BooleanExpression {\n  return new FunctionExpression(\n    'and',\n    [first, second, ...more],\n    'and'\n  ).asBoolean();\n}\n\n/**\n *\n * Creates an expression that performs a logical 'OR' operation on multiple filter conditions.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is greater than 18 OR the 'city' field is \"London\" OR\n * // the 'status' field is \"active\"\n * const condition = or(greaterThan(\"age\", 18), equal(\"city\", \"London\"), equal(\"status\", \"active\"));\n * ```\n *\n * @param first - The first filter condition.\n * @param second - The second filter condition.\n * @param more - Additional filter conditions to 'OR' together.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical 'OR' operation.\n */\nexport function or(\n  first: BooleanExpression,\n  second: BooleanExpression,\n  ...more: BooleanExpression[]\n): BooleanExpression {\n  return new FunctionExpression(\n    'or',\n    [first, second, ...more],\n    'xor'\n  ).asBoolean();\n}\n\n/**\n *\n * Creates an expression that performs a logical 'NOR' operation on multiple filter conditions.\n *\n * @example\n * ```typescript\n * // Check if neither the 'age' field is greater than 18 nor the 'city' field is \"London\"\n * const condition = nor(\n *   greaterThan(\"age\", 18),\n *   equal(\"city\", \"London\")\n * );\n * ```\n *\n * @param first - The first filter condition.\n * @param second - The second filter condition.\n * @param more - Additional filter conditions to 'NOR' together.\n * @returns A new {@link @firebase/firestore/pipelines#BooleanExpression} representing the logical 'NOR' operation.\n */\nexport function nor(\n  first: BooleanExpression,\n  second: BooleanExpression,\n  ...more: BooleanExpression[]\n): BooleanExpression {\n  return new FunctionExpression(\n    'nor',\n    [first, second, ...more],\n    'nor'\n  ).asBoolean();\n}\n\n/**\n * Creates an expression that returns the value of the base expression raised to the power of the exponent expression.\n *\n * @example\n * ```typescript\n * // Raise the value of the 'base' field to the power of the 'exponent' field.\n * pow(field(\"base\"), field(\"exponent\"));\n * ```\n *\n * @param base - The expression to raise to the power of the exponent.\n * @param exponent - The expression to raise the base to the power of.\n * @returns A new `Expression` representing the power operation.\n */\nexport function pow(base: Expression, exponent: Expression): FunctionExpression;\n\n/**\n * Creates an expression that returns the value of the base expression raised to the power of the exponent.\n *\n * @example\n * ```typescript\n * // Raise the value of the 'base' field to the power of 2.\n * pow(field(\"base\"), 2);\n * ```\n *\n * @param base - The expression to raise to the power of the exponent.\n * @param exponent - The constant value to raise the base to the power of.\n * @returns A new `Expression` representing the power operation.\n */\nexport function pow(base: Expression, exponent: number): FunctionExpression;\n\n/**\n * Creates an expression that returns the value of the base field raised to the power of the exponent expression.\n *\n * @example\n * ```typescript\n * // Raise the value of the 'base' field to the power of the 'exponent' field.\n * pow(\"base\", field(\"exponent\"));\n * ```\n *\n * @param base - The name of the field to raise to the power of the exponent.\n * @param exponent - The expression to raise the base to the power of.\n * @returns A new `Expression` representing the power operation.\n */\nexport function pow(base: string, exponent: Expression): FunctionExpression;\n\n/**\n * Creates an expression that returns the value of the base field raised to the power of the exponent.\n *\n * @example\n * ```typescript\n * // Raise the value of the 'base' field to the power of 2.\n * pow(\"base\", 2);\n * ```\n *\n * @param base - The name of the field to raise to the power of the exponent.\n * @param exponent - The constant value to raise the base to the power of.\n * @returns A new `Expression` representing the power operation.\n */\nexport function pow(base: string, exponent: number): FunctionExpression;\nexport function pow(\n  base: Expression | string,\n  exponent: Expression | number\n): FunctionExpression {\n  return fieldOrExpression(base).pow(exponent as number);\n}\n\n/**\n *\n * Creates an expression that generates a random number between 0.0 and 1.0 but not including 1.0.\n *\n * @example\n * ```typescript\n * // Generate a random number between 0.0 and 1.0.\n * rand();\n * ```\n *\n * @returns A new `Expression` representing the rand operation.\n */\nexport function rand(): FunctionExpression {\n  return new FunctionExpression('rand', [], 'rand');\n}\n\n/**\n * Creates an expression that rounds a numeric value to the nearest whole number.\n *\n * @example\n * ```typescript\n * // Round the value of the 'price' field.\n * round(\"price\");\n * ```\n *\n * @param fieldName - The name of the field to round.\n * @returns A new `Expression` representing the rounded value.\n */\nexport function round(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that rounds a numeric value to the nearest whole number.\n *\n * @example\n * ```typescript\n * // Round the value of the 'price' field.\n * round(field(\"price\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which will be rounded.\n * @returns A new `Expression` representing the rounded value.\n */\nexport function round(expression: Expression): FunctionExpression;\n\n/**\n * Creates an expression that rounds a numeric value to the specified number of decimal places.\n *\n * @example\n * ```typescript\n * // Round the value of the 'price' field to two decimal places.\n * round(\"price\", 2);\n * ```\n *\n * @param fieldName - The name of the field to round.\n * @param decimalPlaces - A constant or expression specifying the rounding precision in decimal places.\n * @returns A new `Expression` representing the rounded value.\n */\nexport function round(\n  fieldName: string,\n  decimalPlaces: number | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that rounds a numeric value to the specified number of decimal places.\n *\n * @example\n * ```typescript\n * // Round the value of the 'price' field to two decimal places.\n * round(field(\"price\"), constant(2));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which will be rounded.\n * @param decimalPlaces - A constant or expression specifying the rounding precision in decimal places.\n * @returns A new `Expression` representing the rounded value.\n */\nexport function round(\n  expression: Expression,\n  decimalPlaces: number | Expression\n): FunctionExpression;\nexport function round(\n  expr: Expression | string,\n  decimalPlaces?: number | Expression\n): FunctionExpression {\n  if (decimalPlaces === undefined) {\n    return fieldOrExpression(expr).round();\n  } else {\n    return fieldOrExpression(expr).round(valueToDefaultExpr(decimalPlaces));\n  }\n}\n\n/**\n * Creates an expression that truncates the numeric value of a field to an integer.\n *\n * @example\n * ```typescript\n * // Truncate the value of the 'rating' field\n * trunc(\"rating\");\n * ```\n *\n * @param fieldName - The name of the field containing the number to truncate.\n * @returns A new `Expression` representing the truncated value.\n */\nexport function trunc(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that truncates the numeric value of an expression to an integer.\n *\n * @example\n * ```typescript\n * // Truncate the value of the 'rating' field.\n * trunc(field(\"rating\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which will be truncated.\n * @returns A new `Expression` representing the truncated value.\n */\nexport function trunc(expression: Expression): FunctionExpression;\n\n/**\n * Creates an expression that truncates a numeric expression to the specified number of decimal places.\n *\n * @example\n * ```typescript\n * // Truncate the value of the 'rating' field to two decimal places.\n * trunc(\"rating\", 2);\n * ```\n *\n * @param fieldName - The name of the field to truncate.\n * @param decimalPlaces - A constant or expression specifying the truncation precision in decimal places.\n * @returns A new `Expression` representing the truncated value.\n */\nexport function trunc(\n  fieldName: string,\n  decimalPlaces: number | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that truncates a numeric value to the specified number of decimal places.\n *\n * @example\n * ```typescript\n * // Truncate the value of the 'rating' field to two decimal places.\n * trunc(field(\"rating\"), constant(2));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which will be truncated.\n * @param decimalPlaces - A constant or expression specifying the truncation precision in decimal places.\n * @returns A new `Expression` representing the truncated value.\n */\nexport function trunc(\n  expression: Expression,\n  decimalPlaces: number | Expression\n): FunctionExpression;\nexport function trunc(\n  expr: Expression | string,\n  decimalPlaces?: number | Expression\n): FunctionExpression {\n  if (decimalPlaces === undefined) {\n    return fieldOrExpression(expr).trunc();\n  } else {\n    return fieldOrExpression(expr).trunc(valueToDefaultExpr(decimalPlaces));\n  }\n}\n\n/**\n * Creates an expression that returns the collection ID from a path.\n *\n * @example\n * ```typescript\n * // Get the collection ID from a path.\n * collectionId(\"__name__\");\n * ```\n *\n * @param fieldName - The name of the field to get the collection ID from.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the collectionId operation.\n */\nexport function collectionId(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that returns the collection ID from a path.\n *\n * @example\n * ```typescript\n * // Get the collection ID from a path.\n * collectionId(field(\"__name__\"));\n * ```\n *\n * @param expression - An expression evaluating to a path, which the collection ID will be extracted from.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the collectionId operation.\n */\nexport function collectionId(expression: Expression): FunctionExpression;\nexport function collectionId(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).collectionId();\n}\n\n/**\n * Creates an expression that calculates the length of a string, array, map, vector, or bytes.\n *\n * @example\n * ```typescript\n * // Get the length of the 'name' field.\n * length(\"name\");\n *\n * // Get the number of items in the 'cart' array.\n * length(\"cart\");\n * ```\n *\n * @param fieldName - The name of the field to calculate the length of.\n * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes.\n */\nexport function length(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that calculates the length of a string, array, map, vector, or bytes.\n *\n * @example\n * ```typescript\n * // Get the length of the 'name' field.\n * length(field(\"name\"));\n *\n * // Get the number of items in the 'cart' array.\n * length(field(\"cart\"));\n * ```\n *\n * @param expression - An expression evaluating to a string, array, map, vector, or bytes, which the length will be calculated for.\n * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes.\n */\nexport function length(expression: Expression): FunctionExpression;\nexport function length(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).length();\n}\n\n/**\n * Creates an expression that computes the natural logarithm of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the natural logarithm of the 'value' field.\n * ln(\"value\");\n * ```\n *\n * @param fieldName - The name of the field to compute the natural logarithm of.\n * @returns A new `Expression` representing the natural logarithm of the numeric value.\n */\nexport function ln(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that computes the natural logarithm of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the natural logarithm of the 'value' field.\n * ln(field(\"value\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which the natural logarithm will be computed for.\n * @returns A new `Expression` representing the natural logarithm of the numeric value.\n */\nexport function ln(expression: Expression): FunctionExpression;\nexport function ln(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).ln();\n}\n\n/**\n * Creates an expression that computes the logarithm of an expression to a given base.\n *\n * @example\n * ```typescript\n * // Compute the logarithm of the 'value' field with base 10.\n * log(field(\"value\"), 10);\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which the logarithm will be computed for.\n * @param base - The base of the logarithm.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logarithm of the numeric value.\n */\nexport function log(expression: Expression, base: number): FunctionExpression;\n/**\n * Creates an expression that computes the logarithm of an expression to a given base.\n *\n * @example\n * ```typescript\n * // Compute the logarithm of the 'value' field with the base in the 'base' field.\n * log(field(\"value\"), field(\"base\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which the logarithm will be computed for.\n * @param base - The base of the logarithm.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logarithm of the numeric value.\n */\nexport function log(\n  expression: Expression,\n  base: Expression\n): FunctionExpression;\n/**\n * Creates an expression that computes the logarithm of a field to a given base.\n *\n * @example\n * ```typescript\n * // Compute the logarithm of the 'value' field with base 10.\n * log(\"value\", 10);\n * ```\n *\n * @param fieldName - The name of the field to compute the logarithm of.\n * @param base - The base of the logarithm.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logarithm of the numeric value.\n */\nexport function log(fieldName: string, base: number): FunctionExpression;\n/**\n * Creates an expression that computes the logarithm of a field to a given base.\n *\n * @example\n * ```typescript\n * // Compute the logarithm of the 'value' field with the base in the 'base' field.\n * log(\"value\", field(\"base\"));\n * ```\n *\n * @param fieldName - The name of the field to compute the logarithm of.\n * @param base - The base of the logarithm.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logarithm of the numeric value.\n */\nexport function log(fieldName: string, base: Expression): FunctionExpression;\nexport function log(\n  expr: Expression | string,\n  base: number | Expression\n): FunctionExpression {\n  return new FunctionExpression('log', [\n    fieldOrExpression(expr),\n    valueToDefaultExpr(base)\n  ]);\n}\n\n/**\n * Creates an expression that computes the square root of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the square root of the 'value' field.\n * sqrt(field(\"value\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which the square root will be computed for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the square root of the numeric value.\n */\nexport function sqrt(expression: Expression): FunctionExpression;\n/**\n * Creates an expression that computes the square root of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the square root of the 'value' field.\n * sqrt(\"value\");\n * ```\n *\n * @param fieldName - The name of the field to compute the square root of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the square root of the numeric value.\n */\nexport function sqrt(fieldName: string): FunctionExpression;\nexport function sqrt(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).sqrt();\n}\n\n/**\n * Creates an expression that reverses a string.\n *\n * @example\n * ```typescript\n * // Reverse the value of the 'myString' field.\n * stringReverse(field(\"myString\"));\n * ```\n *\n * @param stringExpression - An expression evaluating to a string value, which will be reversed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.\n */\nexport function stringReverse(stringExpression: Expression): FunctionExpression;\n\n/**\n * Creates an expression that reverses a string value in the specified field.\n *\n * @example\n * ```typescript\n * // Reverse the value of the 'myString' field.\n * stringReverse(\"myString\");\n * ```\n *\n * @param field - The name of the field representing the string to reverse.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.\n */\nexport function stringReverse(field: string): FunctionExpression;\nexport function stringReverse(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).stringReverse();\n}\n\n/**\n * Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed.\n *\n * @example\n * ```typescript\n * // Concatenate the 'firstName' and 'lastName' fields with a space in between.\n * concat(field(\"firstName\"), \" \", field(\"lastName\"))\n * ```\n *\n * @param first - The first expressions to concatenate.\n * @param second - The second literal or expression to concatenate.\n * @param others - Additional literals or expressions to concatenate.\n * @returns A new `Expression` representing the concatenation.\n */\nexport function concat(\n  first: Expression,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\n\n/**\n * Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed.\n *\n * @example\n * ```typescript\n * // Concatenate a field with a literal string.\n * concat(field(\"firstName\"), \"Doe\")\n * ```\n *\n * @param fieldName - The name of a field to concatenate.\n * @param second - The second literal or expression to concatenate.\n * @param others - Additional literal or expressions to concatenate.\n * @returns A new `Expression` representing the concatenation.\n */\nexport function concat(\n  fieldName: string,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\n\nexport function concat(\n  fieldNameOrExpression: string | Expression,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression {\n  return new FunctionExpression('concat', [\n    fieldOrExpression(fieldNameOrExpression),\n    valueToDefaultExpr(second),\n    ...others.map(valueToDefaultExpr)\n  ]);\n}\n\n/**\n * Creates an expression that computes the absolute value of a numeric value.\n *\n * @param expr - The expression to compute the absolute value of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the absolute value of the numeric value.\n */\nexport function abs(expr: Expression): FunctionExpression;\n\n/**\n * Creates an expression that computes the absolute value of a numeric value.\n *\n * @param fieldName - The field to compute the absolute value of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the absolute value of the numeric value.\n */\nexport function abs(fieldName: string): FunctionExpression;\nexport function abs(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).abs();\n}\n\n/**\n * Creates an expression that returns the `elseExpr` argument if `ifExpr` is absent, else return\n * the result of the `ifExpr` argument evaluation.\n *\n * @example\n * ```typescript\n * // Returns the value of the optional field 'optional_field', or returns 'default_value'\n * // if the field is absent.\n * ifAbsent(field(\"optional_field\"), constant(\"default_value\"))\n * ```\n *\n * @param ifExpr - The expression to check for absence.\n * @param elseExpr - The expression that will be evaluated and returned if [ifExpr] is absent.\n * @returns A new Expression representing the ifAbsent operation.\n */\nexport function ifAbsent(ifExpr: Expression, elseExpr: Expression): Expression;\n\n/**\n * Creates an expression that returns the `elseValue` argument if `ifExpr` is absent, else\n * return the result of the `ifExpr` argument evaluation.\n *\n * @example\n * ```typescript\n * // Returns the value of the optional field 'optional_field', or returns 'default_value'\n * // if the field is absent.\n * ifAbsent(field(\"optional_field\"), \"default_value\")\n * ```\n *\n * @param ifExpr - The expression to check for absence.\n * @param elseValue - The value that will be returned if `ifExpr` evaluates to an absent value.\n * @returns A new [Expression] representing the ifAbsent operation.\n */\nexport function ifAbsent(ifExpr: Expression, elseValue: unknown): Expression;\n\n/**\n * Creates an expression that returns the `elseExpr` argument if `ifFieldName` is absent, else\n * return the value of the field.\n *\n * @example\n * ```typescript\n * // Returns the value of the optional field 'optional_field', or returns the value of\n * // 'default_field' if 'optional_field' is absent.\n * ifAbsent(\"optional_field\", field(\"default_field\"))\n * ```\n *\n * @param ifFieldName - The field to check for absence.\n * @param elseExpr - The expression that will be evaluated and returned if `ifFieldName` is\n * absent.\n * @returns A new Expression representing the ifAbsent operation.\n */\nexport function ifAbsent(ifFieldName: string, elseExpr: Expression): Expression;\n\n/**\n * Creates an expression that returns the `elseValue` argument if `ifFieldName` is absent, else\n * return the value of the field.\n *\n * @example\n * ```typescript\n * // Returns the value of the optional field 'optional_field', or returns 'default_value'\n * // if the field is absent.\n * ifAbsent(\"optional_field\", \"default_value\")\n * ```\n *\n * @param ifFieldName - The field to check for absence.\n * @param elseValue - The value that will be returned if [ifFieldName] is absent.\n * @returns A new Expression representing the ifAbsent operation.\n */\nexport function ifAbsent(\n  ifFieldName: string | Expression,\n  elseValue: Expression | unknown\n): Expression;\nexport function ifAbsent(\n  fieldNameOrExpression: string | Expression,\n  elseValue: Expression | unknown\n): Expression {\n  return fieldOrExpression(fieldNameOrExpression).ifAbsent(\n    valueToDefaultExpr(elseValue)\n  );\n}\n\n/**\n * Creates an expression that returns the `elseExpr` argument if `ifExpr` is null, else\n * return the result of the `ifExpr` argument evaluation.\n *\n * @remarks\n * This function provides a fallback for both absent and explicit null values. In contrast,\n * `ifAbsent()` only triggers for missing fields.\n *\n * @example\n * ```typescript\n * // Returns the user's preferred name, or if that is null, returns their full name.\n * ifNull(field(\"preferredName\"), field(\"fullName\"))\n * ```\n *\n * @param ifExpr - The expression to check for null.\n * @param elseExpr - The expression that will be evaluated and returned if `ifExpr` is null.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ifNull operation.\n */\nexport function ifNull(\n  ifExpr: Expression,\n  elseExpr: Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that returns the `elseValue` argument if `ifExpr` is null, else\n * return the result of the `ifExpr` argument evaluation.\n *\n * @remarks\n * This function provides a fallback for both absent and explicit null values. In contrast,\n * `ifAbsent()` only triggers for missing fields.\n *\n * @example\n * ```typescript\n * // Returns the user's display name, or returns \"Anonymous\" if the field is null.\n * ifNull(field(\"displayName\"), \"Anonymous\")\n * ```\n *\n * @param ifExpr - The expression to check for null.\n * @param elseValue - The value that will be returned if `ifExpr` evaluates to null.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ifNull operation.\n */\nexport function ifNull(\n  ifExpr: Expression,\n  elseValue: unknown\n): FunctionExpression;\n\n/**\n * Creates an expression that returns the `elseExpr` argument if `ifFieldName` field is null, else\n * return the value of the field.\n *\n * @remarks\n * This function provides a fallback for both absent and explicit null values. In contrast,\n * `ifAbsent()` only triggers for missing fields.\n *\n * @example\n * ```typescript\n * // Returns the user's preferred name, or if that is null, returns their full name.\n * ifNull(\"preferredName\", field(\"fullName\"))\n * ```\n *\n * @param ifFieldName - The field to check for null.\n * @param elseExpr - The expression that will be evaluated and returned if `ifFieldName` is null.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ifNull operation.\n */\nexport function ifNull(\n  ifFieldName: string,\n  elseExpr: Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that returns the `elseValue` argument if `ifFieldName` field is null, else\n * return the value of the field.\n *\n * @remarks\n * This function provides a fallback for both absent and explicit null values. In contrast,\n * `ifAbsent()` only triggers for missing fields.\n *\n * @example\n * ```typescript\n * // Returns the user's display name, or returns \"Anonymous\" if the field is null.\n * ifNull(\"displayName\", \"Anonymous\")\n * ```\n *\n * @param ifFieldName - The field to check for null.\n * @param elseValue - The value that will be returned if `ifFieldName` is null.\n * @returns A new {@link @firebase/firestore/pipelines#Expression}  representing the ifNull operation.\n */\nexport function ifNull(\n  ifFieldName: string,\n  elseValue: unknown\n): FunctionExpression;\nexport function ifNull(\n  fieldNameOrExpression: string | Expression,\n  elseValue: Expression | unknown\n): FunctionExpression {\n  return fieldOrExpression(fieldNameOrExpression).ifNull(elseValue);\n}\n\n/**\n * Creates an expression that returns the first non-null, non-absent argument, without evaluating\n * the rest of the arguments. When all arguments are null or absent, returns the last argument.\n *\n * @example\n * ```typescript\n * // Returns the value of the first non-null, non-absent field among 'preferredName', 'fullName',\n * // or the last argument if all previous fields are null.\n * coalesce(field(\"preferredName\"), field(\"fullName\"), constant(\"Anonymous\"))\n * ```\n *\n * @param expression - The first expression to check for null.\n * @param replacement - The fallback expression or value if the first one is null.\n * @param others - Optional additional expressions to check if previous ones are null.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the coalesce operation.\n */\nexport function coalesce(\n  expression: Expression,\n  replacement: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\n\n/**\n * Creates an expression that returns the first non-null, non-absent argument, without evaluating\n * the rest of the arguments. When all arguments are null or absent, returns the last argument.\n *\n * @example\n * ```typescript\n * // Returns the value of the first non-null, non-absent field among 'preferredName', 'fullName',\n * // or the last argument if all previous fields are null.\n * coalesce(\"preferredName\", field(\"fullName\"), constant(\"Anonymous\"))\n * ```\n *\n * @param fieldName - The name of the first field to check for null.\n * @param replacement - The fallback expression or value if the first one is null.\n * @param others - Optional additional expressions to check if previous ones are null.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the coalesce operation.\n */\nexport function coalesce(\n  fieldName: string,\n  replacement: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\nexport function coalesce(\n  fieldNameOrExpression: Expression | string,\n  replacement: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression {\n  return fieldOrExpression(fieldNameOrExpression).coalesce(\n    replacement,\n    ...others\n  );\n}\n\n/**\n * Creates an expression that evaluates to the result corresponding to the first true condition.\n *\n * @remarks\n * This function behaves like a `switch` statement. It accepts an alternating sequence of conditions\n * and their corresponding results.\n * If an odd number of arguments is provided, the final argument serves as a default fallback result.\n * If no default is provided and no condition evaluates to true, it throws an error.\n *\n * @example\n * ```typescript\n * // Return \"Active\" if field \"status\" is 1, \"Pending\" if field \"status\" is 2,\n * // and default to \"Unknown\" if none of the conditions are true.\n * switchOn(\n *   equal(field(\"status\"), 1), constant(\"Active\"),\n *   equal(field(\"status\"), 2), constant(\"Pending\"),\n *   constant(\"Unknown\")\n * )\n * ```\n *\n * @param condition - The first condition to check.\n * @param result - The result if the first condition is true.\n * @param others - Additional conditions and results, and optionally a default value.\n * @returns A new Expression representing the switch operation.\n */\nexport function switchOn(\n  condition: BooleanExpression,\n  result: Expression,\n  ...others: Array<BooleanExpression | Expression>\n): FunctionExpression {\n  return new FunctionExpression(\n    'switch_on',\n    [\n      valueToDefaultExpr(condition),\n      valueToDefaultExpr(result),\n      ...others.map(valueToDefaultExpr)\n    ],\n    'switchOn'\n  );\n}\n\n/**\n * Creates an expression that joins the elements of an array into a string.\n *\n * @example\n * ```typescript\n * // Join the elements of the 'tags' field with a comma and space.\n * join(\"tags\", \", \")\n * ```\n *\n * @param arrayFieldName - The name of the field containing the array.\n * @param delimiter - The string to use as a delimiter.\n * @returns A new Expression representing the join operation.\n */\nexport function join(arrayFieldName: string, delimiter: string): Expression;\n\n/**\n * Creates an expression that joins the elements of an array into a string.\n *\n * @example\n * ```typescript\n * // Join an array of string using the delimiter from the 'separator' field.\n * join(array(['foo', 'bar']), field(\"separator\"))\n * ```\n *\n * @param arrayExpression - An expression that evaluates to an array.\n * @param delimiterExpression - The expression that evaluates to the delimiter string.\n * @returns A new Expression representing the join operation.\n */\nexport function join(\n  arrayExpression: Expression,\n  delimiterExpression: Expression\n): Expression;\n\n/**\n * Creates an expression that joins the elements of an array into a string.\n *\n * @example\n * ```typescript\n * // Join the elements of the 'tags' field with a comma and space.\n * join(field(\"tags\"), \", \")\n * ```\n *\n * @param arrayExpression - An expression that evaluates to an array.\n * @param delimiter - The string to use as a delimiter.\n * @returns A new Expression representing the join operation.\n */\nexport function join(\n  arrayExpression: Expression,\n  delimiter: string\n): Expression;\n\n/**\n * Creates an expression that joins the elements of an array into a string.\n *\n * @example\n * ```typescript\n * // Join the elements of the 'tags' field with the delimiter from the 'separator' field.\n * join('tags', field(\"separator\"))\n * ```\n *\n * @param arrayFieldName - The name of the field containing the array.\n * @param delimiterExpression - The expression that evaluates to the delimiter string.\n * @returns A new Expression representing the join operation.\n */\nexport function join(\n  arrayFieldName: string,\n  delimiterExpression: Expression\n): Expression;\nexport function join(\n  fieldNameOrExpression: string | Expression,\n  delimiterValueOrExpression: Expression | string\n): Expression {\n  return fieldOrExpression(fieldNameOrExpression).join(\n    valueToDefaultExpr(delimiterValueOrExpression)\n  );\n}\n\n/**\n * Creates an expression that computes the base-10 logarithm of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the base-10 logarithm of the 'value' field.\n * log10(\"value\");\n * ```\n *\n * @param fieldName - The name of the field to compute the base-10 logarithm of.\n * @returns A new `Expression` representing the base-10 logarithm of the numeric value.\n */\nexport function log10(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that computes the base-10 logarithm of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the base-10 logarithm of the 'value' field.\n * log10(field(\"value\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which the base-10 logarithm will be computed for.\n * @returns A new `Expression` representing the base-10 logarithm of the numeric value.\n */\nexport function log10(expression: Expression): FunctionExpression;\nexport function log10(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).log10();\n}\n\n/**\n * Creates an expression that computes the sum of the elements in an array.\n *\n * @example\n * ```typescript\n * // Compute the sum of the elements in the 'scores' field.\n * arraySum(\"scores\");\n * ```\n *\n * @param fieldName - The name of the field to compute the sum of.\n * @returns A new `Expression` representing the sum of the elements in the array.\n */\nexport function arraySum(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that computes the sum of the elements in an array.\n *\n * @example\n * ```typescript\n * // Compute the sum of the elements in the 'scores' field.\n * arraySum(field(\"scores\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric array, which the sum will be computed for.\n * @returns A new `Expression` representing the sum of the elements in the array.\n */\nexport function arraySum(expression: Expression): FunctionExpression;\nexport function arraySum(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).arraySum();\n}\n\n/**\n * Creates an expression that splits the value of a field on the provided delimiter.\n *\n * @example\n * ```typescript\n * // Split the 'scoresCsv' field on delimiter ','\n * split('scoresCsv', ',')\n * ```\n *\n * @param fieldName - Split the value in this field.\n * @param delimiter - Split on this delimiter.\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function.\n */\nexport function split(fieldName: string, delimiter: string): FunctionExpression;\n\n/**\n * Creates an expression that splits the value of a field on the provided delimiter.\n *\n * @example\n * ```typescript\n * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format\n * split('scores', conditional(field('format').equal('csv'), constant(','), constant(':')))\n * ```\n *\n * @param fieldName - Split the value in this field.\n * @param delimiter - Split on this delimiter returned by evaluating this expression.\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function.\n */\nexport function split(\n  fieldName: string,\n  delimiter: Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that splits a string into an array of substrings based on the provided delimiter.\n *\n * @example\n * ```typescript\n * // Split the 'scoresCsv' field on delimiter ','\n * split(field('scoresCsv'), ',')\n * ```\n *\n * @param expression - Split the result of this expression.\n * @param delimiter - Split on this delimiter.\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function.\n */\nexport function split(\n  expression: Expression,\n  delimiter: string\n): FunctionExpression;\n\n/**\n * Creates an expression that splits a string into an array of substrings based on the provided delimiter.\n *\n * @example\n * ```typescript\n * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format\n * split(field('scores'), conditional(field('format').equal('csv'), constant(','), constant(':')))\n * ```\n *\n * @param expression - Split the result of this expression.\n * @param delimiter - Split on this delimiter returned by evaluating this expression.\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function.\n */\nexport function split(\n  expression: Expression,\n  delimiter: Expression\n): FunctionExpression;\nexport function split(\n  fieldNameOrExpression: string | Expression,\n  delimiter: string | Expression\n): FunctionExpression {\n  return fieldOrExpression(fieldNameOrExpression).split(\n    valueToDefaultExpr(delimiter)\n  );\n}\n\n/**\n * Creates an expression that truncates a timestamp to a specified granularity.\n *\n * @example\n * ```typescript\n * // Truncate the 'createdAt' timestamp to the beginning of the day.\n * timestampTruncate('createdAt', 'day')\n * ```\n *\n * @param fieldName - Truncate the timestamp value contained in this field.\n * @param granularity - The granularity to truncate to.\n * @param timezone - The timezone to use for truncation. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1\".\n * @returns A new `Expression` representing the truncated timestamp.\n */\nexport function timestampTruncate(\n  fieldName: string,\n  granularity: TimeGranularity,\n  timezone?: string | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that truncates a timestamp to a specified granularity.\n *\n * @example\n * ```typescript\n * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'.\n * timestampTruncate('createdAt', field('granularity'))\n * ```\n *\n * @param fieldName - Truncate the timestamp value contained in this field.\n * @param granularity - The granularity to truncate to.\n * @param timezone - The timezone to use for truncation. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1\".\n * @returns A new `Expression` representing the truncated timestamp.\n */\nexport function timestampTruncate(\n  fieldName: string,\n  granularity: Expression,\n  timezone?: string | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that truncates a timestamp to a specified granularity.\n *\n * @example\n * ```typescript\n * // Truncate the 'createdAt' timestamp to the beginning of the day.\n * timestampTruncate(field('createdAt'), 'day')\n * ```\n *\n * @param timestampExpression - Truncate the timestamp value that is returned by this expression.\n * @param granularity - The granularity to truncate to.\n * @param timezone - The timezone to use for truncation. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1\".\n * @returns A new `Expression` representing the truncated timestamp.\n */\nexport function timestampTruncate(\n  timestampExpression: Expression,\n  granularity: TimeGranularity,\n  timezone?: string | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that truncates a timestamp to a specified granularity.\n *\n * @example\n * ```typescript\n * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'.\n * timestampTruncate(field('createdAt'), field('granularity'))\n * ```\n *\n * @param timestampExpression - Truncate the timestamp value that is returned by this expression.\n * @param granularity - The granularity to truncate to.\n * @param timezone - The timezone to use for truncation. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1\".\n * @returns A new `Expression` representing the truncated timestamp.\n */\nexport function timestampTruncate(\n  timestampExpression: Expression,\n  granularity: Expression,\n  timezone?: string | Expression\n): FunctionExpression;\nexport function timestampTruncate(\n  fieldNameOrExpression: string | Expression,\n  granularity: TimeGranularity | Expression,\n  timezone?: string | Expression\n): FunctionExpression {\n  const internalGranularity = isString(granularity)\n    ? valueToDefaultExpr(granularity)\n    : granularity;\n  return fieldOrExpression(fieldNameOrExpression).timestampTruncate(\n    internalGranularity,\n    timezone\n  );\n}\n\n/**\n * @public\n * Creates an expression that retrieves the value of a variable bound via `define()`.\n *\n * @example\n * ```typescript\n * db.pipeline().collection(\"products\")\n *   .define(\n *     field(\"price\").multiply(0.9).as(\"discountedPrice\"),\n *     field(\"stock\").add(10).as(\"newStock\")\n *   )\n *   .where(variable(\"discountedPrice\").lessThan(100))\n *   .select(field(\"name\"), variable(\"newStock\"));\n * ```\n *\n * @param name - The name of the variable to retrieve.\n * @returns An {@link @firebase/firestore/pipelines#Expression} representing the variable's value.\n */\nexport function variable(name: string): Expression {\n  return new VariableExpression(name);\n}\n\n/**\n * @internal\n *\n * Expression representing a variable reference. This evaluates to the value of a variable\n * defined in a pipeline.\n */\nexport class VariableExpression extends Expression {\n  readonly _methodName?: string | undefined;\n\n  /**\n   * @hideconstructor\n   */\n  constructor(private readonly name: string) {\n    super();\n  }\n\n  expressionType: ExpressionType = 'Variable';\n\n  /**\n   * @internal\n   */\n  _toProto(_: JsonProtoSerializer): ProtoValue {\n    return {\n      variableReferenceValue: this.name\n    };\n  }\n\n  /**\n   * @internal\n   */\n  _readUserData(_: ParseContext): void {}\n}\n\n/**\n * @public\n * Creates an expression that represents the current document being processed.\n *\n * @example\n * ```typescript\n * // Define the current document as a variable \"doc\"\n * firestore.pipeline().collection(\"books\")\n *     .define(currentDocument().as(\"doc\"))\n *     // Access a field from the defined document variable\n *     .select(variable(\"doc\").mapGet(\"title\"));\n * ```\n *\n * @returns An {@link @firebase/firestore/pipelines#Expression} representing the current document.\n */\nexport function currentDocument(): Expression {\n  return new FunctionExpression('current_document', []);\n}\n\n/**\n * @internal\n */\nexport function pipelineValue(pipeline: Pipeline): PipelineValueExpression {\n  return new PipelineValueExpression(pipeline);\n}\n\n/**\n * @internal\n */\nclass PipelineValueExpression extends Expression {\n  readonly _methodName?: string | undefined;\n  expressionType: ExpressionType = 'PipelineValue';\n\n  /**\n   * @hideconstructor\n   */\n  constructor(private readonly pipeline: Pipeline) {\n    super();\n  }\n\n  /**\n   * @internal\n   */\n  _toProto(jsonProtoSerializer: JsonProtoSerializer): ProtoValue {\n    return toPipelineValue(this.pipeline._toProto(jsonProtoSerializer));\n  }\n\n  /**\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    this.pipeline._readUserData(context);\n  }\n}\n\n/*\n * Creates an expression that calculates the difference between two timestamps.\n *\n * @example\n * ```typescript\n * // Calculate the difference in days between 'endTime' and 'startTime' fields.\n * timestampDiff('endTime', 'startTime', 'day')\n * ```\n *\n * @param endFieldName - The name of the field representing the ending timestamp.\n * @param startFieldName - The name of the field representing the starting timestamp.\n * @param unit - The unit of time for the difference (e.g., \"day\", \"hour\").\n * @returns A new `Expression` representing the difference as an integer.\n */\nexport function timestampDiff(\n  endFieldName: string,\n  startFieldName: string,\n  unit: TimeUnit | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that calculates the difference between two timestamps.\n *\n * @example\n * ```typescript\n * // Calculate the difference in days between 'endTime' field and a starting timestamp expression.\n * timestampDiff('endTime', field('startTime'), 'day')\n * ```\n *\n * @param endFieldName - The name of the field representing the ending timestamp.\n * @param startExpression - The starting timestamp for the difference calculation.\n * @param unit - The unit of time for the difference (e.g., \"day\", \"hour\").\n * @returns A new `Expression` representing the difference as an integer.\n */\nexport function timestampDiff(\n  endFieldName: string,\n  startExpression: Expression,\n  unit: TimeUnit | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that calculates the difference between two timestamps.\n *\n * @example\n * ```typescript\n * // Calculate the difference in days between an ending timestamp expression and 'startTime' field.\n * timestampDiff(field('endTime'), 'startTime', 'day')\n * ```\n *\n * @param endExpression - The ending timestamp for the difference calculation.\n * @param startFieldName - The name of the field representing the starting timestamp.\n * @param unit - The unit of time for the difference (e.g., \"day\", \"hour\").\n * @returns A new `Expression` representing the difference as an integer.\n */\nexport function timestampDiff(\n  endExpression: Expression,\n  startFieldName: string,\n  unit: TimeUnit | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that calculates the difference between two timestamps.\n *\n * @example\n * ```typescript\n * // Calculate the difference in days between two timestamp expressions.\n * timestampDiff(field('endTime'), field('startTime'), 'day')\n * ```\n *\n * @param endExpression - The ending timestamp for the difference calculation.\n * @param startExpression - The starting timestamp for the difference calculation.\n * @param unit - The unit of time for the difference (e.g., \"day\", \"hour\").\n * @returns A new `Expression` representing the difference as an integer.\n */\nexport function timestampDiff(\n  endExpression: Expression,\n  startExpression: Expression,\n  unit: TimeUnit | Expression\n): FunctionExpression;\nexport function timestampDiff(\n  endFieldNameOrExpression: string | Expression,\n  startFieldNameOrExpression: string | Expression,\n  unit: TimeUnit | Expression\n): FunctionExpression {\n  const normalizedEnd = fieldOrExpression(endFieldNameOrExpression);\n  const normalizedStart = fieldOrExpression(startFieldNameOrExpression);\n  const normalizedUnit = valueToDefaultExpr(unit);\n  return normalizedEnd.timestampDiff(normalizedStart, normalizedUnit);\n}\n\n/**\n * Creates an expression that extracts a specified part from a timestamp.\n *\n * @example\n * ```typescript\n * // Extract the year from the 'createdAt' timestamp.\n * timestampExtract('createdAt', 'year')\n * ```\n *\n * @param fieldName - The name of the field representing the timestamp.\n * @param part - The part to extract from the timestamp (e.g., \"year\", \"month\", \"day\").\n * @param timezone - The timezone to use for extraction. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1.\"\n * @returns A new `Expression` representing the extracted part as an integer.\n */\nexport function timestampExtract(\n  fieldName: string,\n  part: TimePart,\n  timezone?: string | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that extracts a specified part from a timestamp.\n *\n * @example\n * ```typescript\n * // Extract the part specified by the field 'part' from 'createdAt'.\n * timestampExtract('createdAt', field('part'))\n * ```\n *\n * @param fieldName - The name of the field representing the timestamp.\n * @param part - The expression evaluating to the part to extract.\n * @param timezone - The timezone to use for extraction. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1.\"\n * @returns A new `Expression` representing the extracted part as an integer.\n */\nexport function timestampExtract(\n  fieldName: string,\n  part: Expression,\n  timezone?: string | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that extracts a specified part from a timestamp.\n *\n * @example\n * ```typescript\n * // Extract the year from the timestamp returned by the expression.\n * timestampExtract(field('createdAt'), 'year')\n * ```\n *\n * @param timestampExpression - The expression evaluating to the timestamp.\n * @param part - The part to extract from the timestamp (e.g., \"year\", \"month\", \"day\").\n * @param timezone - The timezone to use for extraction. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1.\"\n * @returns A new `Expression` representing the extracted part as an integer.\n */\nexport function timestampExtract(\n  timestampExpression: Expression,\n  part: TimePart,\n  timezone?: string | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that extracts a specified part from a timestamp.\n *\n * @example\n * ```typescript\n * // Extract the part specified by the field 'part' from the timestamp.\n * timestampExtract(field('createdAt'), field('part'))\n * ```\n *\n * @param timestampExpression - The expression evaluating to the timestamp.\n * @param part - The expression evaluating to the part to extract.\n * @param timezone - The timezone to use for extraction. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1.\"\n * @returns A new `Expression` representing the extracted part as an integer.\n */\nexport function timestampExtract(\n  timestampExpression: Expression,\n  part: Expression,\n  timezone?: string | Expression\n): FunctionExpression;\nexport function timestampExtract(\n  fieldNameOrExpression: string | Expression,\n  part: TimePart | Expression,\n  timezone?: string | Expression\n): FunctionExpression {\n  return fieldOrExpression(fieldNameOrExpression).timestampExtract(\n    valueToDefaultExpr(part),\n    timezone\n  );\n}\n\n// TODO(search) enable with backend support\n// /**\n//  * Perform a full-text search on the specified field.\n//  *\n//  * @remarks This Expression can only be used within a `search` stage.\n//  *\n//  * @example\n//  * ```typescript\n//  * db.pipeline().collection('restaurants').search({\n//  *   query: matches('menu', 'waffles')\n//  * })\n//  * ```\n//  *\n//  * @param searchField Search the specified field.\n//  * @param rquery Define the search query using the search domain-specific language (DSL).\n//  */\n// export function matches(\n//   searchField: string | Field,\n//   rquery: string | Expression\n// ): BooleanExpression {\n//   return toField(searchField).matches(rquery);\n// }\n\n/**\n * @beta\n * Perform a full-text search on all indexed search fields in the document.\n *\n * @remarks This Expression can only be used within a `search` stage.\n *\n * @example\n * ```typescript\n * db.pipeline().collection('restaurants').search({\n *   query: documentMatches('waffles OR pancakes')\n * })\n * ```\n *\n * @param rquery Define the search query using the search domain-specific language (DSL).\n */\nexport function documentMatches(\n  rquery: string | Expression\n): BooleanExpression {\n  return new FunctionExpression(\n    'document_matches',\n    [valueToDefaultExpr(rquery)],\n    'documentMatches'\n  ).asBoolean();\n}\n\n/**\n * @beta\n *\n * Evaluates to the search score that reflects the topicality of the document\n * to all of the text predicates (for example: `documentMatches`)\n * in the search query. If `SearchOptions.query` is not set or does not contain\n * any text predicates, then this topicality score will always be `0`.\n *\n * @example\n * ```typescript\n * db.pipeline().collection('restaurants').search({\n *   query: 'waffles',\n *   sort: score().descending()\n * })\n * ```\n *\n * @remarks This Expression can only be used within a `search` stage.\n */\nexport function score(): Expression {\n  return new FunctionExpression('score', [], 'score');\n}\n\n// TODO(search) enable with backend support\n// /**\n//  * Options defining how a snippet expression is evaluated.\n//  */\n// export interface SnippetOptions {\n//   /**\n//    * Define the search query using the search domain-specific language (DSL).\n//    */\n//   rquery: string;\n//\n//   /**\n//    * The maximum width of the string estimated for a variable width font. The\n//    * unit is tenths of ems. The default is `160`.\n//    */\n//   maxSnippetWidth?: number;\n//\n//   /**\n//    * The maximum number of non-contiguous pieces of text in the returned snippet.\n//    * The default is `1`.\n//    */\n//   maxSnippets?: number;\n//\n//   /**\n//    * The string to join the pieces. The default value is '\\n'\n//    */\n//   separator?: string;\n// }\n//\n// /**\n//  * Evaluates to an HTML-formatted text snippet that highlights terms matching\n//  * the search query in `<b>bold</b>`.\n//  *\n//  * @remarks This Expression can only be used within a `search` stage.\n//  *\n//  * @example\n//  * ```typescript\n//  * db.pipeline().collection('restaurants').search({\n//  *   query: 'waffles',\n//  *   addFields: { snippet: snippet('menu', 'waffles') }\n//  * })\n//  * ```\n//  *\n//  * @param searchField Search the specified field for matching terms.\n//  * @param rquery Define the search query using the search domain-specific language (DSL).\n//  */\n// export function snippet(\n//   searchField: string | Field,\n//   rquery: string\n// ): Expression;\n//\n// /**\n//  * Evaluates to an HTML-formatted text snippet that highlights terms matching\n//  * the search query in `<b>bold</b>`.\n//  *\n//  * @remarks This Expression can only be used within a `search` stage.\n//  *\n//  * @param searchField Search the specified field for matching terms.\n//  * @param options Define the search query using the search domain-specific language (DSL).\n//  */\n// export function snippet(\n//   searchField: string | Field,\n//   options: SnippetOptions\n// ): Expression;\n// export function snippet(\n//   field: string | Field,\n//   queryOrOptions: string | SnippetOptions\n// ): Expression {\n//   return toField(field).snippet(\n//     isString(queryOrOptions) ? { rquery: queryOrOptions } : queryOrOptions\n//   );\n// }\n\n/**\n * @beta\n * Evaluates to the distance in meters between the location in the specified\n * field and the query location.\n *\n * @remarks This Expression can only be used within a `search` stage.\n *\n * @example\n * ```typescript\n * db.pipeline().collection('restaurants').search({\n *   query: 'waffles',\n *   sort: geoDistance('location', new GeoPoint(37.0, -122.0)).ascending()\n * })\n * ```\n *\n * @param fieldName - Specifies the field in the document which contains\n * the first GeoPoint for distance computation.\n * @param location - Compute distance to this GeoPoint.\n */\nexport function geoDistance(\n  fieldName: string | Field,\n  location: GeoPoint | Expression\n): Expression {\n  return toField(fieldName).geoDistance(location);\n}\n\n// TODO(search) enable with backend support\n// /**\n//  * Evaluates if the value in the field specified by `fieldName` is between\n//  * the evaluated values for `lowerBound` (inclusive) and `upperBound` (inclusive).\n//  *\n//  * @example\n//  * ```\n//  * // Evaluate if the 'tireWidth' is between 2.2 and 2.4\n//  * between('tireWidth', constant(2.2), constant(2.4))\n//  *\n//  * // This is functionally equivalent to\n//  * and(greaterThanOrEqual('tireWidth', constant(2.2)), lessThanOrEqual('tireWidth', constant(2.4)))\n//  * ```\n//  *\n//  * @param fieldName - Evaluate if the value stored in this field is between the lower and upper bounds.\n//  * @param lowerBound - Lower bound (inclusive) of the range.\n//  * @param upperBound - Upper bound (inclusive) of the range.\n//  */\n// export function between(\n//   fieldName: string,\n//   lowerBound: Expression,\n//   upperBound: Expression\n// ): BooleanExpression;\n//\n// /**\n//  * Evaluates if the value in the field specified by `fieldName` is between\n//  * the values for `lowerBound` (inclusive) and `upperBound` (inclusive).\n//  *\n//  * @example\n//  * ```\n//  * // Evaluate if the 'tireWidth' is between 2.2 and 2.4\n//  * between('tireWidth', 2.2, 2.4)\n//  *\n//  * // This is functionally equivalent to\n//  * and(greaterThanOrEqual('tireWidth', 2.2), lessThanOrEqual('tireWidth', 2.4))\n//  * ```\n//  *\n//  * @param fieldName - Evaluate if the value stored in this field is between the lower and upper bounds.\n//  * @param lowerBound - Lower bound (inclusive) of the range.\n//  * @param upperBound - Upper bound (inclusive) of the range.\n//  */\n// export function between(\n//   fieldName: string,\n//   lowerBound: unknown,\n//   upperBound: unknown\n// ): BooleanExpression;\n//\n// /**\n//  * Evaluates if the result of the specified `expression` is between\n//  * the results of `lowerBound` (inclusive) and `upperBound` (inclusive).\n//  *\n//  * @example\n//  * ```\n//  * // Evaluate if the 'tireWidth' is between 2.2 and 2.4\n//  * between(field('tireWidth'), constant(2.2), constant(2.4))\n//  *\n//  * // This is functionally equivalent to\n//  * and(greaterThanOrEqual(field('tireWidth'), constant(2.2)), lessThanOrEqual(field('tireWidth'), constant(2.4)))\n//  * ```\n//  *\n//  * @param expression - Evaluate if the result of this expression is between the lower and upper bounds.\n//  * @param lowerBound - Lower bound (inclusive) of the range.\n//  * @param upperBound - Upper bound (inclusive) of the range.\n//  */\n// export function between(\n//   expression: Expression,\n//   lowerBound: Expression,\n//   upperBound: Expression\n// ): BooleanExpression;\n//\n// /**\n//  * Evaluates if the result of the specified `expression` is between\n//  * the `lowerBound` (inclusive) and `upperBound` (inclusive).\n//  *\n//  * @example\n//  * ```\n//  * // Evaluate if the 'tireWidth' is between 2.2 and 2.4\n//  * between(field('tireWidth'), 2.2, 2.4)\n//  *\n//  * // This is functionally equivalent to\n//  * and(greaterThanOrEqual(field('tireWidth'), 2.2), lessThanOrEqual(field('tireWidth'), 2.4))\n//  * ```\n//  *\n//  * @param expression - Evaluate if the result of this expression is between the lower and upper bounds.\n//  * @param lowerBound - Lower bound (inclusive) of the range.\n//  * @param upperBound - Upper bound (inclusive) of the range.\n//  */\n// export function between(\n//   expression: Expression,\n//   lowerBound: unknown,\n//   upperBound: unknown\n// ): BooleanExpression;\n//\n// export function between(\n//   expression: Expression | string,\n//   lowerBound: unknown,\n//   upperBound: unknown\n// ): BooleanExpression {\n//   return fieldOrExpression(expression).between(lowerBound, upperBound);\n// }\n\n// TODO(new-expression): Add new top-level expression function definitions above this line\n\n/**\n *\n * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in ascending order based on an expression.\n *\n * @example\n * ```typescript\n * // Sort documents by the 'name' field in lowercase in ascending order\n * firestore.pipeline().collection(\"users\")\n *   .sort(ascending(field(\"name\").toLower()));\n * ```\n *\n * @param expr - The expression to create an ascending ordering for.\n * @returns A new `Ordering` for ascending sorting.\n */\nexport function ascending(expr: Expression): Ordering;\n\n/**\n *\n * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in ascending order based on a field.\n *\n * @example\n * ```typescript\n * // Sort documents by the 'name' field in ascending order\n * firestore.pipeline().collection(\"users\")\n *   .sort(ascending(\"name\"));\n * ```\n *\n * @param fieldName - The field to create an ascending ordering for.\n * @returns A new `Ordering` for ascending sorting.\n */\nexport function ascending(fieldName: string): Ordering;\nexport function ascending(field: Expression | string): Ordering {\n  return new Ordering(fieldOrExpression(field), 'ascending', 'ascending');\n}\n\n/**\n *\n * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in descending order based on an expression.\n *\n * @example\n * ```typescript\n * // Sort documents by the 'name' field in lowercase in descending order\n * firestore.pipeline().collection(\"users\")\n *   .sort(descending(field(\"name\").toLower()));\n * ```\n *\n * @param expr - The expression to create a descending ordering for.\n * @returns A new `Ordering` for descending sorting.\n */\nexport function descending(expr: Expression): Ordering;\n\n/**\n *\n * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in descending order based on a field.\n *\n * @example\n * ```typescript\n * // Sort documents by the 'name' field in descending order\n * firestore.pipeline().collection(\"users\")\n *   .sort(descending(\"name\"));\n * ```\n *\n * @param fieldName - The field to create a descending ordering for.\n * @returns A new `Ordering` for descending sorting.\n */\nexport function descending(fieldName: string): Ordering;\nexport function descending(field: Expression | string): Ordering {\n  return new Ordering(fieldOrExpression(field), 'descending', 'descending');\n}\n\n/**\n *\n * Represents an ordering criterion for sorting documents in a Firestore pipeline.\n *\n * You create `Ordering` instances using the `ascending` and `descending` helper functions.\n */\nexport class Ordering implements ProtoValueSerializable, UserData {\n  constructor(\n    public readonly expr: Expression,\n    public readonly direction: 'ascending' | 'descending',\n    readonly _methodName: string | undefined\n  ) {}\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoValue {\n    return {\n      mapValue: {\n        fields: {\n          direction: toStringValue(this.direction),\n          expression: this.expr._toProto(serializer)\n        }\n      }\n    };\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    this.expr._readUserData(context);\n  }\n\n  _protoValueType: 'ProtoValue' = 'ProtoValue';\n}\n\nexport function isSelectable(val: unknown): val is Selectable {\n  const candidate = val as Selectable;\n  return (\n    candidate.selectable && isString(candidate.alias) && isExpr(candidate.expr)\n  );\n}\n\nexport function isOrdering(val: unknown): val is Ordering {\n  const candidate = val as Ordering | undefined;\n  return (\n    candidate !== undefined &&\n    candidate !== null &&\n    isExpr(candidate.expr) &&\n    (candidate.direction === 'ascending' ||\n      candidate.direction === 'descending')\n  );\n}\n\nexport function isAliasedAggregate(val: unknown): val is AliasedAggregate {\n  const candidate = val as AliasedAggregate;\n  return (\n    isString(candidate.alias) &&\n    candidate.aggregate instanceof AggregateFunction\n  );\n}\n\nexport function isExpr(val: unknown): val is Expression {\n  return val instanceof Expression;\n}\n\nexport function isBooleanExpr(val: unknown): val is BooleanExpression {\n  return val instanceof BooleanExpression;\n}\n\nexport function isAliasedExpr(val: unknown): val is AliasedExpression {\n  return val instanceof AliasedExpression;\n}\n\nexport function isField(val: unknown): val is Field {\n  return val instanceof Field;\n}\n\nexport function toField(value: string | Field): Field {\n  if (isString(value)) {\n    const result = field(value);\n    return result;\n  } else {\n    return value as Field;\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 { ParseContext } from '../api/parse_context';\nimport { OptionsUtil } from '../core/options_util';\nimport {\n  ApiClientObjectMap,\n  firestoreV1ApiClientInterfaces,\n  Stage as ProtoStage\n} from '../protos/firestore_proto_api';\nimport { toNumber } from '../remote/number_serializer';\nimport {\n  JsonProtoSerializer,\n  ProtoSerializable,\n  toMapValue,\n  toPipelineValue,\n  toStringValue\n} from '../remote/serializer';\nimport { hardAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport {\n  AggregateFunction,\n  BooleanExpression,\n  Expression,\n  Field,\n  field,\n  Ordering\n} from './expressions';\nimport { Pipeline } from './pipeline';\nimport { QueryEnhancement, StageOptions } from './stage_options';\nimport { isUserData, UserData } from './user_data_reader';\n\nexport abstract class Stage implements ProtoSerializable<ProtoStage>, UserData {\n  /**\n   * Store _optionsProto parsed by _readUserData.\n   * @private\n   * @internal\n   * @protected\n   */\n  protected optionsProto:\n    | ApiClientObjectMap<firestoreV1ApiClientInterfaces.Value>\n    | undefined = undefined;\n  protected knownOptions: Record<string, unknown>;\n  protected rawOptions?: Record<string, unknown>;\n\n  constructor(options: Record<string, unknown> & StageOptions) {\n    ({ rawOptions: this.rawOptions, ...this.knownOptions } = options);\n  }\n\n  _readUserData(context: ParseContext): void {\n    this.optionsProto = this._optionsUtil.getOptionsProto(\n      context,\n      this.knownOptions,\n      this.rawOptions\n    );\n  }\n\n  _toProto(_: JsonProtoSerializer): ProtoStage {\n    return {\n      name: this._name,\n      options: this.optionsProto\n    };\n  }\n\n  abstract get _optionsUtil(): OptionsUtil;\n  abstract get _name(): string;\n}\n\nexport class AddFields extends Stage {\n  get _name(): string {\n    return 'add_fields';\n  }\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(\n    public readonly fields: Map<string, Expression>,\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toMapValue(serializer, this.fields)]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.fields, context);\n  }\n}\n\nexport class RemoveFields extends Stage {\n  get _name(): string {\n    return 'remove_fields';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(private fields: Field[], options: StageOptions) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: this.fields.map(f => f._toProto(serializer))\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.fields, context);\n  }\n}\n\n/**\n * @public\n */\nexport class Define extends Stage {\n  get _name(): string {\n    return 'let';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(\n    private aliasedExpressions: Map<string, Expression>,\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toMapValue(serializer, this.aliasedExpressions)]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.aliasedExpressions, context);\n  }\n}\n\nexport class Aggregate extends Stage {\n  get _name(): string {\n    return 'aggregate';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(\n    public readonly groups: Map<string, Expression>,\n    public readonly accumulators: Map<string, AggregateFunction>,\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [\n        toMapValue(serializer, this.accumulators),\n        toMapValue(serializer, this.groups)\n      ]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.groups, context);\n    readUserDataHelper(this.accumulators, context);\n  }\n}\n\nexport class Distinct extends Stage {\n  get _name(): string {\n    return 'distinct';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(\n    public readonly groups: Map<string, Expression>,\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toMapValue(serializer, this.groups)]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.groups, context);\n  }\n}\n\nexport class CollectionSource extends Stage {\n  get _name(): string {\n    return 'collection';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({\n      forceIndex: {\n        serverName: 'force_index'\n      }\n    });\n  }\n\n  readonly formattedCollectionPath: string;\n\n  constructor(collection: string, options: StageOptions) {\n    super(options);\n\n    // prepend slash to collection string\n    this.formattedCollectionPath = collection.startsWith('/')\n      ? collection\n      : '/' + collection;\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [{ referenceValue: this.formattedCollectionPath }]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n  }\n}\n\nexport class CollectionGroupSource extends Stage {\n  get _name(): string {\n    return 'collection_group';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({\n      forceIndex: {\n        serverName: 'force_index'\n      }\n    });\n  }\n\n  constructor(public readonly collectionId: string, options: StageOptions) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [{ referenceValue: '' }, { stringValue: this.collectionId }]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n  }\n}\n\nexport class SubcollectionSource extends Stage {\n  get _name(): string {\n    return 'subcollection';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(private path: string, options: StageOptions) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [{ stringValue: this.path }]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n  }\n}\n\nexport class DatabaseSource extends Stage {\n  get _name(): string {\n    return 'database';\n  }\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer)\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n  }\n}\n\nexport class DocumentsSource extends Stage {\n  get _name(): string {\n    return 'documents';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  readonly formattedPaths: string[];\n  readonly formattedPathsSet: Set<string>;\n\n  constructor(docPaths: string[], options: StageOptions) {\n    super(options);\n    if (!docPaths || docPaths.length === 0) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Empty document paths are not allowed in DocumentsSource'\n      );\n    }\n    const paths = docPaths.map(path =>\n      path.startsWith('/') ? path : '/' + path\n    );\n    const uniqueDocPaths = new Set(paths);\n    if (uniqueDocPaths.size !== paths.length) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Duplicate document paths are not allowed in DocumentsSource'\n      );\n    }\n    this.formattedPaths = paths;\n    this.formattedPathsSet = uniqueDocPaths;\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: this.formattedPaths.map(p => {\n        return { referenceValue: p };\n      })\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n  }\n}\n\nexport class Where extends Stage {\n  get _name(): string {\n    return 'where';\n  }\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(\n    public readonly condition: BooleanExpression,\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [this.condition._toProto(serializer)]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.condition, context);\n  }\n}\n\nexport class FindNearest extends Stage {\n  get _name(): string {\n    return 'find_nearest';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({\n      limit: {\n        serverName: 'limit'\n      },\n      distanceField: {\n        serverName: 'distance_field'\n      }\n    });\n  }\n\n  constructor(\n    private vectorValue: Expression,\n    private field: Field,\n    private distanceMeasure: 'euclidean' | 'cosine' | 'dot_product',\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [\n        this.field._toProto(serializer),\n        this.vectorValue._toProto(serializer),\n        toStringValue(this.distanceMeasure)\n      ]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.vectorValue, context);\n    readUserDataHelper(this.field, context);\n  }\n}\n\nexport class Limit extends Stage {\n  get _name(): string {\n    return 'limit';\n  }\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(public readonly limit: number, options: StageOptions) {\n    hardAssert(\n      !isNaN(limit) && limit !== Infinity && limit !== -Infinity,\n      0x882c,\n      'Invalid limit value'\n    );\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toNumber(serializer, this.limit)]\n    };\n  }\n}\n\nexport class Offset extends Stage {\n  get _name(): string {\n    return 'offset';\n  }\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(public readonly offset: number, options: StageOptions) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toNumber(serializer, this.offset)]\n    };\n  }\n}\n\nexport class Select extends Stage {\n  get _name(): string {\n    return 'select';\n  }\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(\n    private selections: Map<string, Expression>,\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toMapValue(serializer, this.selections)]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.selections, context);\n  }\n}\n\nexport class Sort extends Stage {\n  get _name(): string {\n    return 'sort';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(public readonly orderings: Ordering[], options: StageOptions) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: this.orderings.map(o => o._toProto(serializer))\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.orderings, context);\n  }\n}\n\nexport class Sample extends Stage {\n  get _name(): string {\n    return 'sample';\n  }\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(\n    private rate: number,\n    private mode: 'percent' | 'documents',\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toNumber(serializer, this.rate)!, toStringValue(this.mode)!]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n  }\n}\n\nexport class Union extends Stage {\n  get _name(): string {\n    return 'union';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(private other: Pipeline, options: StageOptions) {\n    super(options);\n  }\n\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toPipelineValue(this.other._toProto(serializer))]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    this.other._readUserData(context);\n    super._readUserData(context);\n  }\n}\n\nexport class Unnest extends Stage {\n  get _name(): string {\n    return 'unnest';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({\n      indexField: {\n        serverName: 'index_field'\n      }\n    });\n  }\n\n  constructor(\n    private alias: string,\n    private expr: Expression,\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [\n        this.expr._toProto(serializer),\n        field(this.alias)._toProto(serializer)\n      ]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.expr, context);\n  }\n}\n\nexport class Replace extends Stage {\n  static readonly MODE = 'full_replace';\n\n  get _name(): string {\n    return 'replace_with';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(private map: Expression, options: StageOptions) {\n    super(options);\n  }\n\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [this.map._toProto(serializer), toStringValue(Replace.MODE)]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.map, context);\n  }\n}\n\n// eslint-disable-next-line -- eslint should not convert this type to an interface\ntype InternalSearchOptions = {\n  // These are constrained from the public type\n  query: BooleanExpression;\n  sort?: Ordering[];\n  select?: Record<string, Expression>;\n  addFields?: Record<string, Expression>;\n\n  // These are the same as the public type\n  languageCode?: string;\n  retrievalDepth?: number;\n  offset?: number;\n  limit?: number;\n  queryEnhancement?: QueryEnhancement;\n};\n\n/**\n * @beta\n */\nexport class Search extends Stage {\n  constructor(private _searchOptions: InternalSearchOptions) {\n    super(_searchOptions);\n  }\n\n  get _name(): string {\n    return 'search';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({\n      query: {\n        serverName: 'query'\n      },\n      limit: {\n        serverName: 'limit'\n      },\n      retrievalDepth: {\n        serverName: 'retrieval_depth'\n      },\n      sort: {\n        serverName: 'sort'\n      },\n      addFields: {\n        serverName: 'add_fields'\n      },\n      select: {\n        serverName: 'select'\n      },\n      offset: {\n        serverName: 'offset'\n      },\n      queryEnhancement: {\n        serverName: 'query_enhancement'\n      },\n      languageCode: {\n        serverName: 'language_code'\n      }\n    });\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: []\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    readUserDataHelper(this._searchOptions.query, context);\n    if (this._searchOptions.addFields) {\n      readUserDataHelper(this._searchOptions.addFields, context);\n    }\n    if (this._searchOptions.select) {\n      readUserDataHelper(this._searchOptions.select, context);\n    }\n    if (this._searchOptions.sort) {\n      readUserDataHelper(this._searchOptions.sort, context);\n    }\n\n    super._readUserData(context);\n  }\n}\n\n/**\n * @beta\n */\nexport class RawStage extends Stage {\n  /**\n   * @private\n   * @internal\n   */\n  constructor(\n    private name: string,\n    private params: Array<AggregateFunction | Expression>,\n    rawOptions: Record<string, unknown>\n  ) {\n    super({ rawOptions });\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      name: this.name,\n      args: this.params.map(o => o._toProto(serializer)),\n      options: this.optionsProto\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.params, context);\n  }\n\n  get _name(): string {\n    return this.name;\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n}\n\n/**\n * Helper to read user data across a number of different formats.\n * @param name - Name of the calling function. Used for error messages when invalid user data is encountered.\n * @param expressionMap\n * @returns the expressionMap argument.\n * @private\n */\nfunction readUserDataHelper<\n  T extends\n    | Map<string, UserData>\n    | Record<string, UserData>\n    | UserData[]\n    | UserData\n>(expressionMap: T, context: ParseContext): T {\n  if (isUserData(expressionMap)) {\n    expressionMap._readUserData(context);\n  } else if (Array.isArray(expressionMap)) {\n    expressionMap.forEach(readableData => readableData._readUserData(context));\n  } else if (expressionMap instanceof Map) {\n    expressionMap.forEach(expr => expr._readUserData(context));\n  } else {\n    Object.values(expressionMap).forEach(expression =>\n      expression._readUserData(context)\n    );\n  }\n  return expressionMap;\n}\n","// Copyright 2024 Google LLC* @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 {\n  AddFields,\n  Aggregate,\n  CollectionGroupSource,\n  CollectionSource,\n  DatabaseSource,\n  Distinct,\n  DocumentsSource,\n  Select,\n  Stage\n} from '../lite-api/stage';\nimport { ResourcePath } from '../model/path';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\n\nimport { ListenOptions } from './event_manager';\nimport { PipelineFlavor, PipelineSourceType } from './pipeline-util';\n\nexport class CorePipeline {\n  isCorePipeline = true;\n  constructor(\n    readonly serializer: JsonProtoSerializer,\n    readonly stages: Stage[],\n    readonly listenOptions?: ListenOptions\n  ) {}\n  getPipelineCollection(): string | undefined {\n    return getPipelineCollection(this);\n  }\n  getPipelineCollectionGroup(): string | undefined {\n    return getPipelineCollectionGroup(this);\n  }\n  getPipelineCollectionId(): string | undefined {\n    return getPipelineCollectionId(this);\n  }\n  getPipelineDocuments(): string[] | undefined {\n    return getPipelineDocuments(this);\n  }\n  getPipelineFlavor(): PipelineFlavor {\n    return getPipelineFlavor(this);\n  }\n  getPipelineSourceType(): PipelineSourceType | 'unknown' {\n    return getPipelineSourceType(this);\n  }\n}\n\nexport function getPipelineSourceType(\n  p: CorePipeline\n): PipelineSourceType | 'unknown' {\n  debugAssert(p.stages.length > 0, 'Pipeline must have at least one stage');\n  const source = p.stages[0];\n\n  if (\n    source instanceof CollectionSource ||\n    source instanceof CollectionGroupSource ||\n    source instanceof DatabaseSource ||\n    source instanceof DocumentsSource\n  ) {\n    return source._name as PipelineSourceType;\n  }\n\n  return 'unknown';\n}\n\nexport function getPipelineCollection(p: CorePipeline): string | undefined {\n  if (getPipelineSourceType(p) === 'collection') {\n    return (p.stages[0] as CollectionSource).formattedCollectionPath;\n  }\n  return undefined;\n}\n\nexport function getPipelineCollectionGroup(\n  p: CorePipeline\n): string | undefined {\n  if (getPipelineSourceType(p) === 'collection_group') {\n    return (p.stages[0] as CollectionGroupSource).collectionId;\n  }\n  return undefined;\n}\n\nexport function getPipelineCollectionId(p: CorePipeline): string | undefined {\n  switch (getPipelineSourceType(p)) {\n    case 'collection':\n      return ResourcePath.fromString(getPipelineCollection(p)!).lastSegment();\n    case 'collection_group':\n      return getPipelineCollectionGroup(p);\n    default:\n      return undefined;\n  }\n}\n\nexport function getPipelineDocuments(p: CorePipeline): string[] | undefined {\n  if (getPipelineSourceType(p) === 'documents') {\n    return (p.stages[0] as DocumentsSource).formattedPaths;\n  }\n  return undefined;\n}\n\nexport function getPipelineFlavor(p: CorePipeline): PipelineFlavor {\n  let flavor: PipelineFlavor = 'exact';\n  p.stages.forEach((stage, index) => {\n    if (stage._name === Distinct.name || stage._name === Aggregate.name) {\n      flavor = 'keyless';\n    }\n    if (stage._name === Select.name && flavor === 'exact') {\n      flavor = 'augmented';\n    }\n    // TODO(pipeline): verify the last stage is addFields, and it is added by the SDK.\n    if (\n      stage._name === AddFields.name &&\n      index < p.stages.length - 1 &&\n      flavor === 'exact'\n    ) {\n      flavor = 'augmented';\n    }\n  });\n\n  return flavor;\n}\n","// Copyright 2024 Google LLC* @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 { RE2JS } from 're2js';\n\nimport {\n  Field,\n  Constant,\n  Expression,\n  FunctionExpression,\n  ListOfExprs,\n  BooleanConstant,\n  BooleanExpression,\n  BooleanFunctionExpression,\n  BooleanField\n} from '../lite-api/expressions';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { MutableDocument } from '../model/document';\nimport {\n  CREATE_TIME_NAME,\n  DOCUMENT_KEY_NAME,\n  UPDATE_TIME_NAME\n} from '../model/path';\nimport {\n  getLocalWriteTime,\n  getPreviousValue,\n  isServerTimestamp\n} from '../model/server_timestamps';\nimport {\n  FALSE_VALUE,\n  getVectorValue,\n  isArray,\n  isBoolean,\n  isBytes,\n  isDouble,\n  isInteger,\n  isMapValue,\n  isNanValue,\n  isNullValue,\n  isNumber,\n  isString,\n  isTimestampValue,\n  isVectorValue,\n  MIN_VALUE,\n  TRUE_VALUE,\n  typeOrder,\n  valueCompare,\n  valueEquals as valueEqualsWithOptions\n} from '../model/values';\nimport { ArrayValue, Value, MapValue } from '../protos/firestore_proto_api';\nimport {\n  JsonProtoSerializer,\n  fromTimestamp,\n  toName,\n  toVersion\n} from '../remote/serializer';\nimport { fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logWarn } from '../util/log';\nimport { objectSize } from '../util/obj';\nimport { isNegativeZero } from '../util/types';\n\nexport type PipelineInputOutput = MutableDocument;\n\nexport interface EvaluationContext {\n  serializer: JsonProtoSerializer;\n  serverTimestampBehavior?: 'estimate' | 'previous' | 'none';\n}\nimport { SnapshotVersion } from './snapshot_version';\n\nexport type EvaluateResultType =\n  | 'ERROR'\n  | 'UNSET'\n  | 'NULL'\n  | 'BOOLEAN'\n  | 'INT'\n  | 'DOUBLE'\n  | 'TIMESTAMP'\n  | 'STRING'\n  | 'BYTES'\n  | 'REFERENCE'\n  | 'GEO_POINT'\n  | 'ARRAY'\n  | 'MAP'\n  | 'FIELD_REFERENCE'\n  | 'VECTOR';\n\nexport class EvaluateResult {\n  private constructor(\n    readonly type: EvaluateResultType,\n    readonly value?: Value\n  ) {}\n\n  static newError(): EvaluateResult {\n    return new EvaluateResult('ERROR', undefined);\n  }\n\n  static newUnset(): EvaluateResult {\n    return new EvaluateResult('UNSET', undefined);\n  }\n\n  static newNull(): EvaluateResult {\n    return new EvaluateResult('NULL', MIN_VALUE);\n  }\n\n  static newValue(value: Value): EvaluateResult {\n    if (isNullValue(value)) {\n      return new EvaluateResult('NULL', MIN_VALUE);\n    } else if (isBoolean(value)) {\n      return new EvaluateResult('BOOLEAN', value);\n    } else if (isInteger(value)) {\n      return new EvaluateResult('INT', value);\n    } else if (isDouble(value)) {\n      return new EvaluateResult('DOUBLE', value);\n    } else if (isTimestampValue(value)) {\n      return new EvaluateResult('TIMESTAMP', value);\n    } else if (isString(value)) {\n      return new EvaluateResult('STRING', value);\n    } else if (isBytes(value)) {\n      return new EvaluateResult('BYTES', value);\n    } else if (value.referenceValue) {\n      return new EvaluateResult('REFERENCE', value);\n    } else if (value.geoPointValue) {\n      return new EvaluateResult('GEO_POINT', value);\n    } else if (isArray(value)) {\n      return new EvaluateResult('ARRAY', value);\n    } else if (isVectorValue(value)) {\n      // vector value must be before map value\n      return new EvaluateResult('VECTOR', value);\n    } else if (isMapValue(value)) {\n      return new EvaluateResult('MAP', value);\n    } else {\n      return new EvaluateResult('ERROR', undefined);\n    }\n  }\n\n  isErrorOrUnset(): boolean {\n    return this.type === 'ERROR' || this.type === 'UNSET';\n  }\n\n  isNull(): boolean {\n    return this.type === 'NULL';\n  }\n}\n\nexport function valueOrUndefined(value: EvaluateResult): Value | undefined {\n  if (value.isErrorOrUnset()) {\n    return undefined;\n  }\n  return value.value!;\n}\n\nexport interface EvaluableExpr {\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult;\n}\n\n/**\n * @internal\n *\n * Unwraps a wrapped expression type, like BooleanExpression.\n *\n * @param expr The expression to unwrap.\n * @return The inner expression of a wrapped expression, otherwise\n * returns the input itself.\n */\nexport function unwrapExpression(expr: BooleanConstant): Constant;\nexport function unwrapExpression(\n  expr: BooleanFunctionExpression\n): FunctionExpression;\nexport function unwrapExpression(expr: BooleanField): Field;\nexport function unwrapExpression(expr: Expression): Expression;\nexport function unwrapExpression(expr: Expression): Expression {\n  if (expr instanceof BooleanExpression) {\n    return expr._expr;\n  }\n\n  return expr;\n}\n\nexport function toEvaluable(expr: Expression): EvaluableExpr {\n  expr = unwrapExpression(expr);\n\n  if (expr instanceof Field) {\n    return new CoreField(expr);\n  } else if (expr instanceof Constant) {\n    return new CoreConstant(expr);\n  } else if (expr instanceof ListOfExprs) {\n    return new CoreListOfExprs(expr);\n  } else if (expr instanceof FunctionExpression) {\n    // TODO(pipeline): We should define all supported function names as constants somewhere instead of magic strings.\n    if (expr.name === 'add') {\n      return new CoreAdd(expr);\n    } else if (expr.name === 'subtract') {\n      return new CoreSubtract(expr);\n    } else if (expr.name === 'multiply') {\n      return new CoreMultiply(expr);\n    } else if (expr.name === 'divide') {\n      return new CoreDivide(expr);\n    } else if (expr.name === 'mod') {\n      return new CoreMod(expr);\n    } else if (expr.name === 'and') {\n      return new CoreAnd(expr);\n    } else if (expr.name === 'equal') {\n      return new CoreEq(expr);\n    } else if (expr.name === 'not_equal') {\n      return new CoreNeq(expr);\n    } else if (expr.name === 'less_than') {\n      return new CoreLt(expr);\n    } else if (expr.name === 'less_than_or_equal') {\n      return new CoreLte(expr);\n    } else if (expr.name === 'greater_than') {\n      return new CoreGt(expr);\n    } else if (expr.name === 'greater_than_or_equal') {\n      return new CoreGte(expr);\n    } else if (expr.name === 'array_concat') {\n      return new CoreArrayConcat(expr);\n    } else if (expr.name === 'array_reverse') {\n      return new CoreArrayReverse(expr);\n    } else if (expr.name === 'array_contains') {\n      return new CoreArrayContains(expr);\n    } else if (expr.name === 'array_contains_all') {\n      return new CoreArrayContainsAll(expr);\n    } else if (expr.name === 'array_contains_any') {\n      return new CoreArrayContainsAny(expr);\n    } else if (expr.name === 'array_length') {\n      return new CoreArrayLength(expr);\n    } else if (expr.name === 'array_element') {\n      return new CoreArrayElement(expr);\n    } else if (expr.name === 'equal_any') {\n      return new CoreEqAny(expr);\n    } else if (expr.name === 'not_equal_any') {\n      return new CoreNotEqAny(expr);\n    } else if (expr.name === 'is_nan') {\n      return new CoreIsNan(expr);\n    } else if (expr.name === 'is_not_nan') {\n      return new CoreIsNotNan(expr);\n    } else if (expr.name === 'is_null') {\n      return new CoreIsNull(expr);\n    } else if (expr.name === 'is_not_null') {\n      return new CoreIsNotNull(expr);\n    } else if (expr.name === 'is_error') {\n      return new CoreIsError(expr);\n    } else if (expr.name === 'exists') {\n      return new CoreExists(expr);\n    } else if (expr.name === 'not') {\n      return new CoreNot(expr);\n    } else if (expr.name === 'or') {\n      return new CoreOr(expr);\n    } else if (expr.name === 'xor') {\n      return new CoreXor(expr);\n    } else if (expr.name === 'conditional') {\n      return new CoreCond(expr);\n    } else if (expr.name === 'maximum') {\n      return new CoreLogicalMaximum(expr);\n    } else if (expr.name === 'minimum') {\n      return new CoreLogicalMinimum(expr);\n    } else if (expr.name === 'reverse') {\n      return new CoreReverse(expr);\n    } else if (expr.name === 'replace_first') {\n      return new CoreReplaceFirst(expr);\n    } else if (expr.name === 'replace_all') {\n      return new CoreReplaceAll(expr);\n    } else if (expr.name === 'char_length') {\n      return new CoreCharLength(expr);\n    } else if (expr.name === 'byte_length') {\n      return new CoreByteLength(expr);\n    } else if (expr.name === 'like') {\n      return new CoreLike(expr);\n    } else if (expr.name === 'regex_contains') {\n      return new CoreRegexContains(expr);\n    } else if (expr.name === 'regex_match') {\n      return new CoreRegexMatch(expr);\n    } else if (expr.name === 'string_contains') {\n      return new CoreStrContains(expr);\n    } else if (expr.name === 'starts_with') {\n      return new CoreStartsWith(expr);\n    } else if (expr.name === 'ends_with') {\n      return new CoreEndsWith(expr);\n    } else if (expr.name === 'to_lower') {\n      return new CoreToLower(expr);\n    } else if (expr.name === 'to_upper') {\n      return new CoreToUpper(expr);\n    } else if (expr.name === 'trim') {\n      return new CoreTrim(expr);\n    } else if (expr.name === 'string_concat') {\n      return new CoreStrConcat(expr);\n    } else if (expr.name === 'map_get') {\n      return new CoreMapGet(expr);\n    } else if (expr.name === 'cosine_distance') {\n      return new CoreCosineDistance(expr);\n    } else if (expr.name === 'dot_product') {\n      return new CoreDotProduct(expr);\n    } else if (expr.name === 'euclidean_distance') {\n      return new CoreEuclideanDistance(expr);\n    } else if (expr.name === 'vector_length') {\n      return new CoreVectorLength(expr);\n    } else if (expr.name === 'unix_micros_to_timestamp') {\n      return new CoreUnixMicrosToTimestamp(expr);\n    } else if (expr.name === 'timestamp_to_unix_micros') {\n      return new CoreTimestampToUnixMicros(expr);\n    } else if (expr.name === 'unix_millis_to_timestamp') {\n      return new CoreUnixMillisToTimestamp(expr);\n    } else if (expr.name === 'timestamp_to_unix_millis') {\n      return new CoreTimestampToUnixMillis(expr);\n    } else if (expr.name === 'unix_seconds_to_timestamp') {\n      return new CoreUnixSecondsToTimestamp(expr);\n    } else if (expr.name === 'timestamp_to_unix_seconds') {\n      return new CoreTimestampToUnixSeconds(expr);\n    } else if (expr.name === 'timestamp_add') {\n      return new CoreTimestampAdd(expr);\n    } else if (expr.name === 'timestamp_subtract') {\n      return new CoreTimestampSub(expr);\n    }\n  }\n\n  throw new Error(`Unknown Expr : ${expr}`);\n}\n\nexport class CoreField implements EvaluableExpr {\n  constructor(private expr: Field) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    if (this.expr.fieldName === DOCUMENT_KEY_NAME) {\n      return EvaluateResult.newValue({\n        referenceValue: toName(context.serializer, input.key)\n      });\n    }\n    if (this.expr.fieldName === UPDATE_TIME_NAME) {\n      return EvaluateResult.newValue({\n        timestampValue: toVersion(context.serializer, input.version)\n      });\n    }\n    if (this.expr.fieldName === CREATE_TIME_NAME) {\n      return EvaluateResult.newValue({\n        timestampValue: toVersion(context.serializer, input.createTime)\n      });\n    }\n    // Return 'UNSET' if the field doesn't exist, otherwise the Value.\n    const result = input.data.field(this.expr._fieldPath);\n\n    function getServerTimestampValue(\n      context: EvaluationContext,\n      value: Value\n    ): Value {\n      if (context.serverTimestampBehavior === 'estimate') {\n        return {\n          timestampValue: toVersion(\n            context.serializer,\n            SnapshotVersion.fromTimestamp(getLocalWriteTime(value))\n          )\n        };\n      } else if (context.serverTimestampBehavior === 'previous') {\n        const previousValue = getPreviousValue(value);\n        if (previousValue) {\n          return previousValue;\n        }\n      }\n      return { nullValue: 'NULL_VALUE' };\n    }\n\n    if (!!result) {\n      if (isServerTimestamp(result)) {\n        return EvaluateResult.newValue(\n          getServerTimestampValue(context, result)\n        );\n      }\n\n      return EvaluateResult.newValue(result);\n    } else {\n      return EvaluateResult.newUnset();\n    }\n  }\n}\n\nexport class CoreConstant implements EvaluableExpr {\n  constructor(private expr: Constant) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    return EvaluateResult.newValue(this.expr._getValue());\n  }\n}\n\nexport class CoreBooleanConstant implements EvaluableExpr {\n  private expr: Constant;\n\n  constructor(expr: BooleanConstant) {\n    this.expr = unwrapExpression(expr);\n  }\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    return EvaluateResult.newValue(this.expr._getValue());\n  }\n}\n\nexport class CoreListOfExprs implements EvaluableExpr {\n  constructor(private expr: ListOfExprs) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    const results: EvaluateResult[] = this.expr.exprs.map(expr =>\n      toEvaluable(expr).evaluate(context, input)\n    );\n    // If any sub-expression resulted in error or was unset, the list evaluation fails.\n    if (results.some(value => value.isErrorOrUnset())) {\n      return EvaluateResult.newError();\n    }\n\n    return EvaluateResult.newValue({\n      arrayValue: { values: results.map(value => value.value!) }\n    });\n  }\n}\n\nfunction asDouble(\n  protoNumber:\n    | { doubleValue: number | string }\n    | { integerValue: number | string }\n): number {\n  if (isDouble(protoNumber)) {\n    return Number(protoNumber.doubleValue);\n  }\n  return Number(protoNumber.integerValue);\n}\n\nfunction asBigInt(protoNumber: { integerValue: number | string }): bigint {\n  return BigInt(protoNumber.integerValue);\n}\n\nexport const LongMaxValue = BigInt('0x7fffffffffffffff');\nexport const LongMinValue = -BigInt('0x8000000000000000');\n\nabstract class BigIntOrDoubleArithmetics implements EvaluableExpr {\n  constructor(protected expr: FunctionExpression) {}\n\n  abstract bigIntArith(\n    left: { integerValue: number | string },\n    right: {\n      integerValue: number | string;\n    }\n  ): bigint | number | undefined;\n  abstract doubleArith(\n    left:\n      | { doubleValue: number | string }\n      | {\n          integerValue: number | string;\n        },\n    right:\n      | { doubleValue: number | string }\n      | {\n          integerValue: number | string;\n        }\n  ):\n    | {\n        doubleValue: number;\n      }\n    | undefined;\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length >= 2,\n      0x60ca,\n      'Arithmetics should have at least 2 params'\n    );\n    const left = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    const right = toEvaluable(this.expr.params[1]).evaluate(context, input);\n    let result = this.applyArithmetics(left, right);\n\n    for (const expr of this.expr.params.slice(2)) {\n      const evaluated = toEvaluable(expr).evaluate(context, input);\n      result = this.applyArithmetics(result, evaluated);\n    }\n\n    return result;\n  }\n\n  applyArithmetics(\n    left: EvaluateResult,\n    right: EvaluateResult\n  ): EvaluateResult {\n    // If any operand is error or unset, the result is error.\n    if (left.isErrorOrUnset() || right.isErrorOrUnset()) {\n      return EvaluateResult.newError();\n    }\n    if (left.isNull() || right.isNull()) {\n      return EvaluateResult.newNull();\n    }\n\n    // Type check: Both must be numbers (integer or double).\n    // We know left and right are Value here due to the check above.\n    const leftVal = left.value;\n    const rightVal = right.value;\n    if (\n      (!isDouble(leftVal) && !isInteger(leftVal)) ||\n      (!isDouble(rightVal) && !isInteger(rightVal))\n    ) {\n      return EvaluateResult.newError(); // Type error\n    }\n\n    // Perform arithmetic based on types.\n    if (isDouble(leftVal) || isDouble(rightVal)) {\n      const result = this.doubleArith(leftVal, rightVal);\n      if (!result) {\n        return EvaluateResult.newError();\n      }\n      return EvaluateResult.newValue(result);\n    }\n\n    if (isInteger(leftVal) && isInteger(rightVal)) {\n      // Pass the narrowed Value types\n      const result = this.bigIntArith(leftVal, rightVal);\n      if (result === undefined) {\n        return EvaluateResult.newError(); // Specific arithmetic error (e.g., divide by zero for integers)\n      }\n\n      if (typeof result === 'number') {\n        // Result was double (e.g., integer divide by zero)\n        return EvaluateResult.newValue({ doubleValue: result });\n      }\n      // Check for BigInt overflow\n      else if (result < LongMinValue || result > LongMaxValue) {\n        return EvaluateResult.newError(); // Simulate overflow error\n      } else {\n        return EvaluateResult.newValue({ integerValue: `${result}` });\n      }\n    }\n    // Should not be reached due to initial type checks\n    return EvaluateResult.newError();\n  }\n}\n\ntype Equality = 'NULL' | 'EQ' | 'NOT_EQ' | 'TYPE_MISMATCH';\nfunction strictValueEquals(left: Value, right: Value): Equality {\n  if (typeOrder(left) !== typeOrder(right)) {\n    return 'TYPE_MISMATCH';\n  }\n\n  if (isNanValue(left) || isNanValue(right)) {\n    return 'NOT_EQ';\n  }\n\n  if (isNullValue(left) && isNullValue(right)) {\n    return 'EQ';\n  }\n\n  if (isNullValue(left) || isNullValue(right)) {\n    return 'NULL';\n  }\n\n  if (isArray(left) && isArray(right)) {\n    return strictArrayValueEquals(left.arrayValue, right.arrayValue);\n  }\n  if (\n    (isVectorValue(left) && isVectorValue(right)) ||\n    (isMapValue(left) && isMapValue(right))\n  ) {\n    return strictObjectValueEquals(left.mapValue!, right.mapValue!);\n  }\n\n  return valueEquals(left, right) ? 'EQ' : 'NOT_EQ';\n}\n\nfunction strictArrayValueEquals(left: ArrayValue, right: ArrayValue): Equality {\n  if (left.values?.length !== right.values?.length) {\n    return 'NOT_EQ';\n  }\n\n  let foundNull = false;\n  for (let index = 0; index < (left.values?.length ?? 0); index++) {\n    const leftValue = left.values![index];\n    const rightValue = right.values![index];\n    switch (strictValueEquals(leftValue, rightValue)) {\n      case 'EQ': {\n        break;\n      }\n      case 'NOT_EQ':\n      case 'TYPE_MISMATCH': {\n        return 'NOT_EQ';\n      }\n      case 'NULL': {\n        foundNull = true;\n        break;\n      }\n      default:\n        fail(0xae41, { leftValue, rightValue });\n        break;\n    }\n  }\n\n  if (foundNull) {\n    return 'NULL';\n  }\n\n  return 'EQ';\n}\n\nfunction strictObjectValueEquals(left: MapValue, right: MapValue): Equality {\n  const leftMap = left.fields || {};\n  const rightMap = right.fields || {};\n\n  if (objectSize(leftMap) !== objectSize(rightMap)) {\n    return 'NOT_EQ';\n  }\n\n  let foundNull = false;\n  for (const key in leftMap) {\n    if (leftMap.hasOwnProperty(key)) {\n      if (rightMap[key] === undefined) {\n        return 'NOT_EQ';\n      }\n\n      const equalityResult = strictValueEquals(leftMap[key], rightMap[key]);\n      switch (equalityResult) {\n        case 'NOT_EQ':\n        case 'TYPE_MISMATCH': {\n          return 'NOT_EQ';\n        }\n        case 'NULL': {\n          foundNull = true;\n          break;\n        }\n        default:\n          break;\n      }\n    }\n  }\n\n  if (foundNull) {\n    return 'NULL';\n  }\n\n  return 'EQ';\n}\n\nfunction valueEquals(left: Value, right: Value): boolean {\n  return valueEqualsWithOptions(left, right, {\n    nanEqual: false,\n    mixIntegerDouble: true,\n    semanticsEqual: true\n  });\n}\n\nexport class CoreAdd extends BigIntOrDoubleArithmetics {\n  bigIntArith(\n    left: { integerValue: number | string },\n    right: {\n      integerValue: number | string;\n    }\n  ): bigint | undefined {\n    return asBigInt(left) + asBigInt(right);\n  }\n\n  doubleArith(\n    left:\n      | { doubleValue: number | string }\n      | {\n          integerValue: number | string;\n        },\n    right:\n      | { doubleValue: number | string }\n      | {\n          integerValue: number | string;\n        }\n  ):\n    | {\n        doubleValue: number;\n      }\n    | undefined {\n    return { doubleValue: asDouble(left) + asDouble(right) };\n  }\n}\n\nexport class CoreSubtract extends BigIntOrDoubleArithmetics {\n  constructor(protected expr: FunctionExpression) {\n    super(expr);\n  }\n\n  bigIntArith(\n    left: { integerValue: number | string },\n    right: {\n      integerValue: number | string;\n    }\n  ): bigint | undefined {\n    return asBigInt(left) - asBigInt(right);\n  }\n\n  doubleArith(\n    left:\n      | { doubleValue: number | string }\n      | {\n          integerValue: number | string;\n        },\n    right:\n      | { doubleValue: number | string }\n      | {\n          integerValue: number | string;\n        }\n  ):\n    | {\n        doubleValue: number;\n      }\n    | undefined {\n    return { doubleValue: asDouble(left) - asDouble(right) };\n  }\n}\n\nexport class CoreMultiply extends BigIntOrDoubleArithmetics {\n  constructor(protected expr: FunctionExpression) {\n    super(expr);\n  }\n\n  bigIntArith(\n    left: { integerValue: number | string },\n    right: {\n      integerValue: number | string;\n    }\n  ): bigint | undefined {\n    return asBigInt(left) * asBigInt(right);\n  }\n\n  doubleArith(\n    left:\n      | { doubleValue: number | string }\n      | {\n          integerValue: number | string;\n        },\n    right:\n      | { doubleValue: number | string }\n      | {\n          integerValue: number | string;\n        }\n  ):\n    | {\n        doubleValue: number;\n      }\n    | undefined {\n    return { doubleValue: asDouble(left) * asDouble(right) };\n  }\n}\n\nexport class CoreDivide extends BigIntOrDoubleArithmetics {\n  constructor(protected expr: FunctionExpression) {\n    super(expr);\n  }\n\n  bigIntArith(\n    left: { integerValue: number | string },\n    right: {\n      integerValue: number | string;\n    }\n  ): bigint | number | undefined {\n    const rightValue = asBigInt(right);\n    if (rightValue === BigInt(0)) {\n      return undefined; // Integer division by zero is an error\n    }\n    return asBigInt(left) / rightValue;\n  }\n\n  doubleArith(\n    left:\n      | { doubleValue: number | string }\n      | {\n          integerValue: number | string;\n        },\n    right:\n      | { doubleValue: number | string }\n      | {\n          integerValue: number | string;\n        }\n  ):\n    | {\n        doubleValue: number;\n      }\n    | undefined {\n    const rightValue = asDouble(right);\n    if (rightValue === 0) {\n      // Double division by zero results in Infinity\n      return {\n        doubleValue: isNegativeZero(rightValue)\n          ? Number.NEGATIVE_INFINITY\n          : Number.POSITIVE_INFINITY\n      };\n    }\n    return { doubleValue: asDouble(left) / rightValue };\n  }\n}\n\nexport class CoreMod extends BigIntOrDoubleArithmetics {\n  constructor(protected expr: FunctionExpression) {\n    super(expr);\n  }\n\n  bigIntArith(\n    left: { integerValue: number | string },\n    right: {\n      integerValue: number | string;\n    }\n  ): bigint | undefined {\n    const rightValue = asBigInt(right);\n    if (rightValue === BigInt(0)) {\n      return undefined; // Modulo by zero is an error\n    }\n    return asBigInt(left) % rightValue;\n  }\n\n  doubleArith(\n    left:\n      | { doubleValue: number | string }\n      | {\n          integerValue: number | string;\n        },\n    right:\n      | { doubleValue: number | string }\n      | {\n          integerValue: number | string;\n        }\n  ):\n    | {\n        doubleValue: number;\n      }\n    | undefined {\n    const rightValue = asDouble(right);\n    if (rightValue === 0) {\n      return undefined; // Modulo by zero is an error\n    }\n\n    return { doubleValue: asDouble(left) % rightValue };\n  }\n}\n\nexport class CoreAnd implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    let hasError = false;\n    let hasNull = false;\n    for (const param of this.expr.params) {\n      const result = toEvaluable(param).evaluate(context, input);\n      switch (result.type) {\n        case 'BOOLEAN': {\n          if (!result.value?.booleanValue) {\n            return EvaluateResult.newValue(FALSE_VALUE);\n          }\n          break;\n        }\n        case 'NULL': {\n          hasNull = true;\n          break;\n        }\n        default: {\n          hasError = true;\n        }\n      }\n    }\n\n    if (hasError) {\n      return EvaluateResult.newError();\n    }\n    if (hasNull) {\n      return EvaluateResult.newNull();\n    }\n\n    return EvaluateResult.newValue(TRUE_VALUE);\n  }\n}\n\nexport class CoreNot implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x25a2,\n      'not() function should have exactly 1 param'\n    );\n    const result = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (result.type) {\n      case 'BOOLEAN': {\n        return EvaluateResult.newValue({\n          booleanValue: !result.value?.booleanValue\n        });\n      }\n      case 'NULL': {\n        return EvaluateResult.newNull();\n      }\n      default:\n        return EvaluateResult.newError();\n    }\n  }\n}\n\nexport class CoreOr implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    let hasError = false;\n    let hasNull = false;\n    for (const param of this.expr.params) {\n      const result = toEvaluable(param).evaluate(context, input);\n      switch (result.type) {\n        case 'BOOLEAN': {\n          if (result.value?.booleanValue) {\n            return EvaluateResult.newValue(TRUE_VALUE);\n          }\n          break;\n        }\n        case 'NULL': {\n          hasNull = true;\n          break;\n        }\n        default: {\n          hasError = true;\n        }\n      }\n    }\n\n    if (hasError) {\n      return EvaluateResult.newError();\n    }\n    if (hasNull) {\n      return EvaluateResult.newNull();\n    }\n\n    return EvaluateResult.newValue(FALSE_VALUE);\n  }\n}\n\nexport class CoreXor implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    let result = false;\n    let hasNull = false;\n    for (const param of this.expr.params) {\n      const evaluated = toEvaluable(param).evaluate(context, input);\n      switch (evaluated.type) {\n        case 'BOOLEAN': {\n          result = CoreXor.xor(result, !!evaluated.value?.booleanValue);\n          break;\n        }\n        case 'NULL': {\n          hasNull = true;\n          break;\n        }\n        default: {\n          return EvaluateResult.newError();\n        }\n      }\n    }\n\n    if (hasNull) {\n      return EvaluateResult.newNull();\n    }\n    return EvaluateResult.newValue({ booleanValue: result });\n  }\n\n  // XOR(a, b) is equivalent to (a OR b) AND NOT(a AND b)\n  // It is required to evaluate all arguments to ensure that the correct error semantics are\n  // applied.\n  static xor(a: boolean, b: boolean): boolean {\n    return (a || b) && !(a && b);\n  }\n}\n\nexport class CoreEqAny implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 2,\n      0xd736,\n      'eq_any() function should have exactly 2 params'\n    );\n\n    let foundNull = false;\n    const searchExpr = this.expr.params[0];\n    const searchValue = toEvaluable(searchExpr).evaluate(context, input);\n    switch (searchValue.type) {\n      case 'NULL': {\n        foundNull = true;\n        break;\n      }\n      case 'ERROR':\n        return EvaluateResult.newError();\n      case 'UNSET':\n        return EvaluateResult.newError();\n      default:\n        break;\n    }\n\n    const arrayExpr = this.expr.params[1];\n    const arrayValue = toEvaluable(arrayExpr).evaluate(context, input);\n    switch (arrayValue.type) {\n      case 'ARRAY':\n        break;\n      case 'NULL': {\n        foundNull = true;\n        break;\n      }\n      default:\n        return EvaluateResult.newError();\n    }\n\n    if (foundNull) {\n      return EvaluateResult.newNull();\n    }\n\n    for (const candidate of arrayValue.value?.arrayValue?.values ?? []) {\n      const isBothNull =\n        isNullValue(searchValue.value!) && isNullValue(candidate);\n      const equalityResult = isBothNull\n        ? 'EQ'\n        : strictValueEquals(searchValue.value!, candidate);\n      switch (equalityResult) {\n        case 'EQ':\n          return EvaluateResult.newValue(TRUE_VALUE);\n        case 'NOT_EQ':\n        case 'TYPE_MISMATCH': {\n          break;\n        }\n        case 'NULL': {\n          foundNull = true;\n          break;\n        }\n        default:\n          fail(0xae40, { value: searchValue.value, candidate });\n          break;\n      }\n    }\n\n    if (foundNull) {\n      return EvaluateResult.newNull();\n    }\n\n    return EvaluateResult.newValue(FALSE_VALUE);\n  }\n}\n\nexport class CoreNotEqAny implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    const equivalent = new CoreNot(\n      new FunctionExpression('not', [\n        new FunctionExpression('equal_any', this.expr.params)\n      ])\n    );\n    return equivalent.evaluate(context, input);\n  }\n}\n\nexport class CoreIsNan implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x5b1a,\n      'is_nan() function should have exactly 1 param'\n    );\n    const evaluated = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (evaluated.type) {\n      case 'INT':\n        return EvaluateResult.newValue(FALSE_VALUE);\n      case 'DOUBLE':\n        return EvaluateResult.newValue({\n          booleanValue: isNaN(\n            asDouble(evaluated.value as { doubleValue: number | string })\n          )\n        });\n      case 'NULL':\n        return EvaluateResult.newNull();\n      default:\n        return EvaluateResult.newError();\n    }\n  }\n}\n\nexport class CoreIsNotNan implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0xc4e6,\n      'is_not_nan() function should have exactly 1 param'\n    );\n\n    const equivalent = new CoreNot(\n      new FunctionExpression('not', [\n        new FunctionExpression('is_nan', this.expr.params)\n      ])\n    );\n    return equivalent.evaluate(context, input);\n  }\n}\n\nexport class CoreIsNull implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x5a53,\n      'is_null() function should have exactly 1 param'\n    );\n    const evaluated = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (evaluated.type) {\n      case 'NULL':\n        return EvaluateResult.newValue(TRUE_VALUE);\n      case 'UNSET':\n        return EvaluateResult.newError();\n      case 'ERROR':\n        return EvaluateResult.newError();\n      default:\n        return EvaluateResult.newValue(FALSE_VALUE);\n    }\n  }\n}\n\nexport class CoreIsNotNull implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x5a7f,\n      'is_not_null() function should have exactly 1 param'\n    );\n    const equivalent = new CoreNot(\n      new FunctionExpression('not', [\n        new FunctionExpression('is_null', this.expr.params)\n      ])\n    );\n    return equivalent.evaluate(context, input);\n  }\n}\n\nexport class CoreIsError implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x146c,\n      'is_error() function should have exactly 1 param'\n    );\n    const evaluated = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (evaluated.type) {\n      case 'ERROR':\n        return EvaluateResult.newValue(TRUE_VALUE);\n      default:\n        return EvaluateResult.newValue(FALSE_VALUE);\n    }\n  }\n}\n\nexport class CoreExists implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x1add,\n      'exists() function should have exactly 1 param'\n    );\n    const evaluated = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (evaluated.type) {\n      case 'ERROR':\n        return EvaluateResult.newError();\n      case 'UNSET':\n        return EvaluateResult.newValue(FALSE_VALUE);\n      default:\n        return EvaluateResult.newValue(TRUE_VALUE);\n    }\n  }\n}\n\nexport class CoreCond implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 3,\n      0x2dba,\n      'cond() function should have exactly 3 param'\n    );\n\n    const condition = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (condition.type) {\n      case 'BOOLEAN': {\n        if (condition.value?.booleanValue) {\n          return toEvaluable(this.expr.params[1]).evaluate(context, input);\n        } else {\n          return toEvaluable(this.expr.params[2]).evaluate(context, input);\n        }\n      }\n      case 'NULL': {\n        return toEvaluable(this.expr.params[2]).evaluate(context, input);\n      }\n      default:\n        return EvaluateResult.newError();\n    }\n  }\n}\n\nexport class CoreLogicalMaximum implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    const results = this.expr.params.map(param =>\n      toEvaluable(param).evaluate(context, input)\n    );\n\n    let maxValue: EvaluateResult | undefined;\n\n    for (const result of results) {\n      switch (result.type) {\n        case 'ERROR':\n        case 'UNSET':\n        case 'NULL':\n          continue;\n        default: {\n          if (maxValue === undefined) {\n            maxValue = result;\n          } else {\n            maxValue =\n              valueCompare(result.value!, maxValue.value!) > 0\n                ? result\n                : maxValue;\n          }\n        }\n      }\n    }\n\n    return maxValue === undefined ? EvaluateResult.newNull() : maxValue;\n  }\n}\n\nexport class CoreLogicalMinimum implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    const results = this.expr.params.map(param =>\n      toEvaluable(param).evaluate(context, input)\n    );\n    let minValue: EvaluateResult | undefined;\n\n    for (const result of results) {\n      switch (result.type) {\n        case 'ERROR':\n        case 'UNSET':\n        case 'NULL':\n          continue;\n        default: {\n          if (minValue === undefined) {\n            minValue = result;\n          } else {\n            minValue =\n              valueCompare(result.value!, minValue.value!) < 0\n                ? result\n                : minValue;\n          }\n        }\n      }\n    }\n\n    return minValue === undefined ? EvaluateResult.newNull() : minValue;\n  }\n}\n\nabstract class ComparisonBase implements EvaluableExpr {\n  protected constructor(protected expr: FunctionExpression) {}\n\n  abstract compareToResult(\n    left: EvaluateResult,\n    right: EvaluateResult\n  ): EvaluateResult;\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 2,\n      0x7939,\n      `${this.expr.name}() function should have exactly 2 params`\n    );\n\n    const left = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (left.type) {\n      case 'ERROR':\n        return EvaluateResult.newError();\n      case 'UNSET':\n        return EvaluateResult.newError();\n      default:\n        break;\n    }\n\n    const right = toEvaluable(this.expr.params[1]).evaluate(context, input);\n    switch (right.type) {\n      case 'ERROR':\n        return EvaluateResult.newError();\n      case 'UNSET':\n        return EvaluateResult.newError();\n      default:\n        break;\n    }\n\n    return this.compareToResult(left, right);\n  }\n}\n\nexport class CoreEq extends ComparisonBase {\n  constructor(protected expr: FunctionExpression) {\n    super(expr);\n  }\n\n  compareToResult(left: EvaluateResult, right: EvaluateResult): EvaluateResult {\n    if (left.isNull() && right.isNull()) {\n      return EvaluateResult.newValue(TRUE_VALUE);\n    }\n    if (left.isNull() || right.isNull()) {\n      return EvaluateResult.newValue(FALSE_VALUE);\n    }\n    if (isNanValue(left.value) || isNanValue(right.value)) {\n      return EvaluateResult.newValue(FALSE_VALUE);\n    }\n\n    if (typeOrder(left.value!) !== typeOrder(right.value!)) {\n      return EvaluateResult.newValue(FALSE_VALUE);\n    }\n\n    switch (strictValueEquals(left.value!, right.value!)) {\n      case 'EQ':\n        return EvaluateResult.newValue(TRUE_VALUE);\n      case 'NOT_EQ':\n        return EvaluateResult.newValue(FALSE_VALUE);\n      case 'NULL':\n        return EvaluateResult.newNull();\n      default:\n        fail(0xae47, { left, right });\n        break;\n    }\n  }\n}\n\nexport class CoreNeq extends ComparisonBase {\n  constructor(protected expr: FunctionExpression) {\n    super(expr);\n  }\n\n  compareToResult(left: EvaluateResult, right: EvaluateResult): EvaluateResult {\n    switch (strictValueEquals(left.value!, right.value!)) {\n      case 'EQ':\n        return EvaluateResult.newValue(FALSE_VALUE);\n      case 'NOT_EQ':\n        return EvaluateResult.newValue(TRUE_VALUE);\n      case 'TYPE_MISMATCH':\n        return EvaluateResult.newValue(TRUE_VALUE);\n      case 'NULL':\n        return EvaluateResult.newNull();\n      default:\n        fail(0xae46, { left, right });\n        break;\n    }\n  }\n}\n\nexport class CoreLt extends ComparisonBase {\n  constructor(protected expr: FunctionExpression) {\n    super(expr);\n  }\n\n  compareToResult(left: EvaluateResult, right: EvaluateResult): EvaluateResult {\n    if (typeOrder(left.value!) !== typeOrder(right.value!)) {\n      return EvaluateResult.newValue(FALSE_VALUE);\n    }\n    if (isNanValue(left.value) || isNanValue(right.value)) {\n      return EvaluateResult.newValue(FALSE_VALUE);\n    }\n    return EvaluateResult.newValue({\n      booleanValue: valueCompare(left.value!, right.value!) < 0\n    });\n  }\n}\n\nexport class CoreLte extends ComparisonBase {\n  constructor(protected expr: FunctionExpression) {\n    super(expr);\n  }\n\n  compareToResult(left: EvaluateResult, right: EvaluateResult): EvaluateResult {\n    if (typeOrder(left.value!) !== typeOrder(right.value!)) {\n      return EvaluateResult.newValue(FALSE_VALUE);\n    }\n    if (isNanValue(left.value!) || isNanValue(right.value!)) {\n      return EvaluateResult.newValue(FALSE_VALUE);\n    }\n\n    if (strictValueEquals(left.value!, right.value!) === 'EQ') {\n      return EvaluateResult.newValue(TRUE_VALUE);\n    }\n\n    return EvaluateResult.newValue({\n      booleanValue: valueCompare(left.value!, right.value!) < 0\n    });\n  }\n}\n\nexport class CoreGt extends ComparisonBase {\n  constructor(protected expr: FunctionExpression) {\n    super(expr);\n  }\n\n  compareToResult(left: EvaluateResult, right: EvaluateResult): EvaluateResult {\n    if (typeOrder(left.value!) !== typeOrder(right.value!)) {\n      return EvaluateResult.newValue(FALSE_VALUE);\n    }\n    if (isNanValue(left.value) || isNanValue(right.value)) {\n      return EvaluateResult.newValue(FALSE_VALUE);\n    }\n    return EvaluateResult.newValue({\n      booleanValue: valueCompare(left.value!, right.value!) > 0\n    });\n  }\n}\n\nexport class CoreGte extends ComparisonBase {\n  constructor(protected expr: FunctionExpression) {\n    super(expr);\n  }\n\n  compareToResult(left: EvaluateResult, right: EvaluateResult): EvaluateResult {\n    if (typeOrder(left.value!) !== typeOrder(right.value!)) {\n      return EvaluateResult.newValue(FALSE_VALUE);\n    }\n    if (isNanValue(left.value!) || isNanValue(right.value!)) {\n      return EvaluateResult.newValue(FALSE_VALUE);\n    }\n\n    if (strictValueEquals(left.value!, right.value!) === 'EQ') {\n      return EvaluateResult.newValue(TRUE_VALUE);\n    }\n\n    return EvaluateResult.newValue({\n      booleanValue: valueCompare(left.value!, right.value!) > 0\n    });\n  }\n}\n\nexport class CoreArrayConcat implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    throw new Error('Unimplemented');\n  }\n}\n\nexport class CoreArrayReverse implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x00d8,\n      'array_reverse() function should have exactly one parameter'\n    );\n    const evaluated = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (evaluated.type) {\n      case 'NULL':\n        return EvaluateResult.newNull();\n      case 'ARRAY': {\n        const values = evaluated.value!.arrayValue?.values ?? [];\n        return EvaluateResult.newValue({\n          arrayValue: { values: [...values].reverse() }\n        });\n      }\n      default:\n        return EvaluateResult.newError();\n    }\n  }\n}\n\nexport class CoreArrayContains implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 2,\n      0xce94,\n      'array_contains() function should have exactly two parameters'\n    );\n    return new CoreEqAny(\n      new FunctionExpression('eq_any', [\n        this.expr.params[1],\n        this.expr.params[0]\n      ])\n    ).evaluate(context, input);\n  }\n}\n\nexport class CoreArrayContainsAll implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 2,\n      0x0570,\n      'array_contains_all() function should have exactly two parameters'\n    );\n\n    let foundNull = false;\n    const arrayToSearch = toEvaluable(this.expr.params[0]).evaluate(\n      context,\n      input\n    );\n    switch (arrayToSearch.type) {\n      case 'ARRAY': {\n        break;\n      }\n      case 'NULL': {\n        foundNull = true;\n        break;\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n\n    const elementsToFind = toEvaluable(this.expr.params[1]).evaluate(\n      context,\n      input\n    );\n    switch (elementsToFind.type) {\n      case 'ARRAY': {\n        break;\n      }\n      case 'NULL': {\n        foundNull = true;\n        break;\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n\n    if (foundNull) {\n      return EvaluateResult.newNull();\n    }\n\n    const searchValues = elementsToFind.value?.arrayValue?.values ?? [];\n    const arrayValues = arrayToSearch.value?.arrayValue?.values ?? [];\n    for (const search of searchValues) {\n      let found = false;\n      foundNull = false;\n      for (const value of arrayValues) {\n        const isBothNull = isNullValue(search) && isNullValue(value);\n        const equalityResult = isBothNull\n          ? 'EQ'\n          : strictValueEquals(search, value);\n        switch (equalityResult) {\n          case 'EQ': {\n            found = true;\n            break;\n          }\n          case 'NOT_EQ':\n          case 'TYPE_MISMATCH': {\n            break;\n          }\n          case 'NULL': {\n            foundNull = true;\n            break;\n          }\n          default:\n            fail(0xae45, { value, search });\n            break;\n        }\n\n        if (found) {\n          // short circuit\n          break;\n        }\n      }\n\n      if (!found) {\n        // false case - we didn't find a match, short circuit\n        return EvaluateResult.newValue(FALSE_VALUE);\n      }\n    }\n\n    return EvaluateResult.newValue(TRUE_VALUE);\n  }\n}\n\nexport class CoreArrayContainsAny implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 2,\n      0x0a78,\n      'array_contains_any() function should have exactly two parameters'\n    );\n\n    let foundNull = false;\n    const arrayToSearch = toEvaluable(this.expr.params[0]).evaluate(\n      context,\n      input\n    );\n    switch (arrayToSearch.type) {\n      case 'ARRAY': {\n        break;\n      }\n      case 'NULL': {\n        foundNull = true;\n        break;\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n\n    const elementsToFind = toEvaluable(this.expr.params[1]).evaluate(\n      context,\n      input\n    );\n    switch (elementsToFind.type) {\n      case 'ARRAY': {\n        break;\n      }\n      case 'NULL': {\n        foundNull = true;\n        break;\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n\n    if (foundNull) {\n      return EvaluateResult.newNull();\n    }\n\n    const searchValues = elementsToFind.value?.arrayValue?.values ?? [];\n    const arrayValues = arrayToSearch.value?.arrayValue?.values ?? [];\n\n    for (const value of arrayValues) {\n      for (const search of searchValues) {\n        const isBothNull = isNullValue(value) && isNullValue(search);\n        const equalityResult = isBothNull\n          ? 'EQ'\n          : strictValueEquals(value, search);\n        switch (equalityResult) {\n          case 'EQ': {\n            return EvaluateResult.newValue(TRUE_VALUE);\n          }\n          case 'NOT_EQ':\n          case 'TYPE_MISMATCH': {\n            break;\n          }\n          case 'NULL': {\n            foundNull = true;\n            break;\n          }\n          default:\n            fail(0xae40, { value, search });\n            break;\n        }\n      }\n    }\n\n    if (foundNull) {\n      return EvaluateResult.newNull();\n    }\n\n    return EvaluateResult.newValue(FALSE_VALUE);\n  }\n}\n\nexport class CoreArrayLength implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x96cd,\n      'array_length() function should have exactly one parameter'\n    );\n    const evaluated = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (evaluated.type) {\n      case 'NULL':\n        return EvaluateResult.newNull();\n      case 'ARRAY': {\n        return EvaluateResult.newValue({\n          integerValue: `${evaluated.value?.arrayValue?.values?.length ?? 0}`\n        });\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n  }\n}\n\nexport class CoreArrayElement implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    throw new Error('Unimplemented');\n  }\n}\n\nexport class CoreReverse implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x05e4,\n      'reverse() function should have exactly one parameter'\n    );\n    const evaluated = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (evaluated.type) {\n      case 'NULL':\n        return EvaluateResult.newNull();\n      case 'BYTES': {\n        const value = evaluated.value?.bytesValue!;\n        if (typeof value === 'string') {\n          const byteString = ByteString.fromBase64String(value);\n          const byteArray = byteString.toUint8Array();\n          byteArray.reverse();\n          return EvaluateResult.newValue({\n            bytesValue: ByteString.fromUint8Array(byteArray).toBase64()\n          });\n        } else {\n          return EvaluateResult.newValue({\n            bytesValue: new Uint8Array(value).reverse()\n          });\n        }\n      }\n      case 'STRING': {\n        const str = evaluated.value?.stringValue!;\n        const segmenter = new Intl.Segmenter(undefined, {\n          granularity: 'grapheme'\n        });\n        const segmentsIterable = segmenter.segment(str);\n        const graphemes = Array.from(\n          segmentsIterable,\n          segment => segment.segment\n        );\n        const reversedGraphemes = graphemes.reverse();\n        return EvaluateResult.newValue({\n          stringValue: reversedGraphemes.join('')\n        });\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n  }\n}\n\nexport class CoreReplaceFirst implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    throw new Error('Unimplemented');\n  }\n}\n\nexport class CoreReplaceAll implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    throw new Error('Unimplemented');\n  }\n}\n\nfunction getUnicodePointCount(str: string): number | undefined {\n  let count = 0;\n  for (let i = 0; i < str.length; i++) {\n    const codePoint = str.codePointAt(i);\n\n    if (codePoint === undefined) {\n      return undefined; // Should not happen with valid JS strings\n    }\n\n    // BMP character (including lone surrogates, which count as 1)\n    if (codePoint <= 0xffff) {\n      // Check specifically for lone surrogates which are invalid UTF-16 sequences\n      if (codePoint >= 0xd800 && codePoint <= 0xdfff) {\n        // High surrogate: check if followed by low surrogate\n        if (codePoint <= 0xdbff) {\n          const nextCodePoint = str.codePointAt(i + 1);\n          if (\n            nextCodePoint === undefined ||\n            !(nextCodePoint >= 0xdc00 && nextCodePoint <= 0xdfff)\n          ) {\n            // Lone high surrogate - treat as one character for length, but invalid for byte length\n            count += 1;\n          } else {\n            // Valid surrogate pair (counts as one character)\n            count += 1;\n            i++; // Skip the low surrogate\n          }\n        } else {\n          // Lone low surrogate - treat as one character\n          count += 1;\n        }\n      } else {\n        // Regular BMP character\n        count += 1;\n      }\n    }\n    // Astral plane character (SMP) - should have been handled by surrogate pair check\n    // This case might be redundant if surrogate logic is correct, but kept for clarity\n    else if (codePoint <= 0x10ffff) {\n      count += 1;\n      i++; // Code points > 0xFFFF take two JS string indices\n    } else {\n      return undefined; // Invalid code point\n    }\n  }\n  return count;\n}\n\nexport class CoreCharLength implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x4bc8,\n      'char_length() function should have exactly one parameter'\n    );\n    const evaluated = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (evaluated.type) {\n      case 'NULL':\n        return EvaluateResult.newNull();\n      case 'STRING': {\n        const length = getUnicodePointCount(evaluated.value!.stringValue!);\n        // If counting failed (e.g., invalid sequence), return error\n        return length === undefined\n          ? EvaluateResult.newError()\n          : EvaluateResult.newValue({ integerValue: length });\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n  }\n}\n\nfunction getUtf8ByteLength(str: string): number | undefined {\n  let byteLength = 0;\n  for (let i = 0; i < str.length; i++) {\n    const codePoint = str.codePointAt(i);\n\n    // Check for out of range of lone surrogate\n    if (codePoint === undefined) {\n      return undefined;\n    }\n\n    if (codePoint >= 0xd800 && codePoint <= 0xdfff) {\n      // If it is a high surrogate, check if a low surrogate follows\n      if (codePoint <= 0xdbff) {\n        const lowSurrogate = str.codePointAt(i + 1);\n        if (\n          lowSurrogate === undefined ||\n          !(lowSurrogate >= 0xdc00 && lowSurrogate <= 0xdfff)\n        ) {\n          return undefined; // Lone high surrogate\n        }\n        // Valid surrogate pair\n        byteLength += 4;\n        i++; // Move past the low surrogate\n      } else {\n        return undefined; // Lone low surrogate\n      }\n    } else if (codePoint <= 0x7f) {\n      byteLength += 1;\n    } else if (codePoint <= 0x7ff) {\n      byteLength += 2;\n    } else if (codePoint <= 0xffff) {\n      byteLength += 3;\n    } else if (codePoint <= 0x10ffff) {\n      byteLength += 4;\n      i++; // Increment i to skip the next code unit of the surrogate pair\n    } else {\n      return undefined; // Invalid code point (should not normally happen)\n    }\n  }\n  return byteLength;\n}\n\nexport class CoreByteLength implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x2126,\n      'byte_length() function should have exactly one parameter'\n    );\n    const evaluated = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (evaluated.type) {\n      case 'BYTES': {\n        const value = evaluated.value?.bytesValue!;\n        if (typeof value === 'string') {\n          return EvaluateResult.newValue({\n            integerValue:\n              ByteString.fromBase64String(value).toUint8Array().length\n          });\n        } else {\n          return EvaluateResult.newValue({\n            integerValue: new Uint8Array(value).length\n          });\n        }\n      }\n      case 'STRING': {\n        // return the number of bytes in the string\n        const result = getUtf8ByteLength(evaluated.value?.stringValue!);\n        return result === undefined\n          ? EvaluateResult.newError()\n          : EvaluateResult.newValue({\n              integerValue: result\n            });\n      }\n      case 'NULL': {\n        return EvaluateResult.newNull();\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n  }\n}\n\nabstract class StringSearchFunctionBase implements EvaluableExpr {\n  constructor(readonly expr: FunctionExpression) {}\n\n  abstract performSearch(value: string, search: string): EvaluateResult;\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 2,\n      0x9b5d,\n      `${this.expr.name}() function should have exactly two parameters`\n    );\n\n    let foundNull = false;\n    const value = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (value.type) {\n      case 'STRING': {\n        break;\n      }\n      case 'NULL': {\n        foundNull = true;\n        break;\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n\n    const pattern = toEvaluable(this.expr.params[1]).evaluate(context, input);\n    switch (pattern.type) {\n      case 'STRING': {\n        break;\n      }\n      case 'NULL': {\n        foundNull = true;\n        break;\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n\n    if (foundNull) {\n      return EvaluateResult.newNull();\n    }\n\n    return this.performSearch(\n      value.value?.stringValue!,\n      pattern.value?.stringValue!\n    );\n  }\n}\n\nfunction likeToRegex(like: string): string {\n  let result = '';\n  for (let i = 0; i < like.length; i++) {\n    const c = like.charAt(i);\n    switch (c) {\n      case '_':\n        result += '.';\n        break;\n      case '%':\n        result += '.*';\n        break;\n      // Escape regex special characters\n      case '\\\\': // Need to escape backslash itself\n      case '.':\n      case '*':\n      case '?':\n      case '+':\n      case '^':\n      case '$':\n      case '|':\n      case '(':\n      case ')':\n      case '[':\n      case ']':\n      case '{':\n      case '}':\n        result += '\\\\' + c;\n        break;\n      default:\n        result += c;\n        break;\n    }\n  }\n  // Anchor the regex to match the entire string\n  return '^' + result + '$';\n}\n\nexport class CoreLike extends StringSearchFunctionBase {\n  performSearch(value: string, search: string): EvaluateResult {\n    try {\n      const regexPattern = likeToRegex(search);\n      const regex = RE2JS.compile(regexPattern);\n      return EvaluateResult.newValue({ booleanValue: regex.matches(value) });\n    } catch (e) {\n      logWarn(\n        `Invalid LIKE pattern converted to regex: ${search}, returning error. Error: ${e}`\n      );\n      return EvaluateResult.newError();\n    }\n  }\n}\n\nexport class CoreRegexContains extends StringSearchFunctionBase {\n  performSearch(value: string, search: string): EvaluateResult {\n    try {\n      const regex = RE2JS.compile(search);\n      return EvaluateResult.newValue({\n        booleanValue: regex.matcher(value).find()\n      });\n    } catch (RE2JSError) {\n      logWarn(\n        `Invalid regex pattern found in regex_contains: ${search}, returning error`\n      );\n      return EvaluateResult.newError();\n    }\n  }\n}\n\nexport class CoreRegexMatch extends StringSearchFunctionBase {\n  performSearch(value: string, search: string): EvaluateResult {\n    try {\n      // Use matches() for full string match semantics\n      return EvaluateResult.newValue({\n        booleanValue: RE2JS.compile(search).matches(value)\n      });\n    } catch (RE2JSError) {\n      logWarn(\n        `Invalid regex pattern found in regex_match: ${search}, returning error`\n      );\n      return EvaluateResult.newError();\n    }\n  }\n}\n\nexport class CoreStrContains extends StringSearchFunctionBase {\n  performSearch(value: string, search: string): EvaluateResult {\n    return EvaluateResult.newValue({ booleanValue: value.includes(search) });\n  }\n}\n\nexport class CoreStartsWith extends StringSearchFunctionBase {\n  performSearch(value: string, search: string): EvaluateResult {\n    return EvaluateResult.newValue({ booleanValue: value.startsWith(search) });\n  }\n}\n\nexport class CoreEndsWith extends StringSearchFunctionBase {\n  performSearch(value: string, search: string): EvaluateResult {\n    return EvaluateResult.newValue({ booleanValue: value.endsWith(search) });\n  }\n}\n\nexport class CoreToLower implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x7197,\n      'to_lower() function should have exactly one parameter'\n    );\n\n    const evaluated = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (evaluated.type) {\n      case 'STRING': {\n        return EvaluateResult.newValue({\n          stringValue: evaluated.value?.stringValue?.toLowerCase()\n        });\n      }\n      case 'NULL': {\n        return EvaluateResult.newNull();\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n  }\n}\n\nexport class CoreToUpper implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0xec47,\n      'to_upper() function should have exactly one parameter'\n    );\n\n    const evaluated = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (evaluated.type) {\n      case 'STRING': {\n        return EvaluateResult.newValue({\n          stringValue: evaluated.value?.stringValue?.toUpperCase()\n        });\n      }\n      case 'NULL': {\n        return EvaluateResult.newNull();\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n  }\n}\n\nexport class CoreTrim implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x6f80,\n      'trim() function should have exactly one parameter'\n    );\n\n    const evaluated = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (evaluated.type) {\n      case 'STRING': {\n        return EvaluateResult.newValue({\n          stringValue: evaluated.value?.stringValue?.trim()\n        });\n      }\n      case 'NULL': {\n        return EvaluateResult.newNull();\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n  }\n}\n\nexport class CoreStrConcat implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    const evaluated = this.expr.params.map(val =>\n      toEvaluable(val).evaluate(context, input)\n    );\n    // If any part is error or unset, or not a string (and not null), result is error\n    // If any part is null, result is null\n    let resultString = '';\n    let hasNull = false;\n    for (const val of evaluated) {\n      switch (val.type) {\n        case 'STRING': {\n          resultString += val.value!.stringValue;\n          break;\n        }\n        case 'NULL': {\n          hasNull = true;\n          break;\n        }\n        default: {\n          return EvaluateResult.newError();\n        }\n      }\n    }\n    if (hasNull) {\n      return EvaluateResult.newNull();\n    }\n    return EvaluateResult.newValue({ stringValue: resultString });\n  }\n}\n\nexport class CoreMapGet implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 2,\n      0x1183,\n      'map_get() function should have exactly two parameters'\n    );\n\n    const evaluatedMap = toEvaluable(this.expr.params[0]).evaluate(\n      context,\n      input\n    );\n    switch (evaluatedMap.type) {\n      case 'UNSET': {\n        return EvaluateResult.newUnset();\n      }\n      case 'MAP': {\n        break;\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n\n    const subfield = toEvaluable(this.expr.params[1]).evaluate(context, input);\n    switch (subfield.type) {\n      case 'STRING': {\n        break;\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n\n    const value =\n      evaluatedMap.value?.mapValue?.fields?.[subfield.value?.stringValue!];\n    return value === undefined\n      ? EvaluateResult.newUnset()\n      : EvaluateResult.newValue(value);\n  }\n}\n\nabstract class DistanceBase implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  abstract calculateDistance(\n    vec1: ArrayValue | undefined,\n    vec2: ArrayValue | undefined\n  ): number | undefined;\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 2,\n      0x628f,\n      `${this.expr.name}() function should have exactly 2 params`\n    );\n\n    let hasNull = false;\n    const vector1 = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (vector1.type) {\n      case 'VECTOR': {\n        break;\n      }\n      case 'NULL': {\n        hasNull = true;\n        break;\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n\n    const vector2 = toEvaluable(this.expr.params[1]).evaluate(context, input);\n    switch (vector2.type) {\n      case 'VECTOR': {\n        break;\n      }\n      case 'NULL': {\n        hasNull = true;\n        break;\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n\n    if (hasNull) {\n      return EvaluateResult.newNull();\n    }\n\n    const vectorValue1 = getVectorValue(vector1.value!);\n    const vectorValue2 = getVectorValue(vector2.value!);\n\n    // Mismatched lengths or undefined vectors result in error\n    if (\n      vectorValue1 === undefined ||\n      vectorValue2 === undefined ||\n      vectorValue1.values?.length !== vectorValue2.values?.length\n    ) {\n      return EvaluateResult.newError();\n    }\n\n    const distance = this.calculateDistance(vectorValue1, vectorValue2);\n    // NaN or undefined distance calculation results in error\n    if (distance === undefined || isNaN(distance)) {\n      return EvaluateResult.newError();\n    }\n\n    return EvaluateResult.newValue({ doubleValue: distance });\n  }\n}\n\nexport class CoreCosineDistance extends DistanceBase {\n  calculateDistance(\n    vec1: ArrayValue | undefined,\n    vec2: ArrayValue | undefined\n  ): number | undefined {\n    const values1 = vec1?.values ?? [];\n    const values2 = vec2?.values ?? [];\n    if (values1.length === 0) {\n      return undefined;\n    } // Distance undefined for empty vectors\n\n    let dotProduct = 0;\n    let magnitude1 = 0;\n    let magnitude2 = 0;\n    for (let i = 0; i < values1.length; i++) {\n      // Error if any element is not a number\n      if (!isNumber(values1[i]) || !isNumber(values2[i])) {\n        return undefined;\n      }\n      const val1 = asDouble(values1[i] as { doubleValue: number | string });\n      const val2 = asDouble(values2[i] as { doubleValue: number | string });\n      dotProduct += val1 * val2;\n      magnitude1 += val1 * val1;\n      magnitude2 += val2 * val2;\n    }\n    const magnitude = Math.sqrt(magnitude1) * Math.sqrt(magnitude2);\n    // Distance undefined if either vector has zero magnitude\n    if (magnitude === 0) {\n      return undefined;\n    }\n\n    // Clamp cosine similarity to [-1, 1] due to potential floating point inaccuracies\n    const cosineSimilarity = Math.max(-1, Math.min(1, dotProduct / magnitude));\n    return 1 - cosineSimilarity;\n  }\n}\n\nexport class CoreDotProduct extends DistanceBase {\n  calculateDistance(\n    vec1: ArrayValue | undefined,\n    vec2: ArrayValue | undefined\n  ): number | undefined {\n    const values1 = vec1?.values ?? [];\n    const values2 = vec2?.values ?? [];\n    if (values1.length === 0) {\n      return 0.0;\n    } // Dot product of empty vectors is 0\n\n    let dotProduct = 0;\n    for (let i = 0; i < values1.length; i++) {\n      // Error if any element is not a number\n      if (!isNumber(values1[i]) || !isNumber(values2[i])) {\n        return undefined;\n      }\n      const val1 = asDouble(values1[i] as { doubleValue: number | string });\n      const val2 = asDouble(values2[i] as { doubleValue: number | string });\n      dotProduct += val1 * val2;\n    }\n\n    return dotProduct;\n  }\n}\n\nexport class CoreEuclideanDistance extends DistanceBase {\n  calculateDistance(\n    vec1: ArrayValue | undefined,\n    vec2: ArrayValue | undefined\n  ): number | undefined {\n    const values1 = vec1?.values ?? [];\n    const values2 = vec2?.values ?? [];\n    if (values1.length === 0) {\n      return 0.0;\n    } // Distance between empty vectors is 0\n\n    let euclideanDistanceSq = 0;\n    for (let i = 0; i < values1.length; i++) {\n      // Error if any element is not a number\n      if (!isNumber(values1[i]) || !isNumber(values2[i])) {\n        return undefined;\n      }\n      const val1 = asDouble(values1[i] as { doubleValue: number | string });\n      const val2 = asDouble(values2[i] as { doubleValue: number | string });\n      euclideanDistanceSq += Math.pow(val1 - val2, 2);\n    }\n\n    return Math.sqrt(euclideanDistanceSq);\n  }\n}\n\nexport class CoreVectorLength implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x9884,\n      'vector_length() function should have exactly one parameter'\n    );\n\n    const vector = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (vector.type) {\n      case 'VECTOR': {\n        const vectorValue = getVectorValue(vector.value!);\n        return EvaluateResult.newValue({\n          integerValue: vectorValue?.values?.length ?? 0\n        });\n      }\n      case 'NULL': {\n        return EvaluateResult.newNull();\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n  }\n}\n\n// 0001-01-01T00:00:00Z\nconst TIMESTAMP_MIN_SECONDS: bigint = BigInt(-62135596800);\n// 9999-12-31T23:59:59Z - but the max timestamp has 999,999,999 nanoseconds\nconst TIMESTAMP_MAX_SECONDS: bigint = BigInt(253402300799);\n\nconst MILLISECONDS_PER_SECOND: bigint = BigInt(1000);\nconst MICROSECONDS_PER_SECOND: bigint = BigInt(1000000);\n\n// 0001-01-01T00:00:00.000Z\nconst TIMESTAMP_MIN_MILLISECONDS: bigint =\n  TIMESTAMP_MIN_SECONDS * MILLISECONDS_PER_SECOND;\n// 9999-12-31T23:59:59.999Z - but the max timestamp has 999,999,999 nanoseconds\nconst TIMESTAMP_MAX_MILLISECONDS: bigint =\n  TIMESTAMP_MAX_SECONDS * MILLISECONDS_PER_SECOND + BigInt(999); // Max sub-second millis\n\n// 0001-01-01T00:00:00.000000Z\nconst TIMESTAMP_MIN_MICROSECONDS: bigint =\n  TIMESTAMP_MIN_SECONDS * MICROSECONDS_PER_SECOND;\n// 9999-12-31T23:59:59.999999Z - but the max timestamp has 999,999,999 nanoseconds\nconst TIMESTAMP_MAX_MICROSECONDS: bigint =\n  TIMESTAMP_MAX_SECONDS * MICROSECONDS_PER_SECOND + BigInt(999999); // Max sub-second micros\n\nfunction isMicrosInBounds(micros: bigint): boolean {\n  return (\n    micros >= TIMESTAMP_MIN_MICROSECONDS && micros <= TIMESTAMP_MAX_MICROSECONDS\n  );\n}\n\nfunction isMillisInBounds(millis: bigint): boolean {\n  return (\n    millis >= TIMESTAMP_MIN_MILLISECONDS && millis <= TIMESTAMP_MAX_MILLISECONDS\n  );\n}\n\nfunction isSecondsInBounds(seconds: bigint): boolean {\n  return seconds >= TIMESTAMP_MIN_SECONDS && seconds <= TIMESTAMP_MAX_SECONDS;\n}\n\nfunction isTimestampInBounds(seconds: number, nanos: number): boolean {\n  const sBig = BigInt(seconds);\n  if (sBig < TIMESTAMP_MIN_SECONDS || sBig > TIMESTAMP_MAX_SECONDS) {\n    return false;\n  }\n  // Nanos must be non-negative and less than 1 second\n  if (nanos < 0 || nanos >= 1_000_000_000) {\n    return false;\n  }\n  // Additional check for min/max boundaries\n  if (sBig === TIMESTAMP_MIN_SECONDS && nanos !== 0) {\n    return false;\n  } // Min timestamp has 0 nanos\n  if (sBig === TIMESTAMP_MAX_SECONDS && nanos > 999_999_999) {\n    return false;\n  } // Max timestamp allows up to 999_999_999 nanos\n\n  return true;\n}\n\n// Helper function to adjust timestamp for negative nanoseconds\nfunction adjustTimestamp(\n  seconds: number,\n  nanos: number\n): { seconds: number; nanos: number } {\n  if (nanos < 0) {\n    // Ensure nanos is within [-1e9 + 1, -1] before adding 1e9\n    // Although the modulo operation should guarantee this range for negative results.\n    return {\n      seconds: seconds - 1,\n      nanos: nanos + 1_000_000_000\n    };\n  }\n  return { seconds, nanos };\n}\n\nfunction timestampToMicros(timestamp: Timestamp): bigint {\n  return (\n    BigInt(timestamp.seconds) * MICROSECONDS_PER_SECOND +\n    // Integer division truncates towards zero\n    BigInt(Math.trunc(timestamp.nanoseconds / 1000))\n  );\n}\n\nabstract class UnixToTimestamp implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0xc06e,\n      `${this.expr.name}() function should have exactly one parameter`\n    );\n\n    const value = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (value.type) {\n      case 'INT': {\n        return this.toTimestamp(BigInt(value.value!.integerValue!));\n      }\n      case 'NULL': {\n        return EvaluateResult.newNull();\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n  }\n\n  abstract toTimestamp(value: bigint): EvaluateResult;\n}\n\nexport class CoreUnixMicrosToTimestamp extends UnixToTimestamp {\n  toTimestamp(value: bigint): EvaluateResult {\n    if (!isMicrosInBounds(value)) {\n      return EvaluateResult.newError();\n    }\n\n    let seconds = Number(value / MICROSECONDS_PER_SECOND);\n    // Note: BigInt modulo can result in negative values if the dividend is negative.\n    let nanos = Number((value % MICROSECONDS_PER_SECOND) * BigInt(1000));\n\n    // Adjust for negative nanoseconds\n    const adjusted = adjustTimestamp(seconds, nanos);\n    seconds = adjusted.seconds;\n    nanos = adjusted.nanos;\n\n    // Final bounds check after adjustment\n    if (!isTimestampInBounds(seconds, nanos)) {\n      return EvaluateResult.newError();\n    }\n\n    return EvaluateResult.newValue({ timestampValue: { seconds, nanos } });\n  }\n}\n\nexport class CoreUnixMillisToTimestamp extends UnixToTimestamp {\n  toTimestamp(value: bigint): EvaluateResult {\n    if (!isMillisInBounds(value)) {\n      return EvaluateResult.newError();\n    }\n\n    let seconds = Number(value / MILLISECONDS_PER_SECOND);\n    let nanos = Number((value % MILLISECONDS_PER_SECOND) * BigInt(1000 * 1000));\n\n    // Adjust for negative nanoseconds\n    const adjusted = adjustTimestamp(seconds, nanos);\n    seconds = adjusted.seconds;\n    nanos = adjusted.nanos;\n\n    // Final bounds check after adjustment\n    if (!isTimestampInBounds(seconds, nanos)) {\n      return EvaluateResult.newError();\n    }\n\n    return EvaluateResult.newValue({ timestampValue: { seconds, nanos } });\n  }\n}\n\nexport class CoreUnixSecondsToTimestamp extends UnixToTimestamp {\n  toTimestamp(value: bigint): EvaluateResult {\n    if (!isSecondsInBounds(value)) {\n      return EvaluateResult.newError();\n    }\n\n    const seconds = Number(value);\n    return EvaluateResult.newValue({ timestampValue: { seconds, nanos: 0 } });\n  }\n}\n\nabstract class TimestampToUnix implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 1,\n      0x04f1,\n      `${this.expr.name}() function should have exactly one parameter`\n    );\n\n    const value = toEvaluable(this.expr.params[0]).evaluate(context, input);\n    switch (value.type) {\n      case 'TIMESTAMP': {\n        break;\n      }\n      case 'NULL': {\n        return EvaluateResult.newNull();\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n\n    const timestamp = fromTimestamp(value.value!.timestampValue!);\n    // Check if the input timestamp is within valid bounds\n    if (!isTimestampInBounds(timestamp.seconds, timestamp.nanoseconds)) {\n      return EvaluateResult.newError();\n    }\n\n    return this.toUnix(timestamp);\n  }\n\n  abstract toUnix(value: Timestamp): EvaluateResult;\n}\n\nexport class CoreTimestampToUnixMicros extends TimestampToUnix {\n  toUnix(timestamp: Timestamp): EvaluateResult {\n    const micros = timestampToMicros(timestamp);\n    // Check if the resulting micros are within representable bounds\n    if (!isMicrosInBounds(micros)) {\n      return EvaluateResult.newError();\n    }\n    return EvaluateResult.newValue({ integerValue: `${micros.toString()}` });\n  }\n}\n\nexport class CoreTimestampToUnixMillis extends TimestampToUnix {\n  toUnix(timestamp: Timestamp): EvaluateResult {\n    const micros = timestampToMicros(timestamp);\n    // Perform division, truncating towards zero (default JS BigInt division)\n    const millis = micros / BigInt(1000);\n    const submillis = micros % BigInt(1000);\n    if (millis > BigInt(0) || submillis === BigInt(0)) {\n      return EvaluateResult.newValue({ integerValue: millis.toString() });\n    } else {\n      return EvaluateResult.newValue({\n        integerValue: (millis - BigInt(1)).toString()\n      });\n    }\n  }\n}\n\nexport class CoreTimestampToUnixSeconds extends TimestampToUnix {\n  toUnix(timestamp: Timestamp): EvaluateResult {\n    // Seconds are directly available\n    const seconds = BigInt(timestamp.seconds);\n    // Check if the resulting seconds are within representable bounds\n    if (!isSecondsInBounds(seconds)) {\n      return EvaluateResult.newError();\n    }\n    return EvaluateResult.newValue({ integerValue: seconds.toString() });\n  }\n}\n\ntype TimeUnit =\n  | 'microsecond'\n  | 'millisecond'\n  | 'second'\n  | 'minute'\n  | 'hour'\n  | 'day';\nfunction asTimeUnit(unit?: string): TimeUnit | undefined {\n  switch (unit) {\n    case 'microsecond':\n      return 'microsecond';\n    case 'millisecond':\n      return 'millisecond';\n    case 'second':\n      return 'second';\n    case 'minute':\n      return 'minute';\n    case 'hour':\n      return 'hour';\n    case 'day':\n      return 'day';\n    default:\n      return undefined;\n  }\n}\n\nabstract class TimestampArithmetic implements EvaluableExpr {\n  constructor(private expr: FunctionExpression) {}\n  evaluate(\n    context: EvaluationContext,\n    input: PipelineInputOutput\n  ): EvaluateResult {\n    hardAssert(\n      this.expr.params.length === 3,\n      0x0ad7,\n      `${this.expr.name}() function should have exactly 3 parameters`\n    );\n\n    let foundNull = false;\n    const timestampVal = toEvaluable(this.expr.params[0]).evaluate(\n      context,\n      input\n    );\n    switch (timestampVal.type) {\n      case 'TIMESTAMP': {\n        break;\n      }\n      case 'NULL': {\n        foundNull = true;\n        break;\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n\n    const unitVal = toEvaluable(this.expr.params[1]).evaluate(context, input);\n    let timeUnit: TimeUnit | undefined;\n    switch (unitVal.type) {\n      case 'STRING': {\n        timeUnit = asTimeUnit(unitVal.value!.stringValue);\n        if (timeUnit === undefined) {\n          return EvaluateResult.newError();\n        }\n        break;\n      }\n      case 'NULL': {\n        foundNull = true;\n        break;\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n\n    const amountVal = toEvaluable(this.expr.params[2]).evaluate(context, input);\n    switch (amountVal.type) {\n      case 'INT': {\n        break;\n      }\n      case 'NULL': {\n        foundNull = true;\n        break;\n      }\n      default: {\n        return EvaluateResult.newError();\n      }\n    }\n\n    if (foundNull) {\n      return EvaluateResult.newNull();\n    }\n\n    const amount = BigInt(amountVal.value!.integerValue!);\n    let microsToOperate: bigint;\n    try {\n      switch (timeUnit) {\n        case 'microsecond':\n          microsToOperate = amount;\n          break;\n        case 'millisecond':\n          microsToOperate = amount * BigInt(1000);\n          break;\n        case 'second':\n          microsToOperate = amount * BigInt(1000000);\n          break;\n        case 'minute':\n          microsToOperate = amount * BigInt(60000000);\n          break;\n        case 'hour':\n          microsToOperate = amount * BigInt(3600000000);\n          break;\n        case 'day':\n          microsToOperate = amount * BigInt(86400000000);\n          break;\n        default:\n          return EvaluateResult.newError();\n      }\n      // Check for potential overflow during multiplication\n      if (\n        timeUnit !== 'microsecond' &&\n        amount !== BigInt(0) &&\n        microsToOperate / amount !== BigInt(this.getMultiplier(timeUnit))\n      ) {\n        return EvaluateResult.newError();\n      }\n    } catch (e) {\n      // Catch potential BigInt errors (though unlikely with isInteger check)\n      logWarn(`Error during timestamp arithmetic: ${e}`);\n      return EvaluateResult.newError();\n    }\n\n    const initialTimestamp = fromTimestamp(timestampVal.value!.timestampValue!);\n    // Check initial timestamp bounds\n    if (\n      !isTimestampInBounds(\n        initialTimestamp.seconds,\n        initialTimestamp.nanoseconds\n      )\n    ) {\n      return EvaluateResult.newError();\n    }\n\n    const initialMicros = timestampToMicros(initialTimestamp);\n    const newMicros = this.newMicros(initialMicros, microsToOperate);\n\n    // Check final microsecond bounds\n    if (!isMicrosInBounds(newMicros)) {\n      return EvaluateResult.newError();\n    }\n\n    // Convert back to seconds and nanos\n    const newSeconds = Number(newMicros / MICROSECONDS_PER_SECOND);\n    const nanosRemainder = newMicros % MICROSECONDS_PER_SECOND;\n    const newNanos = Number(\n      (nanosRemainder < 0\n        ? nanosRemainder + MICROSECONDS_PER_SECOND\n        : nanosRemainder) * BigInt(1000)\n    );\n    const adjustedSeconds = nanosRemainder < 0 ? newSeconds - 1 : newSeconds;\n\n    // Final check on calculated timestamp bounds\n    if (!isTimestampInBounds(adjustedSeconds, newNanos)) {\n      return EvaluateResult.newError();\n    }\n\n    return EvaluateResult.newValue({\n      timestampValue: { seconds: adjustedSeconds, nanos: newNanos }\n    });\n  }\n\n  private getMultiplier(unit: TimeUnit): number {\n    switch (unit) {\n      case 'millisecond':\n        return 1000;\n      case 'second':\n        return 1000000;\n      case 'minute':\n        return 60000000;\n      case 'hour':\n        return 3600000000;\n      case 'day':\n        return 86400000000;\n      default:\n        return 1; // microsecond\n    }\n  }\n\n  abstract newMicros(initialMicros: bigint, microsToOperation: bigint): bigint;\n}\n\nexport class CoreTimestampAdd extends TimestampArithmetic {\n  newMicros(initialMicros: bigint, microsToAdd: bigint): bigint {\n    return initialMicros + microsToAdd;\n  }\n}\n\nexport class CoreTimestampSub extends TimestampArithmetic {\n  newMicros(initialMicros: bigint, microsToSub: bigint): bigint {\n    return initialMicros - microsToSub;\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 { RealtimePipeline } from '../api/realtime_pipeline';\nimport { Firestore } from '../lite-api/database';\nimport {\n  Constant,\n  Expression,\n  Field,\n  BooleanExpression,\n  and,\n  or,\n  Ordering,\n  lessThan,\n  greaterThan,\n  field,\n  FunctionExpression\n} from '../lite-api/expressions';\nimport { Pipeline, Pipeline as ApiPipeline } from '../lite-api/pipeline';\nimport { doc, DocumentReference } from '../lite-api/reference';\nimport {\n  AddFields,\n  Aggregate,\n  CollectionGroupSource,\n  CollectionSource,\n  DatabaseSource,\n  Distinct,\n  DocumentsSource,\n  Limit,\n  Offset,\n  Sort,\n  Stage,\n  Where\n} from '../lite-api/stage';\nimport { UserDataSource } from '../lite-api/user_data_reader';\nimport { VectorValue } from '../lite-api/vector_value';\nimport { DOCUMENT_KEY_NAME, ResourcePath } from '../model/path';\nimport { fail } from '../util/assert';\n\nimport { Bound } from './bound';\nimport { ListenOptions } from './event_manager';\nimport { unwrapExpression } from './expressions';\nimport {\n  CompositeFilter as CompositeFilterInternal,\n  CompositeOperator,\n  FieldFilter as FieldFilterInternal,\n  Filter as FilterInternal,\n  Operator\n} from './filter';\nimport { Direction } from './order_by';\nimport { CorePipeline } from './pipeline';\nimport {\n  canonifyQuery,\n  isCollectionGroupQuery,\n  isDocumentQuery,\n  LimitType,\n  Query,\n  queryEquals,\n  queryNormalizedOrderBy,\n  stringifyQuery\n} from './query';\nimport {\n  canonifyTarget,\n  Target,\n  targetEquals,\n  targetIsPipelineTarget\n} from './target';\n\n/* eslint @typescript-eslint/no-explicit-any: 0 */\n\nexport function toPipelineBooleanExpr(f: FilterInternal): BooleanExpression {\n  if (f instanceof FieldFilterInternal) {\n    const fieldValue = field(f.field.toString());\n    // Comparison filters\n    const value = f.value;\n    switch (f.op) {\n      case Operator.LESS_THAN:\n        return and(\n          fieldValue.exists(),\n          fieldValue.lessThan(Constant._fromProto(value))\n        );\n      case Operator.LESS_THAN_OR_EQUAL:\n        return and(\n          fieldValue.exists(),\n          fieldValue.lessThanOrEqual(Constant._fromProto(value))\n        );\n      case Operator.GREATER_THAN:\n        return and(\n          fieldValue.exists(),\n          fieldValue.greaterThan(Constant._fromProto(value))\n        );\n      case Operator.GREATER_THAN_OR_EQUAL:\n        return and(\n          fieldValue.exists(),\n          fieldValue.greaterThanOrEqual(Constant._fromProto(value))\n        );\n      case Operator.EQUAL:\n        return and(\n          fieldValue.exists(),\n          fieldValue.equal(Constant._fromProto(value))\n        );\n      case Operator.NOT_EQUAL:\n        return fieldValue.notEqual(Constant._fromProto(value));\n      case Operator.ARRAY_CONTAINS:\n        return and(\n          fieldValue.exists(),\n          fieldValue.arrayContains(Constant._fromProto(value))\n        );\n      case Operator.IN: {\n        const values = value?.arrayValue?.values?.map((val: any) =>\n          Constant._fromProto(val)\n        );\n        if (!values) {\n          return and(fieldValue.exists(), fieldValue.equalAny([]));\n        } else if (values.length === 1) {\n          return and(fieldValue.exists(), fieldValue.equal(values[0]));\n        } else {\n          return and(fieldValue.exists(), fieldValue.equalAny(values));\n        }\n      }\n      case Operator.ARRAY_CONTAINS_ANY: {\n        const values = value?.arrayValue?.values?.map((val: any) =>\n          Constant._fromProto(val)\n        );\n        return and(fieldValue.exists(), fieldValue.arrayContainsAny(values!));\n      }\n      case Operator.NOT_IN: {\n        const values = value?.arrayValue?.values?.map((val: any) =>\n          Constant._fromProto(val)\n        );\n        if (!values) {\n          return fieldValue.notEqualAny([]);\n        } else if (values.length === 1) {\n          return fieldValue.notEqual(values[0]);\n        } else {\n          return fieldValue.notEqualAny(values);\n        }\n      }\n      default:\n        fail(0x9047, 'Unexpected operator');\n    }\n  } else if (f instanceof CompositeFilterInternal) {\n    switch (f.op) {\n      case CompositeOperator.AND: {\n        const conditions = f.getFilters().map(f => toPipelineBooleanExpr(f));\n        return and(conditions[0], conditions[1], ...conditions.slice(2));\n      }\n      case CompositeOperator.OR: {\n        const conditions = f.getFilters().map(f => toPipelineBooleanExpr(f));\n        return or(conditions[0], conditions[1], ...conditions.slice(2));\n      }\n      default:\n        fail(0x89ea, 'Unexpected operator');\n    }\n  }\n\n  throw new Error(`Failed to convert filter to pipeline conditions: ${f}`);\n}\n\nfunction reverseOrderings(orderings: Ordering[]): Ordering[] {\n  return orderings.map(\n    o =>\n      new Ordering(\n        o.expr,\n        o.direction === 'ascending' ? 'descending' : 'ascending',\n        undefined\n      )\n  );\n}\n\nexport function toPipelineStages(query: Query, db: Firestore): Stage[] {\n  let pipeline: Pipeline;\n  if (isCollectionGroupQuery(query)) {\n    pipeline = db.pipeline().collectionGroup(query.collectionGroup!);\n  } else if (isDocumentQuery(query)) {\n    pipeline = db.pipeline().documents([doc(db, query.path.canonicalString())]);\n  } else {\n    pipeline = db.pipeline().collection(query.path.canonicalString());\n  }\n\n  // filters\n  for (const filter of query.filters) {\n    pipeline = pipeline.where(toPipelineBooleanExpr(filter));\n  }\n\n  // orders\n  const orders = queryNormalizedOrderBy(query);\n  const existsConditions = orders.map(order =>\n    field(order.field.canonicalString()).exists()\n  );\n  if (existsConditions.length > 1) {\n    pipeline = pipeline.where(\n      and(\n        existsConditions[0],\n        existsConditions[1],\n        ...existsConditions.slice(2)\n      )\n    );\n  } else {\n    pipeline = pipeline.where(existsConditions[0]);\n  }\n\n  const orderings = orders.map(order =>\n    order.dir === Direction.ASCENDING\n      ? field(order.field.canonicalString()).ascending()\n      : field(order.field.canonicalString()).descending()\n  );\n\n  if (orderings.length > 0) {\n    if (query.limitType === LimitType.Last) {\n      const actualOrderings = reverseOrderings(orderings);\n      pipeline = pipeline.sort(actualOrderings[0], ...actualOrderings.slice(1));\n      // cursors\n      if (query.startAt !== null) {\n        pipeline = pipeline.where(\n          whereConditionsFromCursor(query.startAt, orderings, 'after')\n        );\n      }\n\n      if (query.endAt !== null) {\n        pipeline = pipeline.where(\n          whereConditionsFromCursor(query.endAt, orderings, 'before')\n        );\n      }\n\n      pipeline = pipeline.limit(query.limit!);\n      pipeline = pipeline.sort(orderings[0], ...orderings.slice(1));\n    } else {\n      pipeline = pipeline.sort(orderings[0], ...orderings.slice(1));\n      if (query.startAt !== null) {\n        pipeline = pipeline.where(\n          whereConditionsFromCursor(query.startAt, orderings, 'after')\n        );\n      }\n      if (query.endAt !== null) {\n        pipeline = pipeline.where(\n          whereConditionsFromCursor(query.endAt, orderings, 'before')\n        );\n      }\n\n      if (query.limit !== null) {\n        pipeline = pipeline.limit(query.limit);\n      }\n    }\n  }\n\n  return pipeline.stages;\n}\n\nfunction whereConditionsFromCursor(\n  bound: Bound,\n  orderings: Ordering[],\n  position: 'before' | 'after'\n): BooleanExpression {\n  // The filterFunc is either greater than or less than\n  const filterFunc = position === 'before' ? lessThan : greaterThan;\n  const cursors = bound.position.map(value => Constant._fromProto(value));\n  const size = cursors.length;\n\n  let field = orderings[size - 1].expr;\n  let value = cursors[size - 1];\n\n  // Add condition for last bound\n  let condition: BooleanExpression = filterFunc(field, value);\n  if (bound.inclusive) {\n    // When the cursor bound is inclusive, then the last bound\n    // can be equal to the value, otherwise it's not equal\n    condition = or(condition, field.equal(value));\n  }\n\n  // Iterate backwards over the remaining bounds, adding\n  // a condition for each one\n  for (let i = size - 2; i >= 0; i--) {\n    field = orderings[i].expr;\n    value = cursors[i];\n\n    // For each field in the orderings, the condition is either\n    // a) lt|gt the cursor value,\n    // b) or equal the cursor value and lt|gt the cursor values for other fields\n    condition = or(\n      filterFunc(field, value),\n      and(field.equal(value), condition)\n    );\n  }\n\n  return condition;\n}\n\nfunction canonifyConstantValue(value: unknown): string {\n  if (value === null) {\n    return 'null';\n  } else if (typeof value === 'number') {\n    return value.toString();\n  } else if (typeof value === 'string') {\n    return `\"${value}\"`;\n  } else if (value instanceof DocumentReference) {\n    return `ref(${value.path})`;\n  } else if (value instanceof VectorValue) {\n    return `vec(${JSON.stringify(value)})`;\n  }\n  {\n    return JSON.stringify(value);\n  }\n}\n\nexport function canonifyExpr(expr: Expression): string {\n  expr = unwrapExpression(expr);\n\n  if (expr instanceof Field) {\n    return `fld(${expr.fieldName})`;\n  }\n  if (expr instanceof Constant) {\n    return `cst(${canonifyConstantValue(expr.value)})`;\n  }\n  if (expr instanceof FunctionExpression) {\n    return `fn(${expr.name},[${expr.params.map(canonifyExpr).join(',')}])`;\n  }\n  if ((expr as any).expressionType === 'ListOfExpressions') {\n    return `list([${(expr as any).exprs.map(canonifyExpr).join(',')}])`;\n  }\n  throw new Error(`Unrecognized expr ${JSON.stringify(expr, null, 2)}`);\n}\n\nfunction canonifySortOrderings(orders: Ordering[]): string {\n  return orders.map(o => `${canonifyExpr(o.expr)}${o.direction}`).join(',');\n}\n\nfunction canonifyStage(stage: Stage): string {\n  if (stage instanceof AddFields) {\n    return `${stage._name}(${canonifyExprMap(stage.fields)})`;\n  }\n  if (stage instanceof Aggregate) {\n    let result = `${stage._name}(${canonifyExprMap(\n      stage.accumulators as unknown as Map<string, Expression>\n    )})`;\n    if (stage.groups.size > 0) {\n      result = result + `grouping(${canonifyExprMap(stage.groups)})`;\n    }\n    return result;\n  }\n  if (stage instanceof Distinct) {\n    return `${stage._name}(${canonifyExprMap(stage.groups)})`;\n  }\n  if (stage instanceof CollectionSource) {\n    return `${stage._name}(${stage.formattedCollectionPath})`;\n  }\n  if (stage instanceof CollectionGroupSource) {\n    return `${stage._name}(${stage.collectionId})`;\n  }\n  if (stage instanceof DatabaseSource) {\n    return `${stage._name}()`;\n  }\n  if (stage instanceof DocumentsSource) {\n    return `${stage._name}(${stage.formattedPaths.sort()})`;\n  }\n  if (stage instanceof Where) {\n    return `${stage._name}(${canonifyExpr(stage.condition)})`;\n  }\n  if (stage instanceof Limit) {\n    return `${stage._name}(${stage.limit})`;\n  }\n  if (stage instanceof Sort) {\n    return `${stage._name}(${canonifySortOrderings(stage.orderings)})`;\n  }\n\n  throw new Error(`Unrecognized stage ${stage._name}`);\n}\n\nfunction canonifyExprMap(map: Map<string, Expression>): string {\n  const sortedEntries = Array.from(map.entries()).sort();\n  return `${sortedEntries\n    .map(([key, val]) => `${key}=${canonifyExpr(val)}`)\n    .join(',')}`;\n}\n\nexport function canonifyPipeline(p: CorePipeline): string;\nexport function canonifyPipeline(p: CorePipeline): string {\n  return p.stages.map(s => canonifyStage(s)).join('|');\n}\n\n// TODO(pipeline): do a proper implementation for eq.\nexport function pipelineEq(left: CorePipeline, right: CorePipeline): boolean {\n  return canonifyPipeline(left) === canonifyPipeline(right);\n}\n\nexport type PipelineFlavor = 'exact' | 'augmented' | 'keyless';\n\nexport type PipelineSourceType =\n  | 'collection'\n  | 'collection_group'\n  | 'database'\n  | 'documents';\n\nexport function asCollectionPipelineAtPath(\n  pipeline: CorePipeline,\n  path: ResourcePath\n): CorePipeline {\n  const newStages = pipeline.stages.map(s => {\n    if (s instanceof CollectionGroupSource) {\n      return new CollectionSource(path.canonicalString(), {});\n    }\n\n    return s;\n  });\n\n  return new CorePipeline(pipeline.serializer, newStages);\n}\n\nexport type QueryOrPipeline = Query | CorePipeline;\n\nexport function isPipeline(q: QueryOrPipeline): q is CorePipeline {\n  return q instanceof CorePipeline;\n}\n\nexport function stringifyQueryOrPipeline(q: QueryOrPipeline): string {\n  if (isPipeline(q)) {\n    return canonifyPipeline(q);\n  }\n\n  return stringifyQuery(q);\n}\n\nexport function canonifyQueryOrPipeline(q: QueryOrPipeline): string {\n  if (isPipeline(q)) {\n    return canonifyPipeline(q);\n  }\n\n  return canonifyQuery(q);\n}\n\nexport function queryOrPipelineEqual(\n  left: QueryOrPipeline,\n  right: QueryOrPipeline\n): boolean {\n  if (left instanceof CorePipeline && right instanceof CorePipeline) {\n    return pipelineEq(left, right);\n  }\n  if (\n    (left instanceof CorePipeline && !(right instanceof CorePipeline)) ||\n    (!(left instanceof CorePipeline) && right instanceof CorePipeline)\n  ) {\n    return false;\n  }\n\n  return queryEquals(left as Query, right as Query);\n}\n\nexport type TargetOrPipeline = Target | CorePipeline;\n\nexport function canonifyTargetOrPipeline(q: TargetOrPipeline): string {\n  if (targetIsPipelineTarget(q)) {\n    return canonifyPipeline(q);\n  }\n\n  return canonifyTarget(q as Target);\n}\n\nexport function targetOrPipelineEqual(\n  left: TargetOrPipeline,\n  right: TargetOrPipeline\n): boolean {\n  if (left instanceof CorePipeline && right instanceof CorePipeline) {\n    return pipelineEq(left, right);\n  }\n  if (\n    (left instanceof CorePipeline && !(right instanceof CorePipeline)) ||\n    (!(left instanceof CorePipeline) && right instanceof CorePipeline)\n  ) {\n    return false;\n  }\n\n  return targetEquals(left as Target, right as Target);\n}\n\nexport function pipelineHasRanges(pipeline: CorePipeline): boolean {\n  return pipeline.stages.some(\n    stage => stage instanceof Limit || stage instanceof Offset\n  );\n}\n\nfunction rewriteStages(stages: Stage[]): Stage[] {\n  let hasOrder = false;\n  const newStages: Stage[] = [];\n  for (const stage of stages) {\n    // For stages that provide ordering semantics\n    if (stage instanceof Sort) {\n      hasOrder = true;\n      // Ensure we have a stable ordering\n      if (\n        stage.orderings.some(\n          order =>\n            order.expr instanceof Field &&\n            order.expr.fieldName === DOCUMENT_KEY_NAME\n        )\n      ) {\n        newStages.push(stage);\n      } else {\n        const copy = stage.orderings.map(o => o);\n        copy.push(field(DOCUMENT_KEY_NAME).ascending());\n        newStages.push(new Sort(copy, {}));\n      }\n    }\n    // For stages whose semantics depend on ordering\n    else if (stage instanceof Limit) {\n      if (!hasOrder) {\n        newStages.push(new Sort([field(DOCUMENT_KEY_NAME).ascending()], {}));\n        hasOrder = true;\n      }\n      newStages.push(stage);\n    } else {\n      newStages.push(stage);\n    }\n  }\n\n  if (!hasOrder) {\n    newStages.push(new Sort([field(DOCUMENT_KEY_NAME).ascending()], {}));\n  }\n\n  return newStages;\n}\n\n// function addSystemFields(\n//   fields: Map<string, Expression>\n// ): Map<string, Expression> {\n//   const newFields = new Map<string, Expression>(fields);\n//   newFields.set(DOCUMENT_KEY_NAME, field(DOCUMENT_KEY_NAME));\n//   newFields.set(CREATE_TIME_NAME, field(CREATE_TIME_NAME));\n//   newFields.set(UPDATE_TIME_NAME, field(UPDATE_TIME_NAME));\n//   return newFields;\n// }\n\nexport function toCorePipeline(\n  p: ApiPipeline | RealtimePipeline,\n  listenOptions?: ListenOptions\n): CorePipeline {\n  const newStages = rewriteStages(p.stages);\n  if (p.userDataReader) {\n    const context = p.userDataReader.createContext(\n      UserDataSource.Argument,\n      'toCorePipeline'\n    );\n    newStages.forEach(stage => stage._readUserData(context));\n  }\n  return new CorePipeline(\n    p.userDataReader!.serializer,\n    newStages,\n    listenOptions\n  );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport {\n  documentKeySet,\n  DocumentKeySet,\n  MutationMap,\n  DocumentVersionMap,\n  documentVersionMap,\n  newMutationMap,\n  OverlayedDocumentMap\n} from './collections';\nimport { MutableDocument } from './document';\nimport { FieldMask } from './field_mask';\nimport {\n  calculateOverlayMutation,\n  Mutation,\n  mutationApplyToLocalView,\n  mutationApplyToRemoteDocument,\n  mutationEquals,\n  MutationResult\n} from './mutation';\n\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */\nexport class MutationBatch {\n  /**\n   * @param batchId - The unique ID of this mutation batch.\n   * @param localWriteTime - The original write time of this mutation.\n   * @param baseMutations - Mutations that are used to populate the base\n   * values when this mutation is applied locally. This can be used to locally\n   * overwrite values that are persisted in the remote document cache. Base\n   * mutations are never sent to the backend.\n   * @param mutations - The user-provided mutations in this mutation batch.\n   * User-provided mutations are applied both locally and remotely on the\n   * backend.\n   */\n  constructor(\n    public batchId: BatchId,\n    public localWriteTime: Timestamp,\n    public baseMutations: Mutation[],\n    public mutations: Mutation[]\n  ) {\n    debugAssert(mutations.length > 0, 'Cannot create an empty mutation batch');\n  }\n\n  /**\n   * Applies all the mutations in this MutationBatch to the specified document\n   * to compute the state of the remote document\n   *\n   * @param document - The document to apply mutations to.\n   * @param batchResult - The result of applying the MutationBatch to the\n   * backend.\n   */\n  applyToRemoteDocument(\n    document: MutableDocument,\n    batchResult: MutationBatchResult\n  ): void {\n    const mutationResults = batchResult.mutationResults;\n    debugAssert(\n      mutationResults.length === this.mutations.length,\n      `Mismatch between mutations length\n      (${this.mutations.length}) and mutation results length\n      (${mutationResults.length}).`\n    );\n\n    for (let i = 0; i < this.mutations.length; i++) {\n      const mutation = this.mutations[i];\n      if (mutation.key.isEqual(document.key)) {\n        const mutationResult = mutationResults[i];\n        mutationApplyToRemoteDocument(mutation, document, mutationResult);\n      }\n    }\n  }\n\n  /**\n   * Computes the local view of a document given all the mutations in this\n   * batch.\n   *\n   * @param document - The document to apply mutations to.\n   * @param mutatedFields - Fields that have been updated before applying this mutation batch.\n   * @returns A `FieldMask` representing all the fields that are mutated.\n   */\n  applyToLocalView(\n    document: MutableDocument,\n    mutatedFields: FieldMask | null\n  ): FieldMask | null {\n    // First, apply the base state. This allows us to apply non-idempotent\n    // transform against a consistent set of values.\n    for (const mutation of this.baseMutations) {\n      if (mutation.key.isEqual(document.key)) {\n        mutatedFields = mutationApplyToLocalView(\n          mutation,\n          document,\n          mutatedFields,\n          this.localWriteTime\n        );\n      }\n    }\n\n    // Second, apply all user-provided mutations.\n    for (const mutation of this.mutations) {\n      if (mutation.key.isEqual(document.key)) {\n        mutatedFields = mutationApplyToLocalView(\n          mutation,\n          document,\n          mutatedFields,\n          this.localWriteTime\n        );\n      }\n    }\n    return mutatedFields;\n  }\n\n  /**\n   * Computes the local view for all provided documents given the mutations in\n   * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to\n   * replace all the mutation applications.\n   */\n  applyToLocalDocumentSet(\n    documentMap: OverlayedDocumentMap,\n    documentsWithoutRemoteVersion: DocumentKeySet\n  ): MutationMap {\n    // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\n    // directly (as done in `applyToLocalView()`), we can reduce the complexity\n    // to O(n).\n    const overlays = newMutationMap();\n    this.mutations.forEach(m => {\n      const overlayedDocument = documentMap.get(m.key)!;\n      // TODO(mutabledocuments): This method should take a MutableDocumentMap\n      // and we should remove this cast.\n      const mutableDocument =\n        overlayedDocument.overlayedDocument as MutableDocument;\n      let mutatedFields = this.applyToLocalView(\n        mutableDocument,\n        overlayedDocument.mutatedFields\n      );\n      // Set mutatedFields to null if the document is only from local mutations.\n      // This creates a Set or Delete mutation, instead of trying to create a\n      // patch mutation as the overlay.\n      mutatedFields = documentsWithoutRemoteVersion.has(m.key)\n        ? null\n        : mutatedFields;\n      const overlay = calculateOverlayMutation(mutableDocument, mutatedFields);\n      if (overlay !== null) {\n        overlays.set(m.key, overlay);\n      }\n\n      if (!mutableDocument.isValidDocument()) {\n        mutableDocument.convertToNoDocument(SnapshotVersion.min());\n      }\n    });\n    return overlays;\n  }\n\n  keys(): DocumentKeySet {\n    return this.mutations.reduce(\n      (keys, m) => keys.add(m.key),\n      documentKeySet()\n    );\n  }\n\n  isEqual(other: MutationBatch): boolean {\n    return (\n      this.batchId === other.batchId &&\n      arrayEquals(this.mutations, other.mutations, (l, r) =>\n        mutationEquals(l, r)\n      ) &&\n      arrayEquals(this.baseMutations, other.baseMutations, (l, r) =>\n        mutationEquals(l, r)\n      )\n    );\n  }\n}\n\n/** The result of applying a mutation batch to the backend. */\nexport class MutationBatchResult {\n  private constructor(\n    readonly batch: MutationBatch,\n    readonly commitVersion: SnapshotVersion,\n    readonly mutationResults: MutationResult[],\n    /**\n     * A pre-computed mapping from each mutated document to the resulting\n     * version.\n     */\n    readonly docVersions: DocumentVersionMap\n  ) {}\n\n  /**\n   * Creates a new MutationBatchResult for the given batch and results. There\n   * must be one result for each mutation in the batch. This static factory\n   * caches a document=&gt;version mapping (docVersions).\n   */\n  static from(\n    batch: MutationBatch,\n    commitVersion: SnapshotVersion,\n    results: MutationResult[]\n  ): MutationBatchResult {\n    hardAssert(\n      batch.mutations.length === results.length,\n      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 { TargetOrPipeline } from '../core/pipeline-util';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, RemoteTargetId, 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<T extends TargetId | RemoteTargetId = TargetId> {\n  constructor(\n    /** The target being listened to. */\n    readonly target: TargetOrPipeline,\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: T,\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<T> {\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<T> {\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<T> {\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<T> {\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 { CorePipeline } from '../core/pipeline';\nimport {\n  canonifyTargetOrPipeline,\n  TargetOrPipeline\n} from '../core/pipeline-util';\nimport { LimitType, Query, queryWithLimit } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, targetIsPipelineTarget } from '../core/target';\nimport {\n  BooleanExpression,\n  Constant,\n  Expression,\n  Field,\n  FunctionExpression,\n  Ordering\n} from '../lite-api/expressions';\nimport {\n  CollectionGroupSource,\n  CollectionSource,\n  DatabaseSource,\n  DocumentsSource,\n  Limit,\n  Sort,\n  Stage,\n  Where\n} from '../lite-api/stage';\nimport { fieldPathFromArgument } from '../lite-api/user_data_reader';\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 {\n  DocumentsTarget as PublicDocumentsTarget,\n  PipelineQueryTarget as ProtoPipelineQueryTarget,\n  PipelineQueryTarget as PublicPipelineQueryTarget,\n  Stage as ProtoStage,\n  Value as ProtoValue\n} 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  toPipelineTarget,\n  toQueryTarget\n} from '../remote/serializer';\nimport { debugAssert, fail, hardAssert } 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(\n  serializer: LocalSerializer,\n  dbTarget: DbTarget\n): 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: TargetOrPipeline;\n  if (isPipelineQueryTarget(dbTarget.query)) {\n    target = fromPipelineTarget(dbTarget.query, serializer.remoteSerializer);\n  } else 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 (targetIsPipelineTarget(targetData.target)) {\n    queryProto = toPipelineTarget(\n      localSerializer.remoteSerializer,\n      targetData.target\n    );\n  } else 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: canonifyTargetOrPipeline(targetData.target),\n    readTime: dbTimestamp,\n    resumeToken,\n    lastListenSequenceNumber: targetData.sequenceNumber,\n    lastLimboFreeSnapshotVersion: dbLastLimboFreeTimestamp,\n    query: queryProto\n  };\n}\n\nfunction isPipelineQueryTarget(\n  dbQuery: DbQuery\n): dbQuery is PublicPipelineQueryTarget {\n  return (\n    (dbQuery as PublicPipelineQueryTarget).structuredPipeline !== undefined\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\nexport function fromPipelineTarget(\n  target: ProtoPipelineQueryTarget,\n  serializer: JsonProtoSerializer\n): CorePipeline {\n  const pipeline = target.structuredPipeline;\n  hardAssert(\n    (pipeline?.pipeline?.stages ?? []).length > 0,\n    0x0735,\n    'Deserializing pipeline without any stages.'\n  );\n\n  const stages = pipeline?.pipeline?.stages!.map(stageFromProto);\n\n  return new CorePipeline(serializer, stages!);\n}\n\nfunction stageFromProto(protoStage: ProtoStage): Stage {\n  switch (protoStage.name) {\n    case 'collection': {\n      return new CollectionSource(protoStage.args![0].referenceValue!, {});\n    }\n    case 'collection_group': {\n      return new CollectionGroupSource(protoStage.args![1].stringValue!, {});\n    }\n    case 'database': {\n      return new DatabaseSource({});\n    }\n    case 'documents': {\n      return new DocumentsSource(\n        protoStage.args!.map(arg => arg.referenceValue!),\n        {}\n      );\n    }\n    case 'where': {\n      return new Where(\n        exprFromProto(protoStage.args![0]) as BooleanExpression,\n        {}\n      );\n    }\n    case 'limit': {\n      const limitValue =\n        protoStage.args![0].integerValue ?? protoStage.args![0].doubleValue!;\n      return new Limit(\n        typeof limitValue === 'number' ? limitValue : Number(limitValue),\n        {}\n      );\n    }\n    case 'sort': {\n      return new Sort(\n        protoStage.args!.map(arg => orderingFromProto(arg)),\n        {}\n      );\n    }\n    default: {\n      throw new Error(`Stage type: ${protoStage.name} not supported.`);\n    }\n  }\n}\n\nfunction exprFromProto(value: ProtoValue): Expression {\n  if (!!value.fieldReferenceValue) {\n    return new Field(\n      fieldPathFromArgument('_exprFromProto', value.fieldReferenceValue),\n      '_exprFromProto'\n    );\n  } else if (!!value.functionValue) {\n    return functionFromProto(value);\n  } else {\n    return Constant._fromProto(value);\n  }\n}\n\nfunction functionFromProto(value: ProtoValue): FunctionExpression {\n  // TODO(pipeline): When aggregation is supported, we need to return AggregateFunction for the functions\n  // with aggregate names (sum, count, etc).\n  return new FunctionExpression(\n    value.functionValue!.name!,\n    value.functionValue!.args?.map(exprFromProto) || []\n  );\n}\n\nfunction orderingFromProto(value: ProtoValue): Ordering {\n  const fields = value.mapValue?.fields!;\n  return new Ordering(\n    exprFromProto(fields.expression),\n    fields.direction?.stringValue! as 'ascending' | 'descending',\n    'orderingFromProto'\n  );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n  BundleMetadata as ProtoBundleMetadata,\n  NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport { DbBundle, DbNamedQuery } from './indexeddb_schema';\nimport {\n  DbBundlesKey,\n  DbBundleStore,\n  DbNamedQueriesKey,\n  DbNamedQueryStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n  fromDbBundle,\n  fromDbNamedQuery,\n  toDbBundle,\n  toDbNamedQuery\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nexport class IndexedDbBundleCache implements BundleCache {\n  getBundleMetadata(\n    transaction: PersistenceTransaction,\n    bundleId: string\n  ): PersistencePromise<BundleMetadata | undefined> {\n    return bundlesStore(transaction)\n      .get(bundleId)\n      .next(bundle => {\n        if (bundle) {\n          return fromDbBundle(bundle);\n        }\n        return undefined;\n      });\n  }\n\n  saveBundleMetadata(\n    transaction: PersistenceTransaction,\n    bundleMetadata: ProtoBundleMetadata\n  ): PersistencePromise<void> {\n    return bundlesStore(transaction).put(toDbBundle(bundleMetadata));\n  }\n\n  getNamedQuery(\n    transaction: PersistenceTransaction,\n    queryName: string\n  ): PersistencePromise<NamedQuery | undefined> {\n    return namedQueriesStore(transaction)\n      .get(queryName)\n      .next(query => {\n        if (query) {\n          return fromDbNamedQuery(query);\n        }\n        return undefined;\n      });\n  }\n\n  saveNamedQuery(\n    transaction: PersistenceTransaction,\n    query: ProtoNamedQuery\n  ): PersistencePromise<void> {\n    return namedQueriesStore(transaction).put(toDbNamedQuery(query));\n  }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */\nfunction bundlesStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbBundlesKey, DbBundle> {\n  return getStore<DbBundlesKey, DbBundle>(txn, DbBundleStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */\nfunction namedQueriesStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbNamedQueriesKey, DbNamedQuery> {\n  return getStore<DbNamedQueriesKey, DbNamedQuery>(txn, DbNamedQueryStore);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport {\n  DocumentKeySet,\n  MutationMap,\n  OverlayMap,\n  newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { DbDocumentOverlay } from './indexeddb_schema';\nimport {\n  DbDocumentOverlayCollectionGroupOverlayIndex,\n  DbDocumentOverlayCollectionPathOverlayIndex,\n  DbDocumentOverlayKey,\n  DbDocumentOverlayStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n  fromDbDocumentOverlay,\n  LocalSerializer,\n  toDbDocumentOverlay,\n  toDbDocumentOverlayKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */\nexport class IndexedDbDocumentOverlayCache implements DocumentOverlayCache {\n  /**\n   * @param serializer - The document serializer.\n   * @param userId - The userId for which we are accessing overlays.\n   */\n  constructor(\n    private readonly serializer: LocalSerializer,\n    private readonly userId: string\n  ) {}\n\n  static forUser(\n    serializer: LocalSerializer,\n    user: User\n  ): IndexedDbDocumentOverlayCache {\n    const userId = user.uid || '';\n    return new IndexedDbDocumentOverlayCache(serializer, userId);\n  }\n\n  getOverlay(\n    transaction: PersistenceTransaction,\n    key: DocumentKey\n  ): PersistencePromise<Overlay | null> {\n    return documentOverlayStore(transaction)\n      .get(toDbDocumentOverlayKey(this.userId, key))\n      .next(dbOverlay => {\n        if (dbOverlay) {\n          return fromDbDocumentOverlay(this.serializer, dbOverlay);\n        }\n        return null;\n      });\n  }\n\n  getOverlays(\n    transaction: PersistenceTransaction,\n    keys: DocumentKey[]\n  ): PersistencePromise<OverlayMap> {\n    const result = newOverlayMap();\n    return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n      return this.getOverlay(transaction, key).next(overlay => {\n        if (overlay !== null) {\n          result.set(key, overlay);\n        }\n      });\n    }).next(() => result);\n  }\n\n  getAllOverlays(\n    transaction: PersistenceTransaction,\n    sinceBatchId: number\n  ): PersistencePromise<OverlayMap> {\n    const overlays = newOverlayMap();\n    // TODO(pipeline): should we create an index for this? But how often people really expect\n    // querying entire database to be fast?\n    return documentOverlayStore(transaction)\n      .iterate((dbOverlayKey, dbOverlay) => {\n        const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n        if (overlay.largestBatchId > sinceBatchId) {\n          overlays.set(overlay.getKey(), overlay);\n        }\n      })\n      .next(() => overlays);\n  }\n\n  saveOverlays(\n    transaction: PersistenceTransaction,\n    largestBatchId: number,\n    overlays: MutationMap\n  ): PersistencePromise<void> {\n    const promises: Array<PersistencePromise<void>> = [];\n    overlays.forEach((_, mutation) => {\n      const overlay = new Overlay(largestBatchId, mutation);\n      promises.push(this.saveOverlay(transaction, overlay));\n    });\n    return PersistencePromise.waitFor(promises);\n  }\n\n  removeOverlaysForBatchId(\n    transaction: PersistenceTransaction,\n    documentKeys: DocumentKeySet,\n    batchId: number\n  ): PersistencePromise<void> {\n    const collectionPaths = new Set<string>();\n\n    // Get the set of unique collection paths.\n    documentKeys.forEach(key =>\n      collectionPaths.add(encodeResourcePath(key.getCollectionPath()))\n    );\n\n    const promises: Array<PersistencePromise<void>> = [];\n    collectionPaths.forEach(collectionPath => {\n      const range = IDBKeyRange.bound(\n        [this.userId, collectionPath, batchId],\n        [this.userId, collectionPath, batchId + 1],\n        /*lowerOpen=*/ false,\n        /*upperOpen=*/ true\n      );\n      promises.push(\n        documentOverlayStore(transaction).deleteAll(\n          DbDocumentOverlayCollectionPathOverlayIndex,\n          range\n        )\n      );\n    });\n    return PersistencePromise.waitFor(promises);\n  }\n\n  getOverlaysForCollection(\n    transaction: PersistenceTransaction,\n    collection: ResourcePath,\n    sinceBatchId: number\n  ): PersistencePromise<OverlayMap> {\n    const result = newOverlayMap();\n    const collectionPath = encodeResourcePath(collection);\n    // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n    // is not inclusive.\n    const range = IDBKeyRange.bound(\n      [this.userId, collectionPath, sinceBatchId],\n      [this.userId, collectionPath, Number.POSITIVE_INFINITY],\n      /*lowerOpen=*/ true\n    );\n    return documentOverlayStore(transaction)\n      .loadAll(DbDocumentOverlayCollectionPathOverlayIndex, range)\n      .next(dbOverlays => {\n        for (const dbOverlay of dbOverlays) {\n          const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n          result.set(overlay.getKey(), overlay);\n        }\n        return result;\n      });\n  }\n\n  getOverlaysForCollectionGroup(\n    transaction: PersistenceTransaction,\n    collectionGroup: string,\n    sinceBatchId: number,\n    count: number\n  ): PersistencePromise<OverlayMap> {\n    const result = newOverlayMap();\n    let currentBatchId: number | undefined = undefined;\n    // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n    // is not inclusive.\n    const range = IDBKeyRange.bound(\n      [this.userId, collectionGroup, sinceBatchId],\n      [this.userId, collectionGroup, Number.POSITIVE_INFINITY],\n      /*lowerOpen=*/ true\n    );\n    return documentOverlayStore(transaction)\n      .iterate(\n        {\n          index: DbDocumentOverlayCollectionGroupOverlayIndex,\n          range\n        },\n        (_, dbOverlay, control) => {\n          // We do not want to return partial batch overlays, even if the size\n          // of the result set exceeds the given `count` argument. Therefore, we\n          // continue to aggregate results even after the result size exceeds\n          // `count` if there are more overlays from the `currentBatchId`.\n          const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n          if (\n            result.size() < count ||\n            overlay.largestBatchId === currentBatchId\n          ) {\n            result.set(overlay.getKey(), overlay);\n            currentBatchId = overlay.largestBatchId;\n          } else {\n            control.done();\n          }\n        }\n      )\n      .next(() => result);\n  }\n\n  private saveOverlay(\n    transaction: PersistenceTransaction,\n    overlay: Overlay\n  ): PersistencePromise<void> {\n    return documentOverlayStore(transaction).put(\n      toDbDocumentOverlay(this.serializer, this.userId, overlay)\n    );\n  }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */\nfunction documentOverlayStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbDocumentOverlayKey, DbDocumentOverlay> {\n  return getStore<DbDocumentOverlayKey, DbDocumentOverlay>(\n    txn,\n    DbDocumentOverlayStore\n  );\n}\n","/**\n * @license\n * Copyright 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<DbGlobalsKey, DbGlobals> {\n    return getStore<DbGlobalsKey, DbGlobals>(txn, DbGlobalsStore);\n  }\n\n  getSessionToken(txn: PersistenceTransaction): PersistencePromise<ByteString> {\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<void> {\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<FieldFilter>((lhs, rhs) =>\n    FieldPath.comparator(lhs.field, rhs.field)\n  );\n\n  // The list of equality filters of the target.\n  private readonly equalityFilters: FieldFilter[];\n  // The list of orderBys of the target.\n  private readonly orderBys: OrderBy[];\n\n  constructor(target: Target) {\n    this.collectionId =\n      target.collectionGroup != null\n        ? target.collectionGroup\n        : target.path.lastSegment();\n    this.orderBys = target.orderBy;\n    this.equalityFilters = [];\n    for (const filter of target.filters) {\n      const fieldFilter = filter as FieldFilter;\n      if (fieldFilter.isInequality()) {\n        this.inequalityFilters = this.inequalityFilters.add(fieldFilter);\n      } else {\n        this.equalityFilters.push(fieldFilter);\n      }\n    }\n  }\n\n  get hasMultipleInequality(): boolean {\n    return this.inequalityFilters.size > 1;\n  }\n\n  /**\n   * Returns whether the index can be used to serve the TargetIndexMatcher's\n   * target.\n   *\n   * An index is considered capable of serving the target when:\n   * - The target uses all index segments for its filters and orderBy clauses.\n   *   The target can have additional filter and orderBy clauses, but not\n   *   fewer.\n   * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n   *   have a corresponding `CONTAINS` segment.\n   * - All directional index segments can be mapped to the target as a series of\n   *   equality filters, a single inequality filter and a series of orderBy\n   *   clauses.\n   * - The segments that represent the equality filters may appear out of order.\n   * - The optional segment for the inequality filter must appear after all\n   *   equality segments.\n   * - The segments that represent that orderBy clause of the target must appear\n   *   in order after all equality and inequality segments. Single orderBy\n   *   clauses cannot be skipped, but a continuous orderBy suffix may be\n   *   omitted.\n   */\n  servedByIndex(index: FieldIndex): boolean {\n    hardAssert(\n      index.collectionGroup === this.collectionId,\n      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<string>();\n    let segmentIndex = 0;\n    let orderBysIndex = 0;\n\n    // Process all equalities first. Equalities can appear out of order.\n    for (; segmentIndex < segments.length; ++segmentIndex) {\n      // We attempt to greedily match all segments to equality filters. If a\n      // filter matches an index segment, we can mark the segment as used.\n      if (this.hasMatchingEqualityFilter(segments[segmentIndex])) {\n        equalitySegments = equalitySegments.add(\n          segments[segmentIndex].fieldPath.canonicalString()\n        );\n      } else {\n        // If we cannot find a matching filter, we need to verify whether the\n        // remaining segments map to the target's inequality and its orderBy\n        // clauses.\n        break;\n      }\n    }\n\n    // If we already have processed all segments, all segments are used to serve\n    // the equality filters and we do not need to map any segments to the\n    // target's inequality and orderBy clauses.\n    if (segmentIndex === segments.length) {\n      return true;\n    }\n\n    if (this.inequalityFilters.size > 0) {\n      // Only a single inequality is currently supported. Get the only entry in the set.\n      const inequalityFilter = this.inequalityFilters.getIterator().getNext();\n      // If there is an inequality filter and the field was not in one of the\n      // equality filters above, the next segment must match both the filter\n      // and the first orderBy clause.\n      if (!equalitySegments.has(inequalityFilter.field.canonicalString())) {\n        const segment = segments[segmentIndex];\n\n        if (\n          !this.matchesFilter(inequalityFilter, segment) ||\n          !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n        ) {\n          return false;\n        }\n      }\n\n      ++segmentIndex;\n    }\n\n    // All remaining segments need to represent the prefix of the target's\n    // orderBy.\n    for (; segmentIndex < segments.length; ++segmentIndex) {\n      const segment = segments[segmentIndex];\n      if (\n        orderBysIndex >= this.orderBys.length ||\n        !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n      ) {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  /**\n   * Returns a full matched field index for this target. Currently multiple\n   * inequality query is not supported so function returns null.\n   */\n  buildTargetIndex(): FieldIndex | null {\n    if (this.hasMultipleInequality) {\n      return null;\n    }\n\n    // We want to make sure only one segment created for one field. For example,\n    // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created\n    // once.\n    let uniqueFields = new SortedSet<FieldPath>(FieldPath.comparator);\n    const segments: IndexSegment[] = [];\n\n    for (const filter of this.equalityFilters) {\n      if (filter.field.isKeyField()) {\n        continue;\n      }\n      const isArrayOperator =\n        filter.op === Operator.ARRAY_CONTAINS ||\n        filter.op === Operator.ARRAY_CONTAINS_ANY;\n      if (isArrayOperator) {\n        segments.push(new IndexSegment(filter.field, IndexKind.CONTAINS));\n      } else {\n        if (uniqueFields.has(filter.field)) {\n          continue;\n        }\n        uniqueFields = uniqueFields.add(filter.field);\n        segments.push(new IndexSegment(filter.field, IndexKind.ASCENDING));\n      }\n    }\n\n    // Note: We do not explicitly check `this.inequalityFilter` but rather rely\n    // on the target defining an appropriate \"order by\" to ensure that the\n    // required index segment is added. The query engine would reject a query\n    // with an inequality filter that lacks the required order-by clause.\n    for (const orderBy of this.orderBys) {\n      // Stop adding more segments if we see a order-by on key. Typically this\n      // is the default implicit order-by which is covered in the index_entry\n      // table as a separate column. If it is not the default order-by, the\n      // generated index will be missing some segments optimized for order-bys,\n      // which is probably fine.\n      if (orderBy.field.isKeyField()) {\n        continue;\n      }\n\n      if (uniqueFields.has(orderBy.field)) {\n        continue;\n      }\n      uniqueFields = uniqueFields.add(orderBy.field);\n\n      segments.push(\n        new IndexSegment(\n          orderBy.field,\n          orderBy.dir === Direction.ASCENDING\n            ? IndexKind.ASCENDING\n            : IndexKind.DESCENDING\n        )\n      );\n    }\n\n    return new FieldIndex(\n      FieldIndex.UNKNOWN_ID,\n      this.collectionId,\n      segments,\n      IndexState.empty()\n    );\n  }\n\n  private hasMatchingEqualityFilter(segment: IndexSegment): boolean {\n    for (const filter of this.equalityFilters) {\n      if (this.matchesFilter(filter, segment)) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  private matchesFilter(\n    filter: FieldFilter | undefined,\n    segment: IndexSegment\n  ): boolean {\n    if (filter === undefined || !filter.field.isEqual(segment.fieldPath)) {\n      return false;\n    }\n    const isArrayOperator =\n      filter.op === Operator.ARRAY_CONTAINS ||\n      filter.op === Operator.ARRAY_CONTAINS_ANY;\n    return (segment.kind === IndexKind.CONTAINS) === isArrayOperator;\n  }\n\n  private matchesOrderBy(orderBy: OrderBy, segment: IndexSegment): boolean {\n    if (!orderBy.field.isEqual(segment.fieldPath)) {\n      return false;\n    }\n    return (\n      (segment.kind === IndexKind.ASCENDING &&\n        orderBy.dir === Direction.ASCENDING) ||\n      (segment.kind === IndexKind.DESCENDING &&\n        orderBy.dir === Direction.DESCENDING)\n    );\n  }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  CompositeFilter,\n  compositeFilterIsConjunction,\n  compositeFilterIsDisjunction,\n  compositeFilterIsFlat,\n  compositeFilterIsFlatConjunction,\n  compositeFilterWithAddedFilters,\n  CompositeOperator,\n  FieldFilter,\n  Filter,\n  InFilter,\n  Operator\n} from '../core/filter';\n\nimport { hardAssert } from './assert';\n\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */\nexport function computeInExpansion(filter: Filter): Filter {\n  hardAssert(\n    filter instanceof FieldFilter || filter instanceof CompositeFilter,\n    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 * <p>Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter - the composite filter to calculate DNF transform for.\n * @returns 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 * <p>In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n * <p>For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */\nfunction isDisjunctiveNormalForm(filter: Filter): boolean {\n  return (\n    isSingleFieldFilter(filter) ||\n    isFlatConjunction(filter) ||\n    isDisjunctionOfFieldFiltersAndFlatConjunctions(filter)\n  );\n}\n\n/**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\nfunction isDisjunctionOfFieldFiltersAndFlatConjunctions(\n  filter: Filter\n): boolean {\n  if (filter instanceof CompositeFilter) {\n    if (compositeFilterIsDisjunction(filter)) {\n      for (const subFilter of filter.getFilters()) {\n        if (!isSingleFieldFilter(subFilter) && !isFlatConjunction(subFilter)) {\n          return false;\n        }\n      }\n\n      return true;\n    }\n  }\n\n  return false;\n}\n\nexport function computeDistributedNormalForm(filter: Filter): Filter {\n  hardAssert(\n    filter instanceof FieldFilter || filter instanceof CompositeFilter,\n    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 * <ul>\n *   <li>A | (B | C) == (A | B) | C == (A | B | C)\n *   <li>A & (B & C) == (A & B) & C == (A & B & C)\n * </ul>\n *\n * <p>For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */\nexport function applyAssociation(filter: Filter): Filter {\n  hardAssert(\n    filter instanceof FieldFilter || filter instanceof CompositeFilter,\n    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<void> {\n    this.collectionParentIndex.add(collectionPath);\n    return PersistencePromise.resolve();\n  }\n\n  getCollectionParents(\n    transaction: PersistenceTransaction,\n    collectionId: string\n  ): PersistencePromise<ResourcePath[]> {\n    return PersistencePromise.resolve(\n      this.collectionParentIndex.getEntries(collectionId)\n    );\n  }\n\n  addFieldIndex(\n    transaction: PersistenceTransaction,\n    index: FieldIndex\n  ): PersistencePromise<void> {\n    // Field indices are not supported with memory persistence.\n    return PersistencePromise.resolve();\n  }\n\n  deleteFieldIndex(\n    transaction: PersistenceTransaction,\n    index: FieldIndex\n  ): PersistencePromise<void> {\n    // Field indices are not supported with memory persistence.\n    return PersistencePromise.resolve();\n  }\n\n  deleteAllFieldIndexes(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<void> {\n    // Field indices are not supported with memory persistence.\n    return PersistencePromise.resolve();\n  }\n\n  createTargetIndexes(\n    transaction: PersistenceTransaction,\n    target: Target\n  ): PersistencePromise<void> {\n    // Field indices are not supported with memory persistence.\n    return PersistencePromise.resolve();\n  }\n\n  getDocumentsMatchingTarget(\n    transaction: PersistenceTransaction,\n    target: Target\n  ): PersistencePromise<DocumentKey[] | null> {\n    // Field indices are not supported with memory persistence.\n    return PersistencePromise.resolve<DocumentKey[] | null>(null);\n  }\n\n  getIndexType(\n    transaction: PersistenceTransaction,\n    target: Target\n  ): PersistencePromise<IndexType> {\n    // Field indices are not supported with memory persistence.\n    return PersistencePromise.resolve<IndexType>(IndexType.NONE);\n  }\n\n  getFieldIndexes(\n    transaction: PersistenceTransaction,\n    collectionGroup?: string\n  ): PersistencePromise<FieldIndex[]> {\n    // Field indices are not supported with memory persistence.\n    return PersistencePromise.resolve<FieldIndex[]>([]);\n  }\n\n  getNextCollectionGroupToUpdate(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<string | null> {\n    // Field indices are not supported with memory persistence.\n    return PersistencePromise.resolve<string | null>(null);\n  }\n\n  getMinOffset(\n    transaction: PersistenceTransaction,\n    target: Target\n  ): PersistencePromise<IndexOffset> {\n    return PersistencePromise.resolve(IndexOffset.min());\n  }\n\n  getMinOffsetFromCollectionGroup(\n    transaction: PersistenceTransaction,\n    collectionGroup: string\n  ): PersistencePromise<IndexOffset> {\n    return PersistencePromise.resolve(IndexOffset.min());\n  }\n\n  updateCollectionGroup(\n    transaction: PersistenceTransaction,\n    collectionGroup: string,\n    offset: IndexOffset\n  ): PersistencePromise<void> {\n    // Field indices are not supported with memory persistence.\n    return PersistencePromise.resolve();\n  }\n\n  updateIndexEntries(\n    transaction: PersistenceTransaction,\n    documents: DocumentMap\n  ): PersistencePromise<void> {\n    // Field indices are not supported with memory persistence.\n    return PersistencePromise.resolve();\n  }\n}\n\n/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */\nexport class MemoryCollectionParentIndex {\n  private index = {} as {\n    [collectionId: string]: SortedSet<ResourcePath>;\n  };\n\n  // Returns false if the entry already existed.\n  add(collectionPath: ResourcePath): boolean {\n    debugAssert(collectionPath.length % 2 === 1, 'Expected a collection path.');\n    const collectionId = collectionPath.lastSegment();\n    const parentPath = collectionPath.popLast();\n    const existingParents =\n      this.index[collectionId] ||\n      new SortedSet<ResourcePath>(ResourcePath.comparator);\n    const added = !existingParents.has(parentPath);\n    this.index[collectionId] = existingParents.add(parentPath);\n    return added;\n  }\n\n  has(collectionPath: ResourcePath): boolean {\n    const collectionId = collectionPath.lastSegment();\n    const parentPath = collectionPath.popLast();\n    const existingParents = this.index[collectionId];\n    return existingParents && existingParents.has(parentPath);\n  }\n\n  getEntries(collectionId: string): ResourcePath[] {\n    const parentPaths =\n      this.index[collectionId] ||\n      new SortedSet<ResourcePath>(ResourcePath.comparator);\n    return parentPaths.toArray();\n  }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n  CompositeFilter,\n  CompositeOperator,\n  FieldFilter,\n  Filter,\n  Operator\n} from '../core/filter';\nimport {\n  canonifyTarget,\n  newTarget,\n  Target,\n  targetEquals,\n  targetGetArrayValues,\n  targetGetLowerBound,\n  targetGetNotInValues,\n  targetGetSegmentCount,\n  targetGetUpperBound,\n  targetHasLimit\n} from '../core/target';\nimport { FirestoreIndexValueWriter } from '../index/firestore_index_value_writer';\nimport { IndexByteEncoder } from '../index/index_byte_encoder';\nimport {\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<Target, Target[]>(\n    t => canonifyTarget(t),\n    (l, r) => targetEquals(l, r)\n  );\n\n  constructor(user: User, private readonly databaseId: DatabaseId) {\n    this.uid = user.uid || '';\n  }\n\n  /**\n   * Adds a new entry to the collection parent index.\n   *\n   * Repeated calls for the same collectionPath should be avoided within a\n   * transaction as IndexedDbIndexManager only caches writes once a transaction\n   * has been committed.\n   */\n  addToCollectionParentIndex(\n    transaction: PersistenceTransaction,\n    collectionPath: ResourcePath\n  ): PersistencePromise<void> {\n    debugAssert(collectionPath.length % 2 === 1, 'Expected a collection path.');\n    if (!this.collectionParentsCache.has(collectionPath)) {\n      const collectionId = collectionPath.lastSegment();\n      const parentPath = collectionPath.popLast();\n\n      transaction.addOnCommittedListener(() => {\n        // Add the collection to the in memory cache only if the transaction was\n        // successfully committed.\n        this.collectionParentsCache.add(collectionPath);\n      });\n\n      const collectionParent: DbCollectionParent = {\n        collectionId,\n        parent: encodeResourcePath(parentPath)\n      };\n      return collectionParentsStore(transaction).put(collectionParent);\n    }\n    return PersistencePromise.resolve();\n  }\n\n  getCollectionParents(\n    transaction: PersistenceTransaction,\n    collectionId: string\n  ): PersistencePromise<ResourcePath[]> {\n    const parentPaths = [] as ResourcePath[];\n    const range = IDBKeyRange.bound(\n      [collectionId, ''],\n      [immediateSuccessor(collectionId), ''],\n      /*lowerOpen=*/ false,\n      /*upperOpen=*/ true\n    );\n    return collectionParentsStore(transaction)\n      .loadAll(range)\n      .next(entries => {\n        for (const entry of entries) {\n          // This collectionId guard shouldn't be necessary (and isn't as long\n          // as we're running in a real browser), but there's a bug in\n          // indexeddbshim that breaks our range in our tests running in node:\n          // https://github.com/axemclion/IndexedDBShim/issues/334\n          if (entry.collectionId !== collectionId) {\n            break;\n          }\n          parentPaths.push(decodeResourcePath(entry.parent));\n        }\n        return parentPaths;\n      });\n  }\n\n  addFieldIndex(\n    transaction: PersistenceTransaction,\n    index: FieldIndex\n  ): PersistencePromise<void> {\n    // TODO(indexing): Verify that the auto-incrementing index ID works in\n    // Safari & Firefox.\n    const indexes = indexConfigurationStore(transaction);\n    const dbIndex = toDbIndexConfiguration(index);\n    delete dbIndex.indexId; // `indexId` is auto-populated by IndexedDb\n    const result = indexes.add(dbIndex);\n    if (index.indexState) {\n      const states = indexStateStore(transaction);\n      return result.next(indexId => {\n        states.put(\n          toDbIndexState(\n            indexId,\n            this.uid,\n            index.indexState.sequenceNumber,\n            index.indexState.offset\n          )\n        );\n      });\n    } else {\n      return result.next();\n    }\n  }\n\n  deleteFieldIndex(\n    transaction: PersistenceTransaction,\n    index: FieldIndex\n  ): PersistencePromise<void> {\n    const indexes = indexConfigurationStore(transaction);\n    const states = indexStateStore(transaction);\n    const entries = indexEntriesStore(transaction);\n    return indexes\n      .delete(index.indexId)\n      .next(() =>\n        states.delete(\n          IDBKeyRange.bound(\n            [index.indexId],\n            [index.indexId + 1],\n            /*lowerOpen=*/ false,\n            /*upperOpen=*/ true\n          )\n        )\n      )\n      .next(() =>\n        entries.delete(\n          IDBKeyRange.bound(\n            [index.indexId],\n            [index.indexId + 1],\n            /*lowerOpen=*/ false,\n            /*upperOpen=*/ true\n          )\n        )\n      );\n  }\n\n  deleteAllFieldIndexes(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<void> {\n    const indexes = indexConfigurationStore(transaction);\n    const entries = indexEntriesStore(transaction);\n    const states = indexStateStore(transaction);\n\n    return indexes\n      .deleteAll()\n      .next(() => entries.deleteAll())\n      .next(() => states.deleteAll());\n  }\n\n  createTargetIndexes(\n    transaction: PersistenceTransaction,\n    target: Target\n  ): PersistencePromise<void> {\n    return PersistencePromise.forEach(\n      this.getSubTargets(target),\n      (subTarget: Target) => {\n        return this.getIndexType(transaction, subTarget).next(type => {\n          if (type === IndexType.NONE || type === IndexType.PARTIAL) {\n            const targetIndexMatcher = new TargetIndexMatcher(subTarget);\n            const fieldIndex = targetIndexMatcher.buildTargetIndex();\n            if (fieldIndex != null) {\n              return this.addFieldIndex(transaction, fieldIndex);\n            }\n          }\n        });\n      }\n    );\n  }\n\n  getDocumentsMatchingTarget(\n    transaction: PersistenceTransaction,\n    target: Target\n  ): PersistencePromise<DocumentKey[] | null> {\n    const indexEntries = indexEntriesStore(transaction);\n\n    let canServeTarget = true;\n    const indexes = new Map<Target, FieldIndex | null>();\n\n    return PersistencePromise.forEach(\n      this.getSubTargets(target),\n      (subTarget: Target) => {\n        return this.getFieldIndex(transaction, subTarget).next(index => {\n          canServeTarget &&= !!index;\n          indexes.set(subTarget, index);\n        });\n      }\n    ).next(() => {\n      if (!canServeTarget) {\n        return PersistencePromise.resolve(null as DocumentKey[] | null);\n      } else {\n        let existingKeys = documentKeySet();\n        const result: DocumentKey[] = [];\n        return PersistencePromise.forEach(indexes, (index, subTarget) => {\n          logDebug(\n            LOG_TAG,\n            `Using index ${fieldIndexToString(\n              index!\n            )} to execute ${canonifyTarget(target)}`\n          );\n\n          const arrayValues = targetGetArrayValues(subTarget, index!);\n          const notInValues = targetGetNotInValues(subTarget, index!);\n          const lowerBound = targetGetLowerBound(subTarget, index!);\n          const upperBound = targetGetUpperBound(subTarget, index!);\n\n          const lowerBoundEncoded = this.encodeBound(\n            index!,\n            subTarget,\n            lowerBound\n          );\n          const upperBoundEncoded = this.encodeBound(\n            index!,\n            subTarget,\n            upperBound\n          );\n          const notInEncoded = this.encodeValues(\n            index!,\n            subTarget,\n            notInValues\n          );\n\n          const indexRanges = this.generateIndexRanges(\n            index!.indexId,\n            arrayValues,\n            lowerBoundEncoded,\n            lowerBound.inclusive,\n            upperBoundEncoded,\n            upperBound.inclusive,\n            notInEncoded\n          );\n          return PersistencePromise.forEach(\n            indexRanges,\n            (indexRange: IDBKeyRange) => {\n              return indexEntries\n                .loadFirst(indexRange, target.limit)\n                .next(entries => {\n                  entries.forEach(entry => {\n                    const documentKey = DocumentKey.fromSegments(\n                      entry.documentKey\n                    );\n                    if (!existingKeys.has(documentKey)) {\n                      existingKeys = existingKeys.add(documentKey);\n                      result.push(documentKey);\n                    }\n                  });\n                });\n            }\n          );\n        }).next(() => result as DocumentKey[] | null);\n      }\n    });\n  }\n\n  private getSubTargets(target: Target): Target[] {\n    let subTargets = this.targetToDnfSubTargets.get(target);\n    if (subTargets) {\n      return subTargets;\n    }\n\n    if (target.filters.length === 0) {\n      subTargets = [target];\n    } else {\n      // There is an implicit AND operation between all the filters stored in the target\n      const dnf: Filter[] = getDnfTerms(\n        CompositeFilter.create(target.filters, CompositeOperator.AND)\n      );\n\n      subTargets = dnf.map(term =>\n        newTarget(\n          target.path,\n          target.collectionGroup,\n          target.orderBy,\n          term.getFilters(),\n          target.limit,\n          target.startAt,\n          target.endAt\n        )\n      );\n    }\n\n    this.targetToDnfSubTargets.set(target, subTargets);\n    return subTargets;\n  }\n\n  /**\n   * Constructs a key range query on `DbIndexEntryStore` that unions all\n   * bounds.\n   */\n  private generateIndexRanges(\n    indexId: number,\n    arrayValues: ProtoValue[] | null,\n    lowerBounds: Uint8Array[],\n    lowerBoundInclusive: boolean,\n    upperBounds: Uint8Array[],\n    upperBoundInclusive: boolean,\n    notInValues: Uint8Array[]\n  ): IDBKeyRange[] {\n    // The number of total index scans we union together. This is similar to a\n    // distributed normal form, but adapted for array values. We create a single\n    // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter\n    // combined with the values from the query bounds.\n    const totalScans =\n      (arrayValues != null ? arrayValues.length : 1) *\n      Math.max(lowerBounds.length, upperBounds.length);\n    const scansPerArrayElement =\n      totalScans / (arrayValues != null ? arrayValues.length : 1);\n\n    const indexRanges: IDBKeyRange[] = [];\n    for (let i = 0; i < totalScans; ++i) {\n      const arrayValue = arrayValues\n        ? this.encodeSingleElement(arrayValues[i / scansPerArrayElement])\n        : EMPTY_VALUE;\n\n      const lowerBound = this.generateLowerBound(\n        indexId,\n        arrayValue,\n        lowerBounds[i % scansPerArrayElement],\n        lowerBoundInclusive\n      );\n      const upperBound = this.generateUpperBound(\n        indexId,\n        arrayValue,\n        upperBounds[i % scansPerArrayElement],\n        upperBoundInclusive\n      );\n\n      const notInBound = notInValues.map(notIn =>\n        this.generateLowerBound(\n          indexId,\n          arrayValue,\n          notIn,\n          /* inclusive= */ true\n        )\n      );\n\n      indexRanges.push(...this.createRange(lowerBound, upperBound, notInBound));\n    }\n\n    return indexRanges;\n  }\n\n  /** Generates the lower bound for `arrayValue` and `directionalValue`. */\n  private generateLowerBound(\n    indexId: number,\n    arrayValue: Uint8Array,\n    directionalValue: Uint8Array,\n    inclusive: boolean\n  ): IndexEntry {\n    const entry = new IndexEntry(\n      indexId,\n      DocumentKey.empty(),\n      arrayValue,\n      directionalValue\n    );\n    return inclusive ? entry : entry.successor();\n  }\n\n  /** Generates the upper bound for `arrayValue` and `directionalValue`. */\n  private generateUpperBound(\n    indexId: number,\n    arrayValue: Uint8Array,\n    directionalValue: Uint8Array,\n    inclusive: boolean\n  ): IndexEntry {\n    const entry = new IndexEntry(\n      indexId,\n      DocumentKey.empty(),\n      arrayValue,\n      directionalValue\n    );\n    return inclusive ? entry.successor() : entry;\n  }\n\n  private getFieldIndex(\n    transaction: PersistenceTransaction,\n    target: Target\n  ): PersistencePromise<FieldIndex | null> {\n    const targetIndexMatcher = new TargetIndexMatcher(target);\n    const collectionGroup =\n      target.collectionGroup != null\n        ? target.collectionGroup\n        : target.path.lastSegment();\n\n    return this.getFieldIndexes(transaction, collectionGroup).next(indexes => {\n      // Return the index with the most number of segments.\n      let index: FieldIndex | null = null;\n      for (const candidate of indexes) {\n        const matches = targetIndexMatcher.servedByIndex(candidate);\n        if (\n          matches &&\n          (!index || candidate.fields.length > index.fields.length)\n        ) {\n          index = candidate;\n        }\n      }\n      return index;\n    });\n  }\n\n  getIndexType(\n    transaction: PersistenceTransaction,\n    target: Target\n  ): PersistencePromise<IndexType> {\n    let indexType = IndexType.FULL;\n    const subTargets = this.getSubTargets(target);\n    return PersistencePromise.forEach(subTargets, (target: Target) => {\n      return this.getFieldIndex(transaction, target).next(index => {\n        if (!index) {\n          indexType = IndexType.NONE;\n        } else if (\n          indexType !== IndexType.NONE &&\n          index.fields.length < targetGetSegmentCount(target)\n        ) {\n          indexType = IndexType.PARTIAL;\n        }\n      });\n    }).next(() => {\n      // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider\n      // OR queries that have a `limit` to have a partial index. For such queries we perform sorting\n      // and apply the limit in memory as a post-processing step.\n      if (\n        targetHasLimit(target) &&\n        subTargets.length > 1 &&\n        indexType === IndexType.FULL\n      ) {\n        return IndexType.PARTIAL;\n      }\n\n      return indexType;\n    });\n  }\n\n  /**\n   * Returns the byte encoded form of the directional values in the field index.\n   * Returns `null` if the document does not have all fields specified in the\n   * index.\n   */\n  private encodeDirectionalElements(\n    fieldIndex: FieldIndex,\n    document: Document\n  ): Uint8Array | null {\n    const encoder = new IndexByteEncoder();\n    for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n      const field = document.data.field(segment.fieldPath);\n      if (field == null) {\n        return null;\n      }\n      const directionalEncoder = encoder.forKind(segment.kind);\n      FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n        field,\n        directionalEncoder\n      );\n    }\n    return encoder.encodedBytes();\n  }\n\n  /** Encodes a single value to the ascending index format. */\n  private encodeSingleElement(value: ProtoValue): Uint8Array {\n    const encoder = new IndexByteEncoder();\n    FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n      value,\n      encoder.forKind(IndexKind.ASCENDING)\n    );\n    return encoder.encodedBytes();\n  }\n\n  /**\n   * Returns an encoded form of the document key that sorts based on the key\n   * ordering of the field index.\n   */\n  private encodeDirectionalKey(\n    fieldIndex: FieldIndex,\n    documentKey: DocumentKey\n  ): Uint8Array {\n    const encoder = new IndexByteEncoder();\n    FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n      refValue(this.databaseId, documentKey),\n      encoder.forKind(fieldIndexGetKeyOrder(fieldIndex))\n    );\n    return encoder.encodedBytes();\n  }\n\n  /**\n   * Encodes the given field values according to the specification in `target`.\n   * For IN queries, a list of possible values is returned.\n   */\n  private encodeValues(\n    fieldIndex: FieldIndex,\n    target: Target,\n    values: ProtoValue[] | null\n  ): Uint8Array[] {\n    if (values === null) {\n      return [];\n    }\n\n    let encoders: IndexByteEncoder[] = [];\n    encoders.push(new IndexByteEncoder());\n\n    let valueIdx = 0;\n    for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n      const value = values[valueIdx++];\n      for (const encoder of encoders) {\n        if (this.isInFilter(target, segment.fieldPath) && isArray(value)) {\n          encoders = this.expandIndexValues(encoders, segment, value);\n        } else {\n          const directionalEncoder = encoder.forKind(segment.kind);\n          FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n            value,\n            directionalEncoder\n          );\n        }\n      }\n    }\n    return this.getEncodedBytes(encoders);\n  }\n\n  /**\n   * Encodes the given bounds according to the specification in `target`. For IN\n   * queries, a list of possible values is returned.\n   */\n  private encodeBound(\n    fieldIndex: FieldIndex,\n    target: Target,\n    bound: Bound\n  ): Uint8Array[] {\n    return this.encodeValues(fieldIndex, target, bound.position);\n  }\n\n  /** Returns the byte representation for the provided encoders. */\n  private getEncodedBytes(encoders: IndexByteEncoder[]): Uint8Array[] {\n    const result: Uint8Array[] = [];\n    for (let i = 0; i < encoders.length; ++i) {\n      result[i] = encoders[i].encodedBytes();\n    }\n    return result;\n  }\n\n  /**\n   * Creates a separate encoder for each element of an array.\n   *\n   * The method appends each value to all existing encoders (e.g. filter(\"a\",\n   * \"==\", \"a1\").filter(\"b\", \"in\", [\"b1\", \"b2\"]) becomes [\"a1,b1\", \"a1,b2\"]). A\n   * list of new encoders is returned.\n   */\n  private expandIndexValues(\n    encoders: IndexByteEncoder[],\n    segment: IndexSegment,\n    value: ProtoValue\n  ): IndexByteEncoder[] {\n    const prefixes = [...encoders];\n    const results: IndexByteEncoder[] = [];\n    for (const arrayElement of value.arrayValue!.values || []) {\n      for (const prefix of prefixes) {\n        const clonedEncoder = new IndexByteEncoder();\n        clonedEncoder.seed(prefix.encodedBytes());\n        FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n          arrayElement,\n          clonedEncoder.forKind(segment.kind)\n        );\n        results.push(clonedEncoder);\n      }\n    }\n    return results;\n  }\n\n  private isInFilter(target: Target, fieldPath: FieldPath): boolean {\n    return !!target.filters.find(\n      f =>\n        f instanceof FieldFilter &&\n        f.field.isEqual(fieldPath) &&\n        (f.op === Operator.IN || f.op === Operator.NOT_IN)\n    );\n  }\n\n  getFieldIndexes(\n    transaction: PersistenceTransaction,\n    collectionGroup?: string\n  ): PersistencePromise<FieldIndex[]> {\n    const indexes = indexConfigurationStore(transaction);\n    const states = indexStateStore(transaction);\n\n    return (\n      collectionGroup\n        ? indexes.loadAll(\n            DbIndexConfigurationCollectionGroupIndex,\n            IDBKeyRange.bound(collectionGroup, collectionGroup)\n          )\n        : indexes.loadAll()\n    ).next(indexConfigs => {\n      const result: FieldIndex[] = [];\n      return PersistencePromise.forEach(\n        indexConfigs,\n        (indexConfig: DbIndexConfiguration) => {\n          return states\n            .get([indexConfig.indexId!, this.uid])\n            .next(indexState => {\n              result.push(fromDbIndexConfiguration(indexConfig, indexState));\n            });\n        }\n      ).next(() => result);\n    });\n  }\n\n  getNextCollectionGroupToUpdate(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<string | null> {\n    return this.getFieldIndexes(transaction).next(indexes => {\n      if (indexes.length === 0) {\n        return null;\n      }\n      indexes.sort((l, r) => {\n        const cmp = l.indexState.sequenceNumber - r.indexState.sequenceNumber;\n        return cmp !== 0\n          ? cmp\n          : primitiveComparator(l.collectionGroup, r.collectionGroup);\n      });\n      return indexes[0].collectionGroup;\n    });\n  }\n\n  updateCollectionGroup(\n    transaction: PersistenceTransaction,\n    collectionGroup: string,\n    offset: IndexOffset\n  ): PersistencePromise<void> {\n    const indexes = indexConfigurationStore(transaction);\n    const states = indexStateStore(transaction);\n    return this.getNextSequenceNumber(transaction).next(nextSequenceNumber =>\n      indexes\n        .loadAll(\n          DbIndexConfigurationCollectionGroupIndex,\n          IDBKeyRange.bound(collectionGroup, collectionGroup)\n        )\n        .next(configs =>\n          PersistencePromise.forEach(configs, (config: DbIndexConfiguration) =>\n            states.put(\n              toDbIndexState(\n                config.indexId!,\n                this.uid,\n                nextSequenceNumber,\n                offset\n              )\n            )\n          )\n        )\n    );\n  }\n\n  updateIndexEntries(\n    transaction: PersistenceTransaction,\n    documents: DocumentMap\n  ): PersistencePromise<void> {\n    // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as\n    // it could be used across different IndexedDB transactions. As any cached\n    // data might be invalidated by other multi-tab clients, we can only trust\n    // data within a single IndexedDB transaction. We therefore add a cache\n    // here.\n    const memoizedIndexes = new Map<string, FieldIndex[]>();\n    return PersistencePromise.forEach(documents, (key, doc) => {\n      const memoizedCollectionIndexes = memoizedIndexes.get(\n        key.collectionGroup\n      );\n      const fieldIndexes = memoizedCollectionIndexes\n        ? PersistencePromise.resolve(memoizedCollectionIndexes)\n        : this.getFieldIndexes(transaction, key.collectionGroup);\n\n      return fieldIndexes.next(fieldIndexes => {\n        memoizedIndexes.set(key.collectionGroup, fieldIndexes);\n        return PersistencePromise.forEach(\n          fieldIndexes,\n          (fieldIndex: FieldIndex) => {\n            return this.getExistingIndexEntries(\n              transaction,\n              key,\n              fieldIndex\n            ).next(existingEntries => {\n              const newEntries = this.computeIndexEntries(doc, fieldIndex);\n              if (!existingEntries.isEqual(newEntries)) {\n                return this.updateEntries(\n                  transaction,\n                  doc,\n                  fieldIndex,\n                  existingEntries,\n                  newEntries\n                );\n              }\n              return PersistencePromise.resolve();\n            });\n          }\n        );\n      });\n    });\n  }\n\n  private addIndexEntry(\n    transaction: PersistenceTransaction,\n    document: Document,\n    fieldIndex: FieldIndex,\n    indexEntry: IndexEntry\n  ): PersistencePromise<void> {\n    const indexEntries = indexEntriesStore(transaction);\n    return indexEntries.put(\n      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<void> {\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<SortedSet<IndexEntry>> {\n    const indexEntries = indexEntriesStore(transaction);\n    let results = new SortedSet<IndexEntry>(indexEntryComparator);\n    return indexEntries\n      .iterate(\n        {\n          index: DbIndexEntryDocumentKeyIndex,\n          range: IDBKeyRange.only([\n            fieldIndex.indexId,\n            this.uid,\n            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<IndexEntry> {\n    let results = new SortedSet<IndexEntry>(indexEntryComparator);\n\n    const directionalValue = this.encodeDirectionalElements(\n      fieldIndex,\n      document\n    );\n    if (directionalValue == null) {\n      return results;\n    }\n\n    const arraySegment = fieldIndexGetArraySegment(fieldIndex);\n    if (arraySegment != null) {\n      const value = document.data.field(arraySegment.fieldPath);\n      if (isArray(value)) {\n        for (const arrayValue of value.arrayValue!.values || []) {\n          results = results.add(\n            new IndexEntry(\n              fieldIndex.indexId,\n              document.key,\n              this.encodeSingleElement(arrayValue),\n              directionalValue\n            )\n          );\n        }\n      }\n    } else {\n      results = results.add(\n        new IndexEntry(\n          fieldIndex.indexId,\n          document.key,\n          EMPTY_VALUE,\n          directionalValue\n        )\n      );\n    }\n\n    return results;\n  }\n\n  /**\n   * Updates the index entries for the provided document by deleting entries\n   * that are no longer referenced in `newEntries` and adding all newly added\n   * entries.\n   */\n  private updateEntries(\n    transaction: PersistenceTransaction,\n    document: Document,\n    fieldIndex: FieldIndex,\n    existingEntries: SortedSet<IndexEntry>,\n    newEntries: SortedSet<IndexEntry>\n  ): PersistencePromise<void> {\n    logDebug(LOG_TAG, \"Updating index entries for document '%s'\", document.key);\n\n    const promises: Array<PersistencePromise<void>> = [];\n    diffSortedSets(\n      existingEntries,\n      newEntries,\n      indexEntryComparator,\n      /* onAdd= */ entry => {\n        promises.push(\n          this.addIndexEntry(transaction, document, fieldIndex, entry)\n        );\n      },\n      /* onRemove= */ entry => {\n        promises.push(\n          this.deleteIndexEntry(transaction, document, fieldIndex, entry)\n        );\n      }\n    );\n\n    return PersistencePromise.waitFor(promises);\n  }\n\n  private getNextSequenceNumber(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<number> {\n    let nextSequenceNumber = 1;\n    const states = indexStateStore(transaction);\n    return states\n      .iterate(\n        {\n          index: DbIndexStateSequenceNumberIndex,\n          reverse: true,\n          range: IDBKeyRange.upperBound([this.uid, Number.MAX_SAFE_INTEGER])\n        },\n        (_, state, controller) => {\n          controller.done();\n          nextSequenceNumber = state.sequenceNumber + 1;\n        }\n      )\n      .next(() => nextSequenceNumber);\n  }\n\n  /**\n   * Returns a new set of IDB ranges that splits the existing range and excludes\n   * any values that match the `notInValue` from these ranges. As an example,\n   * '[foo > 2 && foo != 3]` becomes  `[foo > 2 && < 3, foo > 3]`.\n   */\n  private createRange(\n    lower: IndexEntry,\n    upper: IndexEntry,\n    notInValues: IndexEntry[]\n  ): IDBKeyRange[] {\n    // The notIn values need to be sorted and unique so that we can return a\n    // sorted set of non-overlapping ranges.\n    notInValues = notInValues\n      .sort((l, r) => indexEntryComparator(l, r))\n      .filter(\n        (el, i, values) => !i || indexEntryComparator(el, values[i - 1]) !== 0\n      );\n\n    const bounds: IndexEntry[] = [];\n    bounds.push(lower);\n    for (const notInValue of notInValues) {\n      const cmpToLower = indexEntryComparator(notInValue, lower);\n      const cmpToUpper = indexEntryComparator(notInValue, upper);\n\n      if (cmpToLower === 0) {\n        // `notInValue` is the lower bound. We therefore need to raise the bound\n        // to the next value.\n        bounds[0] = lower.successor();\n      } else if (cmpToLower > 0 && cmpToUpper < 0) {\n        // `notInValue` is in the middle of the range\n        bounds.push(notInValue);\n        bounds.push(notInValue.successor());\n      } else if (cmpToUpper > 0) {\n        // `notInValue` (and all following values) are out of the range\n        break;\n      }\n    }\n    bounds.push(upper);\n\n    const ranges: IDBKeyRange[] = [];\n    for (let i = 0; i < bounds.length; i += 2) {\n      // If we encounter two bounds that will create an unmatchable key range,\n      // then we return an empty set of key ranges.\n      if (this.isRangeMatchable(bounds[i], bounds[i + 1])) {\n        return [];\n      }\n\n      const lowerBound = 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<IndexOffset> {\n    return this.getFieldIndexes(transaction, collectionGroup).next(\n      getMinOffsetFromFieldIndexes\n    );\n  }\n\n  getMinOffset(\n    transaction: PersistenceTransaction,\n    target: Target\n  ): PersistencePromise<IndexOffset> {\n    return PersistencePromise.mapArray(\n      this.getSubTargets(target),\n      (subTarget: Target) =>\n        this.getFieldIndex(transaction, subTarget).next(index =>\n          index ? index : fail(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<DbCollectionParentKey, DbCollectionParent> {\n  return getStore<DbCollectionParentKey, DbCollectionParent>(\n    txn,\n    DbCollectionParentStore\n  );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index entry object store.\n */\nfunction indexEntriesStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbIndexEntryKey, DbIndexEntry> {\n  return getStore<DbIndexEntryKey, DbIndexEntry>(txn, DbIndexEntryStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index configuration object store.\n */\nfunction indexConfigurationStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbIndexConfigurationKey, DbIndexConfiguration> {\n  return getStore<DbIndexConfigurationKey, DbIndexConfiguration>(\n    txn,\n    DbIndexConfigurationStore\n  );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index state object store.\n */\nfunction indexStateStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbIndexStateKey, DbIndexState> {\n  return getStore<DbIndexStateKey, DbIndexState>(txn, DbIndexStateStore);\n}\n\nfunction getMinOffsetFromFieldIndexes(fieldIndexes: FieldIndex[]): IndexOffset {\n  hardAssert(\n    fieldIndexes.length !== 0,\n    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<DocumentKey[]> {\n  const mutationStore = txn.store<DbMutationBatchKey, DbMutationBatch>(\n    DbMutationBatchStore\n  );\n  const indexTxn = txn.store<DbDocumentMutationKey, DbDocumentMutation>(\n    DbDocumentMutationStore\n  );\n  const promises: Array<PersistencePromise<void>> = [];\n\n  const range = IDBKeyRange.only(batch.batchId);\n  let numDeleted = 0;\n  const removePromise = mutationStore.iterate(\n    { range },\n    (key, value, control) => {\n      numDeleted++;\n      return control.delete();\n    }\n  );\n  promises.push(\n    removePromise.next(() => {\n      hardAssert(\n        numDeleted === 1,\n        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<boolean> {\n    let empty = true;\n    const range = IDBKeyRange.bound(\n      [this.userId, Number.NEGATIVE_INFINITY],\n      [this.userId, Number.POSITIVE_INFINITY]\n    );\n    return mutationsStore(transaction)\n      .iterate(\n        { index: DbMutationBatchUserMutationsIndex, range },\n        (key, value, control) => {\n          empty = false;\n          control.done();\n        }\n      )\n      .next(() => empty);\n  }\n\n  addMutationBatch(\n    transaction: PersistenceTransaction,\n    localWriteTime: Timestamp,\n    baseMutations: Mutation[],\n    mutations: Mutation[]\n  ): PersistencePromise<MutationBatch> {\n    const documentStore = documentMutationsStore(transaction);\n    const mutationStore = mutationsStore(transaction);\n\n    // The IndexedDb implementation in Chrome (and Firefox) does not handle\n    // compound indices that include auto-generated keys correctly. To ensure\n    // that the index entry is added correctly in all browsers, we perform two\n    // writes: The first write is used to retrieve the next auto-generated Batch\n    // ID, and the second write populates the index and stores the actual\n    // mutation batch.\n    // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n\n    // We write an empty object to obtain key\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    return mutationStore.add({} as any).next(batchId => {\n      hardAssert(\n        typeof batchId === 'number',\n        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<PersistencePromise<void>> = [];\n      let collectionParents = new SortedSet<ResourcePath>((l, r) =>\n        primitiveComparator(l.canonicalString(), r.canonicalString())\n      );\n      for (const mutation of mutations) {\n        const indexKey = newDbDocumentMutationKey(\n          this.userId,\n          mutation.key.path,\n          batchId\n        );\n        collectionParents = collectionParents.add(mutation.key.path.popLast());\n        promises.push(mutationStore.put(dbBatch));\n        promises.push(\n          documentStore.put(indexKey, DbDocumentMutationPlaceholder)\n        );\n      }\n\n      collectionParents.forEach(parent => {\n        promises.push(\n          this.indexManager.addToCollectionParentIndex(transaction, parent)\n        );\n      });\n\n      transaction.addOnCommittedListener(() => {\n        this.documentKeysByBatchId[batchId] = batch.keys();\n      });\n\n      return PersistencePromise.waitFor(promises).next(() => batch);\n    });\n  }\n\n  lookupMutationBatch(\n    transaction: PersistenceTransaction,\n    batchId: BatchId\n  ): PersistencePromise<MutationBatch | null> {\n    return mutationsStore(transaction)\n      .get(batchId)\n      .next(dbBatch => {\n        if (dbBatch) {\n          hardAssert(\n            dbBatch.userId === this.userId,\n            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<DocumentKeySet | null> {\n    if (this.documentKeysByBatchId[batchId]) {\n      return PersistencePromise.resolve<DocumentKeySet | null>(\n        this.documentKeysByBatchId[batchId]\n      );\n    } else {\n      return this.lookupMutationBatch(transaction, batchId).next(batch => {\n        if (batch) {\n          const keys = batch.keys();\n          this.documentKeysByBatchId[batchId] = keys;\n          return keys;\n        } else {\n          return null;\n        }\n      });\n    }\n  }\n\n  getNextMutationBatchAfterBatchId(\n    transaction: PersistenceTransaction,\n    batchId: BatchId\n  ): PersistencePromise<MutationBatch | null> {\n    const nextBatchId = batchId + 1;\n\n    const range = IDBKeyRange.lowerBound([this.userId, nextBatchId]);\n    let foundBatch: MutationBatch | null = null;\n    return mutationsStore(transaction)\n      .iterate(\n        { index: DbMutationBatchUserMutationsIndex, range },\n        (key, dbBatch, control) => {\n          if (dbBatch.userId === this.userId) {\n            hardAssert(\n              dbBatch.batchId >= nextBatchId,\n              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<BatchId> {\n    const range = IDBKeyRange.upperBound([\n      this.userId,\n      Number.POSITIVE_INFINITY\n    ]);\n\n    let batchId = BATCHID_UNKNOWN;\n    return mutationsStore(transaction)\n      .iterate(\n        { index: DbMutationBatchUserMutationsIndex, range, reverse: true },\n        (key, dbBatch, control) => {\n          batchId = dbBatch.batchId;\n          control.done();\n        }\n      )\n      .next(() => batchId);\n  }\n\n  getAllMutationBatches(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<MutationBatch[]> {\n    const range = IDBKeyRange.bound(\n      [this.userId, BATCHID_UNKNOWN],\n      [this.userId, Number.POSITIVE_INFINITY]\n    );\n    return mutationsStore(transaction)\n      .loadAll(DbMutationBatchUserMutationsIndex, range)\n      .next(dbBatches =>\n        dbBatches.map(dbBatch => fromDbMutationBatch(this.serializer, dbBatch))\n      );\n  }\n\n  getAllMutationBatchesAffectingDocumentKey(\n    transaction: PersistenceTransaction,\n    documentKey: DocumentKey\n  ): PersistencePromise<MutationBatch[]> {\n    // Scan the document-mutation index starting with a prefix starting with\n    // the given documentKey.\n    const indexPrefix = newDbDocumentMutationPrefixForPath(\n      this.userId,\n      documentKey.path\n    );\n    const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n    const results: MutationBatch[] = [];\n    return documentMutationsStore(transaction)\n      .iterate({ range: indexStart }, (indexKey, _, control) => {\n        const [userID, encodedPath, batchId] = indexKey;\n\n        // Only consider rows matching exactly the specific key of\n        // interest. Note that because we order by path first, and we\n        // order terminators before path separators, we'll encounter all\n        // the index rows for documentKey contiguously. In particular, all\n        // the rows for documentKey will occur before any rows for\n        // documents nested in a subcollection beneath documentKey so we\n        // can stop as soon as we hit any such row.\n        const path = decodeResourcePath(encodedPath);\n        if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n          control.done();\n          return;\n        }\n        // Look up the mutation batch in the store.\n        return mutationsStore(transaction)\n          .get(batchId)\n          .next(mutation => {\n            if (!mutation) {\n              throw fail(\n                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<DocumentKey, unknown>\n  ): PersistencePromise<MutationBatch[]> {\n    let uniqueBatchIDs = new SortedSet<BatchId>(primitiveComparator);\n\n    const promises: Array<PersistencePromise<void>> = [];\n    documentKeys.forEach(documentKey => {\n      const indexStart = newDbDocumentMutationPrefixForPath(\n        this.userId,\n        documentKey.path\n      );\n      const range = IDBKeyRange.lowerBound(indexStart);\n\n      const promise = documentMutationsStore(transaction).iterate(\n        { range },\n        (indexKey, _, control) => {\n          const [userID, encodedPath, batchID] = indexKey;\n\n          // Only consider rows matching exactly the specific key of\n          // interest. Note that because we order by path first, and we\n          // order terminators before path separators, we'll encounter all\n          // the index rows for documentKey contiguously. In particular, all\n          // the rows for documentKey will occur before any rows for\n          // documents nested in a subcollection beneath documentKey so we\n          // can stop as soon as we hit any such row.\n          const path = decodeResourcePath(encodedPath);\n          if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n            control.done();\n            return;\n          }\n\n          uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n        }\n      );\n\n      promises.push(promise);\n    });\n\n    return PersistencePromise.waitFor(promises).next(() =>\n      this.lookupMutationBatches(transaction, uniqueBatchIDs)\n    );\n  }\n\n  getAllMutationBatchesAffectingQuery(\n    transaction: PersistenceTransaction,\n    query: Query\n  ): PersistencePromise<MutationBatch[]> {\n    debugAssert(\n      !isDocumentQuery(query),\n      \"Document queries shouldn't go down this path\"\n    );\n    debugAssert(\n      !isCollectionGroupQuery(query),\n      'CollectionGroup queries should be handled in LocalDocumentsView'\n    );\n\n    const queryPath = query.path;\n    const immediateChildrenLength = queryPath.length + 1;\n\n    // TODO(mcg): Actually implement a single-collection query\n    //\n    // This is actually executing an ancestor query, traversing the whole\n    // subtree below the collection which can be horrifically inefficient for\n    // some structures. The right way to solve this is to implement the full\n    // value index, but that's not in the cards in the near future so this is\n    // the best we can do for the moment.\n    //\n    // Since we don't yet index the actual properties in the mutations, our\n    // current approach is to just return all mutation batches that affect\n    // documents in the collection being queried.\n    const indexPrefix = newDbDocumentMutationPrefixForPath(\n      this.userId,\n      queryPath\n    );\n    const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n    // Collect up unique batchIDs encountered during a scan of the index. Use a\n    // SortedSet to accumulate batch IDs so they can be traversed in order in a\n    // scan of the main table.\n    let uniqueBatchIDs = new SortedSet<BatchId>(primitiveComparator);\n    return documentMutationsStore(transaction)\n      .iterate({ range: indexStart }, (indexKey, _, control) => {\n        const [userID, encodedPath, batchID] = indexKey;\n        const path = decodeResourcePath(encodedPath);\n        if (userID !== this.userId || !queryPath.isPrefixOf(path)) {\n          control.done();\n          return;\n        }\n        // Rows with document keys more than one segment longer than the\n        // query path can't be matches. For example, a query on 'rooms'\n        // can't match the document /rooms/abc/messages/xyx.\n        // TODO(mcg): we'll need a different scanner when we implement\n        // ancestor queries.\n        if (path.length !== immediateChildrenLength) {\n          return;\n        }\n        uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n      })\n      .next(() => this.lookupMutationBatches(transaction, uniqueBatchIDs));\n  }\n\n  private lookupMutationBatches(\n    transaction: PersistenceTransaction,\n    batchIDs: SortedSet<BatchId>\n  ): PersistencePromise<MutationBatch[]> {\n    const results: MutationBatch[] = [];\n    const promises: Array<PersistencePromise<void>> = [];\n    // TODO(rockwood): Implement this using iterate.\n    batchIDs.forEach(batchId => {\n      promises.push(\n        mutationsStore(transaction)\n          .get(batchId)\n          .next(mutation => {\n            if (mutation === null) {\n              throw fail(\n                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<void> {\n    return removeMutationBatch(\n      (transaction as IndexedDbTransaction).simpleDbTransaction,\n      this.userId,\n      batch\n    ).next(removedDocuments => {\n      transaction.addOnCommittedListener(() => {\n        this.removeCachedMutationKeys(batch.batchId);\n      });\n      return PersistencePromise.forEach(\n        removedDocuments,\n        (key: DocumentKey) => {\n          return this.referenceDelegate.markPotentiallyOrphaned(\n            transaction,\n            key\n          );\n        }\n      );\n    });\n  }\n\n  /**\n   * Clears the cached keys for a mutation batch. This method should be\n   * called by secondary clients after they process mutation updates.\n   *\n   * Note that this method does not have to be called from primary clients as\n   * the corresponding cache entries are cleared when an acknowledged or\n   * rejected batch is removed from the mutation queue.\n   */\n  // PORTING NOTE: Multi-tab only\n  removeCachedMutationKeys(batchId: BatchId): void {\n    delete this.documentKeysByBatchId[batchId];\n  }\n\n  performConsistencyCheck(\n    txn: PersistenceTransaction\n  ): PersistencePromise<void> {\n    return this.checkEmpty(txn).next(empty => {\n      if (!empty) {\n        return PersistencePromise.resolve();\n      }\n\n      // Verify that there are no entries in the documentMutations index if\n      // the queue is empty.\n      const startRange = IDBKeyRange.lowerBound(\n        newDbDocumentMutationPrefixForUser(this.userId)\n      );\n      const danglingMutationReferences: ResourcePath[] = [];\n      return documentMutationsStore(txn)\n        .iterate({ range: startRange }, (key, _, control) => {\n          const userID = key[0];\n          if (userID !== this.userId) {\n            control.done();\n            return;\n          } else {\n            const path = decodeResourcePath(key[1]);\n            danglingMutationReferences.push(path);\n          }\n        })\n        .next(() => {\n          hardAssert(\n            danglingMutationReferences.length === 0,\n            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<boolean> {\n    return mutationQueueContainsKey(txn, this.userId, key);\n  }\n\n  // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n  /** Returns the mutation queue's metadata from IndexedDb. */\n  private getMutationQueueMetadata(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<DbMutationQueue> {\n    return mutationQueuesStore(transaction)\n      .get(this.userId)\n      .next((metadata: DbMutationQueue | null) => {\n        return (\n          metadata || {\n            userId: this.userId,\n            lastAcknowledgedBatchId: BATCHID_UNKNOWN,\n            lastStreamToken: ''\n          }\n        );\n      });\n  }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n *         mutation for the given key.\n */\nfunction mutationQueueContainsKey(\n  txn: PersistenceTransaction,\n  userId: string,\n  key: DocumentKey\n): PersistencePromise<boolean> {\n  const indexKey = newDbDocumentMutationPrefixForPath(userId, key.path);\n  const encodedPath = indexKey[1];\n  const startRange = IDBKeyRange.lowerBound(indexKey);\n  let containsKey = false;\n  return documentMutationsStore(txn)\n    .iterate({ range: startRange, keysOnly: true }, (key, value, control) => {\n      const [userID, keyPath, /*batchID*/ _] = key;\n      if (userID === userId && keyPath === encodedPath) {\n        containsKey = true;\n      }\n      control.done();\n    })\n    .next(() => containsKey);\n}\n\n/** Returns true if any mutation queue contains the given document. */\nexport function mutationQueuesContainKey(\n  txn: PersistenceTransaction,\n  docKey: DocumentKey\n): PersistencePromise<boolean> {\n  let found = false;\n  return mutationQueuesStore(txn)\n    .iterateSerial(userId => {\n      return mutationQueueContainsKey(txn, userId, docKey).next(containsKey => {\n        if (containsKey) {\n          found = true;\n        }\n        return PersistencePromise.resolve(!containsKey);\n      });\n    })\n    .next(() => found);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbMutationBatchKey, DbMutationBatch> {\n  return getStore<DbMutationBatchKey, DbMutationBatch>(\n    txn,\n    DbMutationBatchStore\n  );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbDocumentMutationKey, DbDocumentMutation> {\n  return getStore<DbDocumentMutationKey, DbDocumentMutation>(\n    txn,\n    DbDocumentMutationStore\n  );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbMutationQueueKey, DbMutationQueue> {\n  return getStore<DbMutationQueueKey, DbMutationQueue>(\n    txn,\n    DbMutationQueueStore\n  );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RemoteTargetId, 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<T extends TargetId | RemoteTargetId = TargetId> {\n  constructor(private lastId: number) {}\n\n  next(): T {\n    this.lastId += OFFSET;\n    return this.lastId as T;\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 {\n  canonifyTargetOrPipeline,\n  TargetOrPipeline,\n  targetOrPipelineEqual\n} from '../core/pipeline-util';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { hardAssert } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\n\nimport {\n  decodeResourcePath,\n  encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { DbTarget, DbTargetDocument, DbTargetGlobal } from './indexeddb_schema';\nimport {\n  DbTargetDocumentDocumentTargetsIndex,\n  DbTargetDocumentKey,\n  DbTargetDocumentStore,\n  DbTargetGlobalKey,\n  DbTargetGlobalStore,\n  DbTargetKey,\n  DbTargetQueryTargetsIndexName,\n  DbTargetStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport { fromDbTarget, LocalSerializer, toDbTarget } from './local_serializer';\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\n\nexport class IndexedDbTargetCache implements TargetCache {\n  constructor(\n    private readonly referenceDelegate: IndexedDbLruDelegate,\n    private serializer: LocalSerializer\n  ) {}\n\n  // PORTING NOTE: We don't cache global metadata for the target cache, since\n  // some of it (in particular `highestTargetId`) can be modified by secondary\n  // tabs. We could perhaps be more granular (and e.g. still cache\n  // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n  // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n  // out to have a meaningful performance impact.\n\n  allocateTargetId(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<TargetId> {\n    return this.retrieveMetadata(transaction).next(metadata => {\n      const targetIdGenerator = new TargetIdGenerator(metadata.highestTargetId);\n      metadata.highestTargetId = targetIdGenerator.next();\n      return this.saveMetadata(transaction, metadata).next(\n        () => metadata.highestTargetId\n      );\n    });\n  }\n\n  getLastRemoteSnapshotVersion(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<SnapshotVersion> {\n    return this.retrieveMetadata(transaction).next(metadata => {\n      return SnapshotVersion.fromTimestamp(\n        new Timestamp(\n          metadata.lastRemoteSnapshotVersion.seconds,\n          metadata.lastRemoteSnapshotVersion.nanoseconds\n        )\n      );\n    });\n  }\n\n  getHighestSequenceNumber(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<ListenSequenceNumber> {\n    return this.retrieveMetadata(transaction).next(\n      targetGlobal => targetGlobal.highestListenSequenceNumber\n    );\n  }\n\n  setTargetsMetadata(\n    transaction: PersistenceTransaction,\n    highestListenSequenceNumber: number,\n    lastRemoteSnapshotVersion?: SnapshotVersion\n  ): PersistencePromise<void> {\n    return this.retrieveMetadata(transaction).next(metadata => {\n      metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n      if (lastRemoteSnapshotVersion) {\n        metadata.lastRemoteSnapshotVersion =\n          lastRemoteSnapshotVersion.toTimestamp();\n      }\n      if (highestListenSequenceNumber > metadata.highestListenSequenceNumber) {\n        metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n      }\n      return this.saveMetadata(transaction, metadata);\n    });\n  }\n\n  addTargetData(\n    transaction: PersistenceTransaction,\n    targetData: TargetData\n  ): PersistencePromise<void> {\n    return this.saveTargetData(transaction, targetData).next(() => {\n      return this.retrieveMetadata(transaction).next(metadata => {\n        metadata.targetCount += 1;\n        this.updateMetadataFromTargetData(targetData, metadata);\n        return this.saveMetadata(transaction, metadata);\n      });\n    });\n  }\n\n  updateTargetData(\n    transaction: PersistenceTransaction,\n    targetData: TargetData\n  ): PersistencePromise<void> {\n    return this.saveTargetData(transaction, targetData);\n  }\n\n  removeTargetData(\n    transaction: PersistenceTransaction,\n    targetData: TargetData\n  ): PersistencePromise<void> {\n    return this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n      .next(() => targetsStore(transaction).delete(targetData.targetId))\n      .next(() => this.retrieveMetadata(transaction))\n      .next(metadata => {\n        hardAssert(\n          metadata.targetCount > 0,\n          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<number> {\n    let count = 0;\n    const promises: Array<PersistencePromise<void>> = [];\n    return targetsStore(txn)\n      .iterate((key, value) => {\n        const targetData = fromDbTarget(this.serializer, value);\n        if (\n          targetData.sequenceNumber <= upperBound &&\n          activeTargetIds.get(targetData.targetId) === null\n        ) {\n          count++;\n          promises.push(this.removeTargetData(txn, targetData));\n        }\n      })\n      .next(() => PersistencePromise.waitFor(promises))\n      .next(() => count);\n  }\n\n  /**\n   * Call provided function with each `TargetData` that we have cached.\n   */\n  forEachTarget(\n    txn: PersistenceTransaction,\n    f: (q: TargetData) => void\n  ): PersistencePromise<void> {\n    return targetsStore(txn).iterate((key, value) => {\n      const targetData = fromDbTarget(this.serializer, value);\n      f(targetData);\n    });\n  }\n\n  private retrieveMetadata(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<DbTargetGlobal> {\n    return globalTargetStore(transaction)\n      .get(DbTargetGlobalKey)\n      .next(metadata => {\n        hardAssert(metadata !== null, 0x0b48, 'Missing metadata row.');\n        return metadata;\n      });\n  }\n\n  private saveMetadata(\n    transaction: PersistenceTransaction,\n    metadata: DbTargetGlobal\n  ): PersistencePromise<void> {\n    return globalTargetStore(transaction).put(DbTargetGlobalKey, metadata);\n  }\n\n  private saveTargetData(\n    transaction: PersistenceTransaction,\n    targetData: TargetData\n  ): PersistencePromise<void> {\n    return targetsStore(transaction).put(\n      toDbTarget(this.serializer, targetData)\n    );\n  }\n\n  /**\n   * In-place updates the provided metadata to account for values in the given\n   * TargetData. Saving is done separately. Returns true if there were any\n   * changes to the metadata.\n   */\n  private updateMetadataFromTargetData(\n    targetData: TargetData,\n    metadata: DbTargetGlobal\n  ): boolean {\n    let updated = false;\n    if (targetData.targetId > metadata.highestTargetId) {\n      metadata.highestTargetId = targetData.targetId;\n      updated = true;\n    }\n\n    if (targetData.sequenceNumber > metadata.highestListenSequenceNumber) {\n      metadata.highestListenSequenceNumber = targetData.sequenceNumber;\n      updated = true;\n    }\n    return updated;\n  }\n\n  getTargetCount(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<number> {\n    return this.retrieveMetadata(transaction).next(\n      metadata => metadata.targetCount\n    );\n  }\n\n  getTargetData(\n    transaction: PersistenceTransaction,\n    target: TargetOrPipeline\n  ): PersistencePromise<TargetData | null> {\n    // Iterating by the canonicalId may yield more than one result because\n    // canonicalId values are not required to be unique per target. This query\n    // depends on the queryTargets index to be efficient.\n    const canonicalId = canonifyTargetOrPipeline(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(this.serializer, value);\n          // After finding a potential match, check that the target is\n          // actually equal to the requested target.\n          if (targetOrPipelineEqual(target, found.target)) {\n            result = found;\n            control.done();\n          }\n        }\n      )\n      .next(() => result);\n  }\n\n  addMatchingKeys(\n    txn: PersistenceTransaction,\n    keys: DocumentKeySet,\n    targetId: TargetId\n  ): PersistencePromise<void> {\n    // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n    // IndexedDb.\n    const promises: Array<PersistencePromise<void>> = [];\n    const store = documentTargetStore(txn);\n    keys.forEach(key => {\n      const path = encodeResourcePath(key.path);\n      promises.push(store.put({ targetId, path }));\n      promises.push(this.referenceDelegate.addReference(txn, targetId, key));\n    });\n    return PersistencePromise.waitFor(promises);\n  }\n\n  removeMatchingKeys(\n    txn: PersistenceTransaction,\n    keys: DocumentKeySet,\n    targetId: TargetId\n  ): PersistencePromise<void> {\n    // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n    // IndexedDb.\n    const store = documentTargetStore(txn);\n    return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n      const path = encodeResourcePath(key.path);\n      return PersistencePromise.waitFor([\n        store.delete([targetId, path]),\n        this.referenceDelegate.removeReference(txn, targetId, key)\n      ]);\n    });\n  }\n\n  removeMatchingKeysForTargetId(\n    txn: PersistenceTransaction,\n    targetId: TargetId\n  ): PersistencePromise<void> {\n    const store = documentTargetStore(txn);\n    const range = IDBKeyRange.bound(\n      [targetId],\n      [targetId + 1],\n      /*lowerOpen=*/ false,\n      /*upperOpen=*/ true\n    );\n    return store.delete(range);\n  }\n\n  getMatchingKeysForTargetId(\n    txn: PersistenceTransaction,\n    targetId: TargetId\n  ): PersistencePromise<DocumentKeySet> {\n    const range = IDBKeyRange.bound(\n      [targetId],\n      [targetId + 1],\n      /*lowerOpen=*/ false,\n      /*upperOpen=*/ true\n    );\n    const store = documentTargetStore(txn);\n    let result = documentKeySet();\n\n    return store\n      .iterate({ range, keysOnly: true }, (key, _, control) => {\n        const path = decodeResourcePath(key[1]);\n        const docKey = new DocumentKey(path);\n        result = result.add(docKey);\n      })\n      .next(() => result);\n  }\n\n  containsKey(\n    txn: PersistenceTransaction,\n    key: DocumentKey\n  ): PersistencePromise<boolean> {\n    const path = encodeResourcePath(key.path);\n    const range = IDBKeyRange.bound(\n      [path],\n      [immediateSuccessor(path)],\n      /*lowerOpen=*/ false,\n      /*upperOpen=*/ true\n    );\n    let count = 0;\n    return documentTargetStore(txn!)\n      .iterate(\n        {\n          index: DbTargetDocumentDocumentTargetsIndex,\n          keysOnly: true,\n          range\n        },\n        ([targetId, path], _, control) => {\n          // Having a sentinel row for a document does not count as containing that document;\n          // For the target cache, containing the document means the document is part of some\n          // target.\n          if (targetId !== 0) {\n            count++;\n            control.done();\n          }\n        }\n      )\n      .next(() => count > 0);\n  }\n\n  /**\n   * Looks up a TargetData entry by target ID.\n   *\n   * @param targetId - The target ID of the TargetData entry to look up.\n   * @returns The cached TargetData entry, or null if the cache has no entry for\n   * the target.\n   */\n  // PORTING NOTE: Multi-tab only.\n  getTargetDataForTarget(\n    transaction: PersistenceTransaction,\n    targetId: TargetId\n  ): PersistencePromise<TargetData | null> {\n    return targetsStore(transaction)\n      .get(targetId)\n      .next(found => {\n        if (found) {\n          return fromDbTarget(this.serializer, found);\n        } else {\n          return null;\n        }\n      });\n  }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbTargetKey, DbTarget> {\n  return getStore<DbTargetKey, DbTarget>(txn, DbTargetStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbTargetGlobalKey, DbTargetGlobal> {\n  return getStore<DbTargetGlobalKey, DbTargetGlobal>(txn, DbTargetGlobalStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nexport function documentTargetStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbTargetDocumentKey, DbTargetDocument> {\n  return getStore<DbTargetDocumentKey, DbTargetDocument>(\n    txn,\n    DbTargetDocumentStore\n  );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKey } from '../model/document_key';\n\nimport {\n  decodeResourcePath,\n  EncodedResourcePath,\n  encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { mutationQueuesContainKey } from './indexeddb_mutation_queue';\nimport { DbTargetDocument } from './indexeddb_schema';\nimport { DbTargetDocumentDocumentTargetsIndex } from './indexeddb_sentinels';\nimport {\n  documentTargetStore,\n  IndexedDbTargetCache\n} from './indexeddb_target_cache';\nimport {\n  ActiveTargets,\n  LruGarbageCollector,\n  LruParams\n} from './lru_garbage_collector';\nimport { newLruGarbageCollector } from './lru_garbage_collector_impl';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/** Provides LRU functionality for IndexedDB persistence. */\nexport class IndexedDbLruDelegateImpl implements IndexedDbLruDelegate {\n  readonly garbageCollector: LruGarbageCollector;\n\n  constructor(private readonly db: Persistence, params: LruParams) {\n    this.garbageCollector = newLruGarbageCollector(this, params);\n  }\n\n  getSequenceNumberCount(\n    txn: PersistenceTransaction\n  ): PersistencePromise<number> {\n    const docCountPromise = this.orphanedDocumentCount(txn);\n    const targetCountPromise = this.db.getTargetCache().getTargetCount(txn);\n    return targetCountPromise.next(targetCount =>\n      docCountPromise.next(docCount => targetCount + docCount)\n    );\n  }\n\n  private orphanedDocumentCount(\n    txn: PersistenceTransaction\n  ): PersistencePromise<number> {\n    let orphanedCount = 0;\n    return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n      orphanedCount++;\n    }).next(() => orphanedCount);\n  }\n\n  forEachTarget(\n    txn: PersistenceTransaction,\n    f: (q: TargetData) => void\n  ): PersistencePromise<void> {\n    return this.db.getTargetCache().forEachTarget(txn, f);\n  }\n\n  forEachOrphanedDocumentSequenceNumber(\n    txn: PersistenceTransaction,\n    f: (sequenceNumber: ListenSequenceNumber) => void\n  ): PersistencePromise<void> {\n    return this.forEachOrphanedDocument(txn, (docKey, sequenceNumber) =>\n      f(sequenceNumber)\n    );\n  }\n\n  addReference(\n    txn: PersistenceTransaction,\n    targetId: TargetId,\n    key: DocumentKey\n  ): PersistencePromise<void> {\n    return writeSentinelKey(txn, key);\n  }\n\n  removeReference(\n    txn: PersistenceTransaction,\n    targetId: TargetId,\n    key: DocumentKey\n  ): PersistencePromise<void> {\n    return writeSentinelKey(txn, key);\n  }\n\n  removeTargets(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber,\n    activeTargetIds: ActiveTargets\n  ): PersistencePromise<number> {\n    return (this.db.getTargetCache() as IndexedDbTargetCache).removeTargets(\n      txn,\n      upperBound,\n      activeTargetIds\n    );\n  }\n\n  markPotentiallyOrphaned(\n    txn: PersistenceTransaction,\n    key: DocumentKey\n  ): PersistencePromise<void> {\n    return writeSentinelKey(txn, key);\n  }\n\n  /**\n   * Returns true if anything would prevent this document from being garbage\n   * collected, given that the document in question is not present in any\n   * targets and has a sequence number less than or equal to the upper bound for\n   * the collection run.\n   */\n  private isPinned(\n    txn: PersistenceTransaction,\n    docKey: DocumentKey\n  ): PersistencePromise<boolean> {\n    return mutationQueuesContainKey(txn, docKey);\n  }\n\n  removeOrphanedDocuments(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber\n  ): PersistencePromise<number> {\n    const documentCache = this.db.getRemoteDocumentCache();\n    const changeBuffer = documentCache.newChangeBuffer();\n\n    const promises: Array<PersistencePromise<void>> = [];\n    let documentCount = 0;\n\n    const iteration = this.forEachOrphanedDocument(\n      txn,\n      (docKey, sequenceNumber) => {\n        if (sequenceNumber <= upperBound) {\n          const p = this.isPinned(txn, docKey).next(isPinned => {\n            if (!isPinned) {\n              documentCount++;\n              // Our size accounting requires us to read all documents before\n              // removing them.\n              return changeBuffer.getEntry(txn, docKey).next(() => {\n                changeBuffer.removeEntry(docKey, SnapshotVersion.min());\n                return documentTargetStore(txn).delete(sentinelKey(docKey));\n              });\n            }\n          });\n          promises.push(p);\n        }\n      }\n    );\n\n    return iteration\n      .next(() => PersistencePromise.waitFor(promises))\n      .next(() => changeBuffer.apply(txn))\n      .next(() => documentCount);\n  }\n\n  removeTarget(\n    txn: PersistenceTransaction,\n    targetData: TargetData\n  ): PersistencePromise<void> {\n    const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n    return this.db.getTargetCache().updateTargetData(txn, updated);\n  }\n\n  updateLimboDocument(\n    txn: PersistenceTransaction,\n    key: DocumentKey\n  ): PersistencePromise<void> {\n    return writeSentinelKey(txn, key);\n  }\n\n  /**\n   * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n   * means not a part of any target, so the only entry in the target-document index for\n   * that document will be the sentinel row (targetId 0), which will also have the sequence\n   * number for the last time the document was accessed.\n   */\n  private forEachOrphanedDocument(\n    txn: PersistenceTransaction,\n    f: (docKey: DocumentKey, sequenceNumber: ListenSequenceNumber) => void\n  ): PersistencePromise<void> {\n    const store = documentTargetStore(txn);\n    let nextToReport: ListenSequenceNumber = ListenSequence.INVALID;\n    let nextPath: EncodedResourcePath;\n    return store\n      .iterate(\n        {\n          index: DbTargetDocumentDocumentTargetsIndex\n        },\n        ([targetId, docKey], { path, sequenceNumber }) => {\n          if (targetId === 0) {\n            // if nextToReport is valid, report it, this is a new key so the\n            // last one must not be a member of any targets.\n            if (nextToReport !== ListenSequence.INVALID) {\n              f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n            }\n            // set nextToReport to be this sequence number. It's the next one we\n            // might report, if we don't find any targets for this document.\n            // Note that the sequence number must be defined when the targetId\n            // is 0.\n            nextToReport = sequenceNumber!;\n            nextPath = path;\n          } else {\n            // set nextToReport to be invalid, we know we don't need to report\n            // this one since we found a target for it.\n            nextToReport = ListenSequence.INVALID;\n          }\n        }\n      )\n      .next(() => {\n        // Since we report sequence numbers after getting to the next key, we\n        // need to check if the last key we iterated over was an orphaned\n        // document and report it.\n        if (nextToReport !== ListenSequence.INVALID) {\n          f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n        }\n      });\n  }\n\n  getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n    return this.db.getRemoteDocumentCache().getSize(txn);\n  }\n}\n\nfunction sentinelKey(key: DocumentKey): [TargetId, EncodedResourcePath] {\n  return [0, encodeResourcePath(key.path)];\n}\n\n/**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */\nfunction sentinelRow(\n  key: DocumentKey,\n  sequenceNumber: ListenSequenceNumber\n): DbTargetDocument {\n  return { targetId: 0, path: encodeResourcePath(key.path), sequenceNumber };\n}\n\nfunction writeSentinelKey(\n  txn: PersistenceTransaction,\n  key: DocumentKey\n): PersistencePromise<void> {\n  return documentTargetStore(txn).put(\n    sentinelRow(key, txn.currentSequenceNumber)\n  );\n}\n","// Copyright 2024 Google LLC* @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 {\n  BooleanFunctionExpression,\n  Field,\n  Ordering\n} from '../lite-api/expressions';\nimport {\n  CollectionGroupSource,\n  CollectionSource,\n  DatabaseSource,\n  DocumentsSource,\n  Limit,\n  Offset,\n  Sort,\n  Stage,\n  Where\n} from '../lite-api/stage';\nimport { Document, MutableDocument } from '../model/document';\nimport { DOCUMENT_KEY_NAME } from '../model/path';\nimport {\n  MIN_VALUE,\n  TRUE_VALUE,\n  valueCompare,\n  valueEquals\n} from '../model/values';\n\nimport {\n  EvaluationContext,\n  toEvaluable,\n  valueOrUndefined\n} from './expressions';\nimport { CorePipeline } from './pipeline';\nimport { isPipeline, QueryOrPipeline } from './pipeline-util';\nimport { queryMatches } from './query';\nexport type PipelineInputOutput = MutableDocument;\n\nexport function runPipeline(\n  pipeline: CorePipeline,\n  input: PipelineInputOutput[]\n): PipelineInputOutput[] {\n  let current = input;\n  for (const stage of pipeline.stages) {\n    current = evaluate(\n      {\n        serializer: pipeline.serializer,\n        serverTimestampBehavior: pipeline.listenOptions?.serverTimestampBehavior\n      },\n      stage,\n      current\n    );\n  }\n\n  return current;\n}\n\nexport function pipelineMatches(\n  pipeline: CorePipeline,\n  data: PipelineInputOutput\n): boolean {\n  // TODO(pipeline): this is not true for aggregations, and we need to examine if there are other\n  // stages that will not work this way.\n  return runPipeline(pipeline, [data]).length > 0;\n}\n\nexport function queryOrPipelineMatches(\n  query: QueryOrPipeline,\n  data: PipelineInputOutput\n): boolean {\n  return isPipeline(query)\n    ? pipelineMatches(query, data)\n    : queryMatches(query, data);\n}\n\nexport function pipelineMatchesAllDocuments(pipeline: CorePipeline): boolean {\n  for (const stage of pipeline.stages) {\n    if (stage instanceof Limit || stage instanceof Offset) {\n      return false;\n    }\n    // Check if it's the special 'exists(__name__)' case\n    if (stage instanceof Where) {\n      if (\n        stage.condition instanceof BooleanFunctionExpression &&\n        stage.condition._expr.name === 'exists' &&\n        stage.condition._expr.params[0] instanceof Field &&\n        stage.condition._expr.params[0].fieldName === DOCUMENT_KEY_NAME\n      ) {\n        continue;\n      }\n      return false;\n    }\n  }\n\n  return true;\n}\n\nfunction evaluate(\n  context: EvaluationContext,\n  stage: Stage,\n  input: PipelineInputOutput[]\n): PipelineInputOutput[] {\n  if (stage instanceof CollectionSource) {\n    return evaluateCollection(context, stage, input);\n  } else if (stage instanceof Where) {\n    return evaluateWhere(context, stage, input);\n  } /*else if (stage instanceof AddFields) {\n    return evaluateAddFields(context, stage, input);\n  } else if (stage instanceof Aggregate) {\n    return evaluateAggregate(context, stage, input);\n  } else if (stage instanceof Distinct) {\n    return evaluateDistinct(context, stage, input);\n  } */ else if (stage instanceof CollectionGroupSource) {\n    return evaluateCollectionGroup(context, stage, input);\n  } else if (stage instanceof DatabaseSource) {\n    return evaluateDatabase(context, stage, input);\n  } else if (stage instanceof DocumentsSource) {\n    return evaluateDocuments(context, stage, input);\n  } /* else if (stage instanceof FindNearest) {\n    return evaluateFindNearest(context, stage, input);\n  } */ else if (stage instanceof Limit) {\n    return evaluateLimit(context, stage, input);\n  } /* else if (stage instanceof Offset) {\n    return evaluateOffset(context, stage, input);\n  } else if (stage instanceof Select) {\n    return evaluateSelect(context, stage, input);\n  }*/ else if (stage instanceof Sort) {\n    return evaluateSort(context, stage, input);\n  }\n\n  throw new Error(`Unknown stage: ${stage._name}`);\n}\n\nfunction evaluateWhere(\n  context: EvaluationContext,\n  where: Where,\n  input: PipelineInputOutput[]\n): PipelineInputOutput[] {\n  return input.filter(value => {\n    const result = valueOrUndefined(\n      toEvaluable(where.condition).evaluate(context, value)\n    );\n    return result === undefined ? false : valueEquals(result, TRUE_VALUE);\n  });\n}\n\nfunction evaluateLimit(\n  context: EvaluationContext,\n  stage: Limit,\n  input: PipelineInputOutput[]\n): PipelineInputOutput[] {\n  return input.slice(0, stage.limit);\n}\n\n// function evaluateOffset(\n//   context: EvaluationContext,\n//   stage: Offset,\n//   input: PipelineInputOutput[]\n// ): PipelineInputOutput[] {\n//   return input.slice((stage as any).offset);\n// }\n\nfunction evaluateSort(\n  context: EvaluationContext,\n  stage: Sort,\n  input: PipelineInputOutput[]\n): PipelineInputOutput[] {\n  const evaluableOrderings = stage.orderings.map(ordering => ({\n    evaluable: toEvaluable(ordering.expr),\n    direction: ordering.direction\n  }));\n\n  return [...input].sort((left, right): number => {\n    // Evaluate expressions in stage.orderings against left and right, and use them to compare\n    // the documents\n    for (const { evaluable, direction } of evaluableOrderings) {\n      const leftValue = valueOrUndefined(evaluable.evaluate(context, left));\n      const rightValue = valueOrUndefined(evaluable.evaluate(context, right));\n\n      const comparison = valueCompare(\n        leftValue ?? MIN_VALUE,\n        rightValue ?? MIN_VALUE\n      );\n      if (comparison !== 0) {\n        // Return the comparison result if documents are not equal\n        return direction === 'ascending' ? comparison : -comparison;\n      }\n    }\n\n    return 0;\n  });\n}\n\nfunction evaluateCollection(\n  _: EvaluationContext,\n  coll: CollectionSource,\n  inputs: PipelineInputOutput[]\n): PipelineInputOutput[] {\n  return inputs.filter(input => {\n    return (\n      input.isFoundDocument() &&\n      `/${input.key.getCollectionPath().canonicalString()}` ===\n        coll.formattedCollectionPath\n    );\n  });\n}\n\nfunction evaluateCollectionGroup(\n  context: EvaluationContext,\n  stage: CollectionGroupSource,\n  input: PipelineInputOutput[]\n): PipelineInputOutput[] {\n  // return those records in input whose collection id is stage.collectionId\n  return input.filter(input => {\n    return (\n      input.isFoundDocument() &&\n      input.key.getCollectionPath().lastSegment() === stage.collectionId\n    );\n  });\n}\n\nfunction evaluateDatabase(\n  context: EvaluationContext,\n  stage: DatabaseSource,\n  input: PipelineInputOutput[]\n): PipelineInputOutput[] {\n  return input.filter(input => input.isFoundDocument());\n}\n\nfunction evaluateDocuments(\n  context: EvaluationContext,\n  stage: DocumentsSource,\n  input: PipelineInputOutput[]\n): PipelineInputOutput[] {\n  return input.filter(input => {\n    return (\n      input.isFoundDocument() &&\n      stage.formattedPathsSet.has(input.key.path.toStringWithLeadingSlash())\n    );\n  });\n}\n\nexport function newPipelineComparator(\n  pipeline: CorePipeline\n): (d1: Document, d2: Document) => number {\n  const orderings = lastEffectiveSort(pipeline);\n  return (d1: Document, d2: Document): number => {\n    for (const ordering of orderings) {\n      // TODO(pipeline): consider the possibility of memoizing the evaluation\n      const leftValue = valueOrUndefined(\n        toEvaluable(ordering.expr).evaluate(\n          { serializer: pipeline.serializer },\n          d1 as MutableDocument\n        )\n      );\n      const rightValue = valueOrUndefined(\n        toEvaluable(ordering.expr).evaluate(\n          { serializer: pipeline.serializer },\n          d2 as MutableDocument\n        )\n      );\n      const comparison = valueCompare(\n        leftValue || MIN_VALUE,\n        rightValue || MIN_VALUE\n      );\n      if (comparison !== 0) {\n        return ordering.direction === 'ascending' ? comparison : -comparison;\n      }\n    }\n    return 0;\n  };\n}\n\nfunction lastEffectiveSort(pipeline: CorePipeline): Ordering[] {\n  // return the last sort stage, throws exception if it doesn't exist\n  // TODO(pipeline): this implementation is wrong, there are stages that can invalidate\n  // the orderings later. The proper way to manipulate the pipeline so that last Sort\n  // always has effects.\n  for (let i = pipeline.stages.length - 1; i >= 0; i--) {\n    const stage = pipeline.stages[i];\n    if (stage instanceof Sort) {\n      return stage.orderings;\n    }\n  }\n  throw new Error('Pipeline must contain at least one Sort stage');\n}\n\nexport function getLastEffectiveLimit(\n  pipeline: CorePipeline\n): { limit: number } | undefined {\n  // TODO(pipeline): Consider other stages that might imply a limit,\n  // e.g., FindNearestStage, once they are implemented.\n  for (let i = pipeline.stages.length - 1; i >= 0; i--) {\n    const stage = pipeline.stages[i];\n    if (stage instanceof Limit) {\n      return {\n        limit: stage.limit\n      };\n    }\n  }\n  return undefined;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, MutableDocumentMap } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */\nexport abstract class RemoteDocumentChangeBuffer {\n  // A mapping of document key to the new cache entry that should be written.\n  protected changes: ObjectMap<DocumentKey, MutableDocument> = new ObjectMap(\n    key => key.toString(),\n    (l, r) => l.isEqual(r)\n  );\n\n  private changesApplied = false;\n\n  protected abstract getFromCache(\n    transaction: PersistenceTransaction,\n    documentKey: DocumentKey\n  ): PersistencePromise<MutableDocument>;\n\n  protected abstract getAllFromCache(\n    transaction: PersistenceTransaction,\n    documentKeys: DocumentKeySet\n  ): PersistencePromise<MutableDocumentMap>;\n\n  protected abstract applyChanges(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<void>;\n\n  /**\n   * Buffers a `RemoteDocumentCache.addEntry()` call.\n   *\n   * You can only modify documents that have already been retrieved via\n   * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n   */\n  addEntry(document: MutableDocument): void {\n    this.assertNotApplied();\n    this.changes.set(document.key, document);\n  }\n\n  /**\n   * Buffers a `RemoteDocumentCache.removeEntry()` call.\n   *\n   * You can only remove documents that have already been retrieved via\n   * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n   */\n  removeEntry(key: DocumentKey, readTime: SnapshotVersion): void {\n    this.assertNotApplied();\n    this.changes.set(\n      key,\n      MutableDocument.newInvalidDocument(key).setReadTime(readTime)\n    );\n  }\n\n  /**\n   * Looks up an entry in the cache. The buffered changes will first be checked,\n   * and if no buffered change applies, this will forward to\n   * `RemoteDocumentCache.getEntry()`.\n   *\n   * @param transaction - The transaction in which to perform any persistence\n   *     operations.\n   * @param documentKey - The key of the entry to look up.\n   * @returns The cached document or an invalid document if we have nothing\n   * cached.\n   */\n  getEntry(\n    transaction: PersistenceTransaction,\n    documentKey: DocumentKey\n  ): PersistencePromise<MutableDocument> {\n    this.assertNotApplied();\n    const bufferedEntry = this.changes.get(documentKey);\n    if (bufferedEntry !== undefined) {\n      return PersistencePromise.resolve(bufferedEntry);\n    } else {\n      return this.getFromCache(transaction, documentKey);\n    }\n  }\n\n  /**\n   * Looks up several entries in the cache, forwarding to\n   * `RemoteDocumentCache.getEntry()`.\n   *\n   * @param transaction - The transaction in which to perform any persistence\n   *     operations.\n   * @param documentKeys - The keys of the entries to look up.\n   * @returns A map of cached documents, indexed by key. If an entry cannot be\n   *     found, the corresponding key will be mapped to an invalid document.\n   */\n  getEntries(\n    transaction: PersistenceTransaction,\n    documentKeys: DocumentKeySet\n  ): PersistencePromise<MutableDocumentMap> {\n    return this.getAllFromCache(transaction, documentKeys);\n  }\n\n  /**\n   * Applies buffered changes to the underlying RemoteDocumentCache, using\n   * the provided transaction.\n   */\n  apply(transaction: PersistenceTransaction): PersistencePromise<void> {\n    this.assertNotApplied();\n    this.changesApplied = true;\n    return this.applyChanges(transaction);\n  }\n\n  /** Helper to assert this.changes is not null  */\n  protected assertNotApplied(): void {\n    debugAssert(!this.changesApplied, 'Changes have already been applied.');\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getPipelineCollection } from '../core/pipeline';\nimport { isPipeline, QueryOrPipeline } from '../core/pipeline-util';\nimport { queryOrPipelineMatches } from '../core/pipeline_run';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n  DocumentKeySet,\n  DocumentSizeEntries,\n  MutableDocumentMap,\n  mutableDocumentMap,\n  OverlayMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager } from './index_manager';\nimport { dbDocumentSize } from './indexeddb_mutation_batch_impl';\nimport { DbRemoteDocument, DbRemoteDocumentGlobal } from './indexeddb_schema';\nimport {\n  DbRemoteDocumentCollectionGroupIndex,\n  DbRemoteDocumentDocumentKeyIndex,\n  DbRemoteDocumentGlobalKey,\n  DbRemoteDocumentGlobalStore,\n  DbRemoteDocumentKey,\n  DbRemoteDocumentStore,\n  DbTimestampKey\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n  fromDbRemoteDocument,\n  LocalSerializer,\n  toDbRemoteDocument,\n  toDbTimestampKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { SimpleDbStore } from './simple_db';\n\nexport interface DocumentSizeEntry {\n  document: MutableDocument;\n  size: number;\n}\n\nexport interface IndexedDbRemoteDocumentCache extends RemoteDocumentCache {\n  // The IndexedDbRemoteDocumentCache doesn't implement any methods on top\n  // of RemoteDocumentCache. This class exists for consistency.\n}\n\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */\nclass IndexedDbRemoteDocumentCacheImpl implements IndexedDbRemoteDocumentCache {\n  indexManager!: IndexManager;\n\n  constructor(readonly serializer: LocalSerializer) {}\n\n  setIndexManager(indexManager: IndexManager): void {\n    this.indexManager = indexManager;\n  }\n\n  /**\n   * Adds the supplied entries to the cache.\n   *\n   * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n   * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n   */\n  addEntry(\n    transaction: PersistenceTransaction,\n    key: DocumentKey,\n    doc: DbRemoteDocument\n  ): PersistencePromise<void> {\n    const documentStore = remoteDocumentsStore(transaction);\n    return documentStore.put(doc);\n  }\n\n  /**\n   * Removes a document from the cache.\n   *\n   * All calls of `removeEntry`  are required to go through the RemoteDocumentChangeBuffer\n   * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n   */\n  removeEntry(\n    transaction: PersistenceTransaction,\n    documentKey: DocumentKey,\n    readTime: SnapshotVersion\n  ): PersistencePromise<void> {\n    const store = remoteDocumentsStore(transaction);\n    return store.delete(dbReadTimeKey(documentKey, readTime));\n  }\n\n  /**\n   * Updates the current cache size.\n   *\n   * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n   * cache's metadata.\n   */\n  updateMetadata(\n    transaction: PersistenceTransaction,\n    sizeDelta: number\n  ): PersistencePromise<void> {\n    return this.getMetadata(transaction).next(metadata => {\n      metadata.byteSize += sizeDelta;\n      return this.setMetadata(transaction, metadata);\n    });\n  }\n\n  getEntry(\n    transaction: PersistenceTransaction,\n    documentKey: DocumentKey\n  ): PersistencePromise<MutableDocument> {\n    let doc = MutableDocument.newInvalidDocument(documentKey);\n    return remoteDocumentsStore(transaction)\n      .iterate(\n        {\n          index: DbRemoteDocumentDocumentKeyIndex,\n          range: IDBKeyRange.only(dbKey(documentKey))\n        },\n        (_, dbRemoteDoc) => {\n          doc = this.maybeDecodeDocument(documentKey, dbRemoteDoc);\n        }\n      )\n      .next(() => doc);\n  }\n\n  /**\n   * Looks up an entry in the cache.\n   *\n   * @param documentKey - The key of the entry to look up.\n   * @returns The cached document entry and its size.\n   */\n  getSizedEntry(\n    transaction: PersistenceTransaction,\n    documentKey: DocumentKey\n  ): PersistencePromise<DocumentSizeEntry> {\n    let result = {\n      size: 0,\n      document: MutableDocument.newInvalidDocument(documentKey)\n    };\n    return remoteDocumentsStore(transaction)\n      .iterate(\n        {\n          index: DbRemoteDocumentDocumentKeyIndex,\n          range: IDBKeyRange.only(dbKey(documentKey))\n        },\n        (_, dbRemoteDoc) => {\n          result = {\n            document: this.maybeDecodeDocument(documentKey, dbRemoteDoc),\n            size: dbDocumentSize(dbRemoteDoc)\n          };\n        }\n      )\n      .next(() => result);\n  }\n\n  getEntries(\n    transaction: PersistenceTransaction,\n    documentKeys: DocumentKeySet\n  ): PersistencePromise<MutableDocumentMap> {\n    let results = mutableDocumentMap();\n    return this.forEachDbEntry(\n      transaction,\n      documentKeys,\n      (key, dbRemoteDoc) => {\n        const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n        results = results.insert(key, doc);\n      }\n    ).next(() => results);\n  }\n\n  getAllEntries(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<MutableDocumentMap> {\n    let results = mutableDocumentMap();\n    return remoteDocumentsStore(transaction)\n      .iterate((dbKey, dbDoc) => {\n        const doc = this.maybeDecodeDocument(\n          DocumentKey.fromSegments(\n            dbDoc.prefixPath.concat(dbDoc.collectionGroup, dbDoc.documentId)\n          ),\n          dbDoc\n        );\n        results = results.insert(doc.key, doc);\n      })\n      .next(() => results);\n  }\n\n  /**\n   * Looks up several entries in the cache.\n   *\n   * @param documentKeys - The set of keys entries to look up.\n   * @returns A map of documents indexed by key and a map of sizes indexed by\n   *     key (zero if the document does not exist).\n   */\n  getSizedEntries(\n    transaction: PersistenceTransaction,\n    documentKeys: DocumentKeySet\n  ): PersistencePromise<DocumentSizeEntries> {\n    let results = mutableDocumentMap();\n    let sizeMap = new SortedMap<DocumentKey, number>(DocumentKey.comparator);\n    return this.forEachDbEntry(\n      transaction,\n      documentKeys,\n      (key, dbRemoteDoc) => {\n        const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n        results = results.insert(key, doc);\n        sizeMap = sizeMap.insert(key, dbDocumentSize(dbRemoteDoc));\n      }\n    ).next(() => {\n      return { documents: results, sizeMap };\n    });\n  }\n\n  private forEachDbEntry(\n    transaction: PersistenceTransaction,\n    documentKeys: DocumentKeySet,\n    callback: (key: DocumentKey, doc: DbRemoteDocument | null) => void\n  ): PersistencePromise<void> {\n    if (documentKeys.isEmpty()) {\n      return PersistencePromise.resolve();\n    }\n\n    let sortedKeys = new SortedSet<DocumentKey>(dbKeyComparator);\n    documentKeys.forEach(e => (sortedKeys = sortedKeys.add(e)));\n    const range = IDBKeyRange.bound(\n      dbKey(sortedKeys.first()!),\n      dbKey(sortedKeys.last()!)\n    );\n    const keyIter = sortedKeys.getIterator();\n    let nextKey: DocumentKey | null = keyIter.getNext();\n\n    return remoteDocumentsStore(transaction)\n      .iterate(\n        { index: DbRemoteDocumentDocumentKeyIndex, range },\n        (_, dbRemoteDoc, control) => {\n          const potentialKey = DocumentKey.fromSegments([\n            ...dbRemoteDoc.prefixPath,\n            dbRemoteDoc.collectionGroup,\n            dbRemoteDoc.documentId\n          ]);\n\n          // Go through keys not found in cache.\n          while (nextKey && dbKeyComparator(nextKey!, potentialKey) < 0) {\n            callback(nextKey!, null);\n            nextKey = keyIter.getNext();\n          }\n\n          if (nextKey && nextKey!.isEqual(potentialKey)) {\n            // Key found in cache.\n            callback(nextKey!, dbRemoteDoc);\n            nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n          }\n\n          // Skip to the next key (if there is one).\n          if (nextKey) {\n            control.skip(dbKey(nextKey));\n          } else {\n            control.done();\n          }\n        }\n      )\n      .next(() => {\n        // The rest of the keys are not in the cache. One case where `iterate`\n        // above won't go through them is when the cache is empty.\n        while (nextKey) {\n          callback(nextKey!, null);\n          nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n        }\n      });\n  }\n\n  getDocumentsMatchingQuery(\n    transaction: PersistenceTransaction,\n    query: QueryOrPipeline,\n    offset: IndexOffset,\n    mutatedDocs: OverlayMap,\n    context?: QueryContext\n  ): PersistencePromise<MutableDocumentMap> {\n    if (isPipeline(query)) {\n      debugAssert(\n        !!getPipelineCollection(query),\n        'getDocumentsMatchingQuery can only handle collection pipelines'\n      );\n    }\n\n    const collection = isPipeline(query)\n      ? ResourcePath.fromString(getPipelineCollection(query)!)\n      : 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            (queryOrPipelineMatches(query, document) ||\n              mutatedDocs.has(document.key))\n          ) {\n            // Either the document matches the given query, or it is mutated.\n            results = results.insert(document.key, document);\n          }\n        }\n        return results;\n      });\n  }\n\n  getAllFromCollectionGroup(\n    transaction: PersistenceTransaction,\n    collectionGroup: string,\n    offset: IndexOffset,\n    limit: number\n  ): PersistencePromise<MutableDocumentMap> {\n    debugAssert(limit > 0, 'Limit should be at least 1');\n    let results = mutableDocumentMap();\n\n    const startKey = dbCollectionGroupKey(collectionGroup, offset);\n    const endKey = dbCollectionGroupKey(collectionGroup, IndexOffset.max());\n    return remoteDocumentsStore(transaction)\n      .iterate(\n        {\n          index: DbRemoteDocumentCollectionGroupIndex,\n          range: IDBKeyRange.bound(startKey, endKey, true)\n        },\n        (_, dbRemoteDoc, control) => {\n          const document = this.maybeDecodeDocument(\n            DocumentKey.fromSegments(\n              dbRemoteDoc.prefixPath.concat(\n                dbRemoteDoc.collectionGroup,\n                dbRemoteDoc.documentId\n              )\n            ),\n            dbRemoteDoc\n          );\n          results = results.insert(document.key, document);\n          if (results.size === limit) {\n            control.done();\n          }\n        }\n      )\n      .next(() => results);\n  }\n\n  newChangeBuffer(options?: {\n    trackRemovals: boolean;\n  }): RemoteDocumentChangeBuffer {\n    return new IndexedDbRemoteDocumentChangeBuffer(\n      this,\n      !!options && options.trackRemovals\n    );\n  }\n\n  getSize(txn: PersistenceTransaction): PersistencePromise<number> {\n    return this.getMetadata(txn).next(metadata => metadata.byteSize);\n  }\n\n  private getMetadata(\n    txn: PersistenceTransaction\n  ): PersistencePromise<DbRemoteDocumentGlobal> {\n    return documentGlobalStore(txn)\n      .get(DbRemoteDocumentGlobalKey)\n      .next(metadata => {\n        hardAssert(!!metadata, 0x4e35, 'Missing document cache metadata');\n        return metadata!;\n      });\n  }\n\n  private setMetadata(\n    txn: PersistenceTransaction,\n    metadata: DbRemoteDocumentGlobal\n  ): PersistencePromise<void> {\n    return documentGlobalStore(txn).put(DbRemoteDocumentGlobalKey, metadata);\n  }\n\n  /**\n   * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n   * the document corresponds to the format used for sentinel deletes).\n   */\n  private maybeDecodeDocument(\n    documentKey: DocumentKey,\n    dbRemoteDoc: DbRemoteDocument | null\n  ): MutableDocument {\n    if (dbRemoteDoc) {\n      const doc = fromDbRemoteDocument(this.serializer, dbRemoteDoc);\n      // Whether the document is a sentinel removal and should only be used in the\n      // `getNewDocumentChanges()`\n      const isSentinelRemoval =\n        doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min());\n      if (!isSentinelRemoval) {\n        return doc;\n      }\n    }\n    return MutableDocument.newInvalidDocument(documentKey);\n  }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */\nexport function newIndexedDbRemoteDocumentCache(\n  serializer: LocalSerializer\n): IndexedDbRemoteDocumentCache {\n  return new IndexedDbRemoteDocumentCacheImpl(serializer);\n}\n\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */\nclass IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n  // A map of document sizes and read times prior to applying the changes in\n  // this buffer.\n  protected documentStates: ObjectMap<\n    DocumentKey,\n    { size: number; readTime: SnapshotVersion }\n  > = new ObjectMap(\n    key => key.toString(),\n    (l, r) => l.isEqual(r)\n  );\n\n  /**\n   * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n   * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n   * `getNewDocumentChanges()`.\n   */\n  constructor(\n    private readonly documentCache: IndexedDbRemoteDocumentCacheImpl,\n    private readonly trackRemovals: boolean\n  ) {\n    super();\n  }\n\n  protected applyChanges(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<void> {\n    const promises: Array<PersistencePromise<void>> = [];\n\n    let sizeDelta = 0;\n\n    let collectionParents = new SortedSet<ResourcePath>((l, r) =>\n      primitiveComparator(l.canonicalString(), r.canonicalString())\n    );\n\n    this.changes.forEach((key, documentChange) => {\n      const previousDoc = this.documentStates.get(key);\n      debugAssert(\n        previousDoc !== undefined,\n        `Cannot modify a document that wasn't read (for ${key})`\n      );\n      promises.push(\n        this.documentCache.removeEntry(transaction, key, previousDoc.readTime)\n      );\n      if (documentChange.isValidDocument()) {\n        debugAssert(\n          !documentChange.readTime.isEqual(SnapshotVersion.min()),\n          'Cannot add a document with a read time of zero'\n        );\n        const doc = toDbRemoteDocument(\n          this.documentCache.serializer,\n          documentChange\n        );\n        collectionParents = collectionParents.add(key.path.popLast());\n\n        const size = dbDocumentSize(doc);\n        sizeDelta += size - previousDoc.size;\n        promises.push(this.documentCache.addEntry(transaction, key, doc));\n      } else {\n        sizeDelta -= previousDoc.size;\n        if (this.trackRemovals) {\n          // In order to track removals, we store a \"sentinel delete\" in the\n          // RemoteDocumentCache. This entry is represented by a NoDocument\n          // with a version of 0 and ignored by `maybeDecodeDocument()` but\n          // preserved in `getNewDocumentChanges()`.\n          const deletedDoc = toDbRemoteDocument(\n            this.documentCache.serializer,\n            documentChange.convertToNoDocument(SnapshotVersion.min())\n          );\n          promises.push(\n            this.documentCache.addEntry(transaction, key, deletedDoc)\n          );\n        }\n      }\n    });\n\n    collectionParents.forEach(parent => {\n      promises.push(\n        this.documentCache.indexManager.addToCollectionParentIndex(\n          transaction,\n          parent\n        )\n      );\n    });\n\n    promises.push(this.documentCache.updateMetadata(transaction, sizeDelta));\n\n    return PersistencePromise.waitFor(promises);\n  }\n\n  protected getFromCache(\n    transaction: PersistenceTransaction,\n    documentKey: DocumentKey\n  ): PersistencePromise<MutableDocument> {\n    // Record the size of everything we load from the cache so we can compute a delta later.\n    return this.documentCache\n      .getSizedEntry(transaction, documentKey)\n      .next(getResult => {\n        this.documentStates.set(documentKey, {\n          size: getResult.size,\n          readTime: getResult.document.readTime\n        });\n        return getResult.document;\n      });\n  }\n\n  protected getAllFromCache(\n    transaction: PersistenceTransaction,\n    documentKeys: DocumentKeySet\n  ): PersistencePromise<MutableDocumentMap> {\n    // Record the size of everything we load from the cache so we can compute\n    // a delta later.\n    return this.documentCache\n      .getSizedEntries(transaction, documentKeys)\n      .next(({ documents, sizeMap }) => {\n        // Note: `getAllFromCache` returns two maps instead of a single map from\n        // keys to `DocumentSizeEntry`s. This is to allow returning the\n        // `MutableDocumentMap` directly, without a conversion.\n        sizeMap.forEach((documentKey, size) => {\n          this.documentStates.set(documentKey, {\n            size,\n            readTime: documents.get(documentKey)!.readTime\n          });\n        });\n        return documents;\n      });\n  }\n}\n\nfunction documentGlobalStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbRemoteDocumentGlobalKey, DbRemoteDocumentGlobal> {\n  return getStore<DbRemoteDocumentGlobalKey, DbRemoteDocumentGlobal>(\n    txn,\n    DbRemoteDocumentGlobalStore\n  );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbRemoteDocumentKey, DbRemoteDocument> {\n  return getStore<DbRemoteDocumentKey, DbRemoteDocument>(\n    txn,\n    DbRemoteDocumentStore\n  );\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */\nfunction dbKey(documentKey: DocumentKey): [string[], string, string] {\n  const path = documentKey.path.toArray();\n  return [\n    /* prefix path */ path.slice(0, path.length - 2),\n    /* collection id */ path[path.length - 2],\n    /* document id */ path[path.length - 1]\n  ];\n}\n\n/**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\nfunction dbReadTimeKey(\n  documentKey: DocumentKey,\n  readTime: SnapshotVersion\n): DbRemoteDocumentKey {\n  const path = documentKey.path.toArray();\n  return [\n    /* prefix path */ path.slice(0, path.length - 2),\n    /* collection id */ path[path.length - 2],\n    toDbTimestampKey(readTime),\n    /* document id */ path[path.length - 1]\n  ];\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */\nfunction dbCollectionGroupKey(\n  collectionGroup: string,\n  offset: IndexOffset\n): [string, DbTimestampKey, string[], string] {\n  const path = offset.documentKey.path.toArray();\n  return [\n    /* collection id */ collectionGroup,\n    toDbTimestampKey(offset.readTime),\n    /* prefix path */ path.slice(0, path.length - 2),\n    /* document id */ path.length > 0 ? path[path.length - 1] : ''\n  ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */\nexport function dbKeyComparator(l: DocumentKey, r: DocumentKey): number {\n  const left = l.path.toArray();\n  const right = r.path.toArray();\n\n  // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n  let cmp = 0;\n  for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) {\n    cmp = primitiveComparator(left[i], right[i]);\n    if (cmp) {\n      return cmp;\n    }\n  }\n\n  cmp = primitiveComparator(left.length, right.length);\n  if (cmp) {\n    return cmp;\n  }\n\n  cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]);\n  if (cmp) {\n    return cmp;\n  }\n\n  // 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  PipelineQueryTarget as ProtoPipelineQueryTarget,\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 =\n  | ProtoQueryTarget\n  | ProtoDocumentsTarget\n  | ProtoPipelineQueryTarget;\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  CorePipeline,\n  getPipelineCollection,\n  getPipelineCollectionGroup,\n  getPipelineDocuments,\n  getPipelineSourceType\n} from '../core/pipeline';\nimport {\n  asCollectionPipelineAtPath,\n  canonifyPipeline,\n  isPipeline,\n  QueryOrPipeline\n} from '../core/pipeline-util';\nimport { pipelineMatches } from '../core/pipeline_run';\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 { FirestoreError } from '../util/error';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { LocalWriteResult } from './local_store_impl';\nimport { MutationQueue } from './mutation_queue';\nimport { OverlayedDocument } from './overlayed_document';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\n\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */\nexport class LocalDocumentsView {\n  constructor(\n    readonly remoteDocumentCache: RemoteDocumentCache,\n    readonly mutationQueue: MutationQueue,\n    readonly documentOverlayCache: DocumentOverlayCache,\n    readonly indexManager: IndexManager\n  ) {}\n\n  /**\n   * Get the local view of the document identified by `key`.\n   *\n   * @returns Local view of the document or null if we don't have any cached\n   * state for it.\n   */\n  getDocument(\n    transaction: PersistenceTransaction,\n    key: DocumentKey\n  ): PersistencePromise<Document> {\n    let overlay: Overlay | null = null;\n    return this.documentOverlayCache\n      .getOverlay(transaction, key)\n      .next(value => {\n        overlay = value;\n        return this.remoteDocumentCache.getEntry(transaction, key);\n      })\n      .next(document => {\n        if (overlay !== null) {\n          mutationApplyToLocalView(\n            overlay.mutation,\n            document,\n            FieldMask.empty(),\n            Timestamp.now()\n          );\n        }\n        return document as Document;\n      });\n  }\n\n  /**\n   * Gets the local view of the documents identified by `keys`.\n   *\n   * If we don't have cached state for a document in `keys`, a NoDocument will\n   * be stored for that key in the resulting set.\n   */\n  getDocuments(\n    transaction: PersistenceTransaction,\n    keys: DocumentKeySet\n  ): PersistencePromise<DocumentMap> {\n    return this.remoteDocumentCache\n      .getEntries(transaction, keys)\n      .next(docs =>\n        this.getLocalViewOfDocuments(transaction, docs, documentKeySet()).next(\n          () => docs as DocumentMap\n        )\n      );\n  }\n\n  /**\n   * Similar to `getDocuments`, but creates the local view from the given\n   * `baseDocs` without retrieving documents from the local store.\n   *\n   * @param transaction - The transaction this operation is scoped to.\n   * @param docs - The documents to apply local mutations to get the local views.\n   * @param existenceStateChanged - The set of document keys whose existence state\n   *   is changed. This is useful to determine if some documents overlay needs\n   *   to be recalculated.\n   */\n  getLocalViewOfDocuments(\n    transaction: PersistenceTransaction,\n    docs: MutableDocumentMap,\n    existenceStateChanged: DocumentKeySet = documentKeySet()\n  ): PersistencePromise<DocumentMap> {\n    const overlays = newOverlayMap();\n    return this.populateOverlays(transaction, overlays, docs).next(() => {\n      return this.computeViews(\n        transaction,\n        docs,\n        overlays,\n        existenceStateChanged\n      ).next(computeViewsResult => {\n        let result = documentMap();\n        computeViewsResult.forEach((documentKey, overlayedDocument) => {\n          result = result.insert(\n            documentKey,\n            overlayedDocument.overlayedDocument\n          );\n        });\n        return result;\n      });\n    });\n  }\n\n  /**\n   * Gets the overlayed documents for the given document map, which will include\n   * the local view of those documents and a `FieldMask` indicating which fields\n   * are mutated locally, `null` if overlay is a Set or Delete mutation.\n   */\n  getOverlayedDocuments(\n    transaction: PersistenceTransaction,\n    docs: MutableDocumentMap\n  ): PersistencePromise<OverlayedDocumentMap> {\n    const overlays = newOverlayMap();\n    return this.populateOverlays(transaction, overlays, docs).next(() =>\n      this.computeViews(transaction, docs, overlays, documentKeySet())\n    );\n  }\n\n  /**\n   * Fetches the overlays for {@code docs} and adds them to provided overlay map\n   * if the map does not already contain an entry for the given document key.\n   */\n  private populateOverlays(\n    transaction: PersistenceTransaction,\n    overlays: OverlayMap,\n    docs: MutableDocumentMap\n  ): PersistencePromise<void> {\n    const missingOverlays: DocumentKey[] = [];\n    docs.forEach(key => {\n      if (!overlays.has(key)) {\n        missingOverlays.push(key);\n      }\n    });\n    return this.documentOverlayCache\n      .getOverlays(transaction, missingOverlays)\n      .next(result => {\n        result.forEach((key, val) => {\n          overlays.set(key, val);\n        });\n      });\n  }\n\n  /**\n   * Computes the local view for the given documents.\n   *\n   * @param docs - The documents to compute views for. It also has the base\n   *   version of the documents.\n   * @param overlays - The overlays that need to be applied to the given base\n   *   version of the documents.\n   * @param existenceStateChanged - A set of documents whose existence states\n   *   might have changed. This is used to determine if we need to re-calculate\n   *   overlays from mutation queues.\n   * @returns A map represents the local documents view.\n   */\n  computeViews(\n    transaction: PersistenceTransaction,\n    docs: MutableDocumentMap,\n    overlays: OverlayMap,\n    existenceStateChanged: DocumentKeySet\n  ): PersistencePromise<OverlayedDocumentMap> {\n    let recalculateDocuments = mutableDocumentMap();\n    const mutatedFields = newDocumentKeyMap<FieldMask | null>();\n    const results = newOverlayedDocumentMap();\n    docs.forEach((_, doc) => {\n      const overlay = overlays.get(doc.key);\n      // Recalculate an overlay if the document's existence state changed due to\n      // a remote event *and* the overlay is a PatchMutation. This is because\n      // document existence state can change if some patch mutation's\n      // preconditions are met.\n      // NOTE: we recalculate when `overlay` is undefined as well, because there\n      // might be a patch mutation whose precondition does not match before the\n      // change (hence overlay is undefined), but would now match.\n      if (\n        existenceStateChanged.has(doc.key) &&\n        (overlay === undefined || overlay.mutation instanceof PatchMutation)\n      ) {\n        recalculateDocuments = recalculateDocuments.insert(doc.key, doc);\n      } else if (overlay !== undefined) {\n        mutatedFields.set(doc.key, overlay.mutation.getFieldMask());\n        mutationApplyToLocalView(\n          overlay.mutation,\n          doc,\n          overlay.mutation.getFieldMask(),\n          Timestamp.now()\n        );\n      } else {\n        // no overlay exists\n        // Using EMPTY to indicate there is no overlay for the document.\n        mutatedFields.set(doc.key, FieldMask.empty());\n      }\n    });\n\n    return this.recalculateAndSaveOverlays(\n      transaction,\n      recalculateDocuments\n    ).next(recalculatedFields => {\n      recalculatedFields.forEach((documentKey, mask) =>\n        mutatedFields.set(documentKey, mask)\n      );\n      docs.forEach((documentKey, document) =>\n        results.set(\n          documentKey,\n          new OverlayedDocument(\n            document,\n            mutatedFields.get(documentKey) ?? null\n          )\n        )\n      );\n      return results;\n    });\n  }\n\n  private recalculateAndSaveOverlays(\n    transaction: PersistenceTransaction,\n    docs: MutableDocumentMap\n  ): PersistencePromise<DocumentKeyMap<FieldMask | null>> {\n    const masks = newDocumentKeyMap<FieldMask | null>();\n    // A reverse lookup map from batch id to the documents within that batch.\n    let documentsByBatchId = new SortedMap<number, DocumentKeySet>(\n      (key1: number, key2: number) => key1 - key2\n    );\n    let processed = documentKeySet();\n    return this.mutationQueue\n      .getAllMutationBatchesAffectingDocumentKeys(transaction, docs)\n      .next(batches => {\n        for (const batch of batches) {\n          batch.keys().forEach(key => {\n            const baseDoc = docs.get(key);\n            if (baseDoc === null) {\n              return;\n            }\n            let mask: FieldMask | null = masks.get(key) || FieldMask.empty();\n            mask = batch.applyToLocalView(baseDoc, mask);\n            masks.set(key, mask);\n            const newSet = (\n              documentsByBatchId.get(batch.batchId) || documentKeySet()\n            ).add(key);\n            documentsByBatchId = documentsByBatchId.insert(\n              batch.batchId,\n              newSet\n            );\n          });\n        }\n      })\n      .next(() => {\n        const promises: Array<PersistencePromise<void>> = [];\n        // Iterate in descending order of batch IDs, and skip documents that are\n        // already saved.\n        const iter = documentsByBatchId.getReverseIterator();\n        while (iter.hasNext()) {\n          const entry = iter.getNext();\n          const batchId = entry.key;\n          const keys = entry.value;\n          const overlays = newMutationMap();\n          keys.forEach(key => {\n            if (!processed.has(key)) {\n              const overlayMutation = calculateOverlayMutation(\n                docs.get(key)!,\n                masks.get(key)!\n              );\n              if (overlayMutation !== null) {\n                overlays.set(key, overlayMutation);\n              }\n              processed = processed.add(key);\n            }\n          });\n          promises.push(\n            this.documentOverlayCache.saveOverlays(\n              transaction,\n              batchId,\n              overlays\n            )\n          );\n        }\n        return PersistencePromise.waitFor(promises);\n      })\n      .next(() => masks);\n  }\n\n  /**\n   * Recalculates overlays by reading the documents from remote document cache\n   * first, and saves them after they are calculated.\n   */\n  recalculateAndSaveOverlaysForDocumentKeys(\n    transaction: PersistenceTransaction,\n    documentKeys: DocumentKeySet\n  ): PersistencePromise<DocumentKeyMap<FieldMask | null>> {\n    return this.remoteDocumentCache\n      .getEntries(transaction, documentKeys)\n      .next(docs => this.recalculateAndSaveOverlays(transaction, docs));\n  }\n\n  /**\n   * Performs a query against the local view of all documents.\n   *\n   * @param transaction - The persistence transaction.\n   * @param query - The query to match documents against.\n   * @param offset - Read time and key to start scanning by (exclusive).\n   * @param context - A optional tracker to keep a record of important details\n   *   during database local query execution.\n   */\n  getDocumentsMatchingQuery(\n    transaction: PersistenceTransaction,\n    query: QueryOrPipeline,\n    offset: IndexOffset,\n    context?: QueryContext\n  ): PersistencePromise<DocumentMap> {\n    if (isPipeline(query)) {\n      return this.getDocumentsMatchingPipeline(\n        transaction,\n        query,\n        offset,\n        context\n      );\n    } else if (isDocumentQuery(query)) {\n      return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n    } else if (isCollectionGroupQuery(query)) {\n      return this.getDocumentsMatchingCollectionGroupQuery(\n        transaction,\n        query,\n        offset,\n        context\n      );\n    } else {\n      return this.getDocumentsMatchingCollectionQuery(\n        transaction,\n        query,\n        offset,\n        context\n      );\n    }\n  }\n\n  /**\n   * Given a collection group, returns the next documents that follow the provided offset, along\n   * with an updated batch ID.\n   *\n   * <p>The documents returned by this method are ordered by remote version from the provided\n   * offset. If there are no more remote documents after the provided offset, documents with\n   * mutations in order of batch id from the offset are returned. Since all documents in a batch are\n   * returned together, the total number of documents returned can exceed {@code count}.\n   *\n   * @param transaction\n   * @param collectionGroup - The collection group for the documents.\n   * @param offset - The offset to index into.\n   * @param count - The number of documents to return\n   * @returns A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.\n   */\n  getNextDocuments(\n    transaction: PersistenceTransaction,\n    collectionGroup: string,\n    offset: IndexOffset,\n    count: number\n  ): PersistencePromise<LocalWriteResult> {\n    return this.remoteDocumentCache\n      .getAllFromCollectionGroup(transaction, collectionGroup, offset, count)\n      .next((originalDocs: MutableDocumentMap) => {\n        const overlaysPromise: PersistencePromise<OverlayMap> =\n          count - originalDocs.size > 0\n            ? this.documentOverlayCache.getOverlaysForCollectionGroup(\n                transaction,\n                collectionGroup,\n                offset.largestBatchId,\n                count - originalDocs.size\n              )\n            : PersistencePromise.resolve(newOverlayMap());\n        // The callsite will use the largest batch ID together with the latest read time to create\n        // a new index offset. Since we only process batch IDs if all remote documents have been read,\n        // no overlay will increase the overall read time. This is why we only need to special case\n        // the batch id.\n        let largestBatchId = INITIAL_LARGEST_BATCH_ID;\n        let modifiedDocs = originalDocs;\n        return overlaysPromise.next(overlays => {\n          return PersistencePromise.forEach(\n            overlays,\n            (key: DocumentKey, overlay: Overlay) => {\n              if (largestBatchId < overlay.largestBatchId) {\n                largestBatchId = overlay.largestBatchId;\n              }\n              if (originalDocs.get(key)) {\n                return PersistencePromise.resolve();\n              }\n              return this.remoteDocumentCache\n                .getEntry(transaction, key)\n                .next(doc => {\n                  modifiedDocs = modifiedDocs.insert(key, doc);\n                });\n            }\n          )\n            .next(() =>\n              this.populateOverlays(transaction, overlays, originalDocs)\n            )\n            .next(() =>\n              this.computeViews(\n                transaction,\n                modifiedDocs,\n                overlays,\n                documentKeySet()\n              )\n            )\n            .next(localDocs => ({\n              batchId: largestBatchId,\n              changes: convertOverlayedDocumentMapToDocumentMap(localDocs)\n            }));\n        });\n      });\n  }\n\n  private getDocumentsMatchingDocumentQuery(\n    transaction: PersistenceTransaction,\n    docPath: ResourcePath\n  ): PersistencePromise<DocumentMap> {\n    // Just do a simple document lookup.\n    return this.getDocument(transaction, new DocumentKey(docPath)).next(\n      document => {\n        let result = documentMap();\n        if (document.isFoundDocument()) {\n          result = result.insert(document.key, document);\n        }\n        return result;\n      }\n    );\n  }\n\n  private getDocumentsMatchingCollectionGroupQuery(\n    transaction: PersistenceTransaction,\n    query: Query,\n    offset: IndexOffset,\n    context?: QueryContext\n  ): PersistencePromise<DocumentMap> {\n    debugAssert(\n      query.path.isEmpty(),\n      'Currently we only support collection group queries at the root.'\n    );\n    const collectionId = query.collectionGroup!;\n    let results = documentMap();\n    return this.indexManager\n      .getCollectionParents(transaction, collectionId)\n      .next(parents => {\n        // Perform a collection query against each parent that contains the\n        // collectionId and aggregate the results.\n        return PersistencePromise.forEach(parents, (parent: ResourcePath) => {\n          const collectionQuery = asCollectionQueryAtPath(\n            query,\n            parent.child(collectionId)\n          );\n          return this.getDocumentsMatchingCollectionQuery(\n            transaction,\n            collectionQuery,\n            offset,\n            context\n          ).next(r => {\n            r.forEach((key, doc) => {\n              results = results.insert(key, doc);\n            });\n          });\n        }).next(() => results);\n      });\n  }\n\n  private getDocumentsMatchingCollectionQuery(\n    transaction: PersistenceTransaction,\n    query: Query,\n    offset: IndexOffset,\n    context?: QueryContext\n  ): PersistencePromise<DocumentMap> {\n    // Query the remote documents and overlay mutations.\n    let overlays: OverlayMap;\n    return this.documentOverlayCache\n      .getOverlaysForCollection(transaction, query.path, offset.largestBatchId)\n      .next(result => {\n        overlays = result;\n        return this.remoteDocumentCache.getDocumentsMatchingQuery(\n          transaction,\n          query,\n          offset,\n          overlays,\n          context\n        );\n      })\n      .next(remoteDocuments => {\n        return this.retrieveMatchingLocalDocuments(\n          overlays,\n          remoteDocuments,\n          doc => queryMatches(query, doc)\n        );\n      });\n  }\n\n  private getDocumentsMatchingPipeline(\n    txn: PersistenceTransaction,\n    pipeline: CorePipeline,\n    offset: IndexOffset,\n    context?: QueryContext\n  ): PersistencePromise<DocumentMap> {\n    if (getPipelineSourceType(pipeline) === 'collection_group') {\n      const collectionId = getPipelineCollectionGroup(pipeline)!;\n      let results = documentMap();\n      return this.indexManager\n        .getCollectionParents(txn, 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 collectionPipeline = asCollectionPipelineAtPath(\n              pipeline,\n              parent.child(collectionId)\n            );\n            return this.getDocumentsMatchingPipeline(\n              txn,\n              collectionPipeline,\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    } else {\n      // Query the remote documents and overlay mutations.\n      let overlays: OverlayMap;\n      return this.getOverlaysForPipeline(txn, pipeline, offset.largestBatchId)\n        .next(result => {\n          overlays = result;\n          switch (getPipelineSourceType(pipeline)) {\n            case 'collection':\n              return this.remoteDocumentCache.getDocumentsMatchingQuery(\n                txn,\n                pipeline,\n                offset,\n                overlays,\n                context\n              );\n            case 'documents':\n              let keys = documentKeySet();\n              for (const key of getPipelineDocuments(pipeline)!) {\n                keys = keys.add(DocumentKey.fromPath(key));\n              }\n              return this.remoteDocumentCache.getEntries(txn, keys);\n            case 'database':\n              return this.remoteDocumentCache.getAllEntries(txn);\n            default:\n              throw new FirestoreError(\n                'invalid-argument',\n                `Invalid pipeline source to execute offline: ${canonifyPipeline(\n                  pipeline\n                )}`\n              );\n          }\n        })\n        .next(remoteDocuments => {\n          return this.retrieveMatchingLocalDocuments(\n            overlays,\n            remoteDocuments,\n            doc => pipelineMatches(pipeline, doc as MutableDocument)\n          );\n        });\n    }\n  }\n\n  private retrieveMatchingLocalDocuments(\n    overlays: OverlayMap,\n    remoteDocuments: MutableDocumentMap,\n    matcher: (d: Document) => boolean\n  ): DocumentMap {\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 (matcher(document)) {\n        results = results.insert(key, document);\n      }\n    });\n    return results;\n  }\n\n  private getOverlaysForPipeline(\n    txn: PersistenceTransaction,\n    pipeline: CorePipeline,\n    largestBatchId: number\n  ): PersistencePromise<OverlayMap> {\n    switch (getPipelineSourceType(pipeline)) {\n      case 'collection':\n        return this.documentOverlayCache.getOverlaysForCollection(\n          txn,\n          ResourcePath.fromString(getPipelineCollection(pipeline)!),\n          largestBatchId\n        );\n      case 'collection_group':\n        throw new FirestoreError(\n          'invalid-argument',\n          `Unexpected collection group pipeline: ${canonifyPipeline(pipeline)}`\n        );\n      case 'documents':\n        return this.documentOverlayCache.getOverlays(\n          txn,\n          getPipelineDocuments(pipeline)!.map(key => DocumentKey.fromPath(key))\n        );\n      case 'database':\n        return this.documentOverlayCache.getAllOverlays(txn, largestBatchId);\n      case 'unknown':\n      default:\n        throw new FirestoreError(\n          'invalid-argument',\n          `Failed to get overlays for pipeline: ${canonifyPipeline(pipeline)}`\n        );\n    }\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n  NamedQuery as ProtoNamedQuery,\n  BundleMetadata as ProtoBundleMetadata\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport {\n  fromBundleMetadata,\n  fromProtoNamedQuery,\n  LocalSerializer\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\nexport class MemoryBundleCache implements BundleCache {\n  private bundles = new Map<string, BundleMetadata>();\n  private namedQueries = new Map<string, NamedQuery>();\n\n  constructor(private serializer: LocalSerializer) {}\n\n  getBundleMetadata(\n    transaction: PersistenceTransaction,\n    bundleId: string\n  ): PersistencePromise<BundleMetadata | undefined> {\n    return PersistencePromise.resolve(this.bundles.get(bundleId));\n  }\n\n  saveBundleMetadata(\n    transaction: PersistenceTransaction,\n    bundleMetadata: ProtoBundleMetadata\n  ): PersistencePromise<void> {\n    this.bundles.set(bundleMetadata.id!, fromBundleMetadata(bundleMetadata));\n    return PersistencePromise.resolve();\n  }\n\n  getNamedQuery(\n    transaction: PersistenceTransaction,\n    queryName: string\n  ): PersistencePromise<NamedQuery | undefined> {\n    return PersistencePromise.resolve(this.namedQueries.get(queryName));\n  }\n\n  saveNamedQuery(\n    transaction: PersistenceTransaction,\n    query: ProtoNamedQuery\n  ): PersistencePromise<void> {\n    this.namedQueries.set(query.name!, fromProtoNamedQuery(query));\n    return PersistencePromise.resolve();\n  }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  documentKeySet,\n  DocumentKeySet,\n  MutationMap,\n  OverlayMap,\n  newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of DocumentOverlayCache.\n */\nexport class MemoryDocumentOverlayCache implements DocumentOverlayCache {\n  // A map sorted by DocumentKey, whose value is a pair of the largest batch id\n  // for the overlay and the overlay itself.\n  private overlays = new SortedMap<DocumentKey, Overlay>(\n    DocumentKey.comparator\n  );\n  private overlayByBatchId = new Map<number, DocumentKeySet>();\n\n  getOverlay(\n    transaction: PersistenceTransaction,\n    key: DocumentKey\n  ): PersistencePromise<Overlay | null> {\n    return PersistencePromise.resolve(this.overlays.get(key));\n  }\n\n  getOverlays(\n    transaction: PersistenceTransaction,\n    keys: DocumentKey[]\n  ): PersistencePromise<OverlayMap> {\n    const result = newOverlayMap();\n    return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n      return this.getOverlay(transaction, key).next(overlay => {\n        if (overlay !== null) {\n          result.set(key, overlay);\n        }\n      });\n    }).next(() => result);\n  }\n\n  getAllOverlays(\n    transaction: PersistenceTransaction,\n    sinceBatchId: number\n  ): PersistencePromise<OverlayMap> {\n    const overlays = newOverlayMap();\n    this.overlays.forEach((key, overlay) => {\n      if (overlay.largestBatchId > sinceBatchId) {\n        overlays.set(key, overlay);\n      }\n    });\n    return PersistencePromise.resolve(overlays);\n  }\n\n  saveOverlays(\n    transaction: PersistenceTransaction,\n    largestBatchId: number,\n    overlays: MutationMap\n  ): PersistencePromise<void> {\n    overlays.forEach((_, mutation) => {\n      this.saveOverlay(transaction, largestBatchId, mutation);\n    });\n    return PersistencePromise.resolve();\n  }\n\n  removeOverlaysForBatchId(\n    transaction: PersistenceTransaction,\n    documentKeys: DocumentKeySet,\n    batchId: number\n  ): PersistencePromise<void> {\n    const keys = this.overlayByBatchId.get(batchId);\n    if (keys !== undefined) {\n      keys.forEach(key => (this.overlays = this.overlays.remove(key)));\n      this.overlayByBatchId.delete(batchId);\n    }\n    return PersistencePromise.resolve();\n  }\n\n  getOverlaysForCollection(\n    transaction: PersistenceTransaction,\n    collection: ResourcePath,\n    sinceBatchId: number\n  ): PersistencePromise<OverlayMap> {\n    const result = newOverlayMap();\n\n    const immediateChildrenPathLength = collection.length + 1;\n    const prefix = new DocumentKey(collection.child(''));\n    const iter = this.overlays.getIteratorFrom(prefix);\n    while (iter.hasNext()) {\n      const entry = iter.getNext();\n      const overlay = entry.value;\n      const key = overlay.getKey();\n      if (!collection.isPrefixOf(key.path)) {\n        break;\n      }\n      // Documents from sub-collections\n      if (key.path.length !== immediateChildrenPathLength) {\n        continue;\n      }\n      if (overlay.largestBatchId > sinceBatchId) {\n        result.set(overlay.getKey(), overlay);\n      }\n    }\n\n    return PersistencePromise.resolve(result);\n  }\n\n  getOverlaysForCollectionGroup(\n    transaction: PersistenceTransaction,\n    collectionGroup: string,\n    sinceBatchId: number,\n    count: number\n  ): PersistencePromise<OverlayMap> {\n    let batchIdToOverlays = new SortedMap<number, OverlayMap>(\n      (key1: number, key2: number) => key1 - key2\n    );\n\n    const iter = this.overlays.getIterator();\n    while (iter.hasNext()) {\n      const entry = iter.getNext();\n      const overlay = entry.value;\n      const key = overlay.getKey();\n      if (key.getCollectionGroup() !== collectionGroup) {\n        continue;\n      }\n      if (overlay.largestBatchId > sinceBatchId) {\n        let overlaysForBatchId = batchIdToOverlays.get(overlay.largestBatchId);\n        if (overlaysForBatchId === null) {\n          overlaysForBatchId = newOverlayMap();\n          batchIdToOverlays = batchIdToOverlays.insert(\n            overlay.largestBatchId,\n            overlaysForBatchId\n          );\n        }\n        overlaysForBatchId.set(overlay.getKey(), overlay);\n      }\n    }\n\n    const result = newOverlayMap();\n    const batchIter = batchIdToOverlays.getIterator();\n    while (batchIter.hasNext()) {\n      const entry = batchIter.getNext();\n      const overlays = entry.value;\n      overlays.forEach((key, overlay) => result.set(key, overlay));\n      if (result.size() >= count) {\n        break;\n      }\n    }\n    return PersistencePromise.resolve(result);\n  }\n\n  private saveOverlay(\n    transaction: PersistenceTransaction,\n    largestBatchId: number,\n    mutation: Mutation\n  ): void {\n    // Remove the association of the overlay to its batch id.\n    const existing = this.overlays.get(mutation.key);\n    if (existing !== null) {\n      const newSet = this.overlayByBatchId\n        .get(existing.largestBatchId)!\n        .delete(mutation.key);\n      this.overlayByBatchId.set(existing.largestBatchId, newSet);\n    }\n\n    this.overlays = this.overlays.insert(\n      mutation.key,\n      new Overlay(largestBatchId, mutation)\n    );\n\n    // Create the association of this overlay to the given largestBatchId.\n    let batch = this.overlayByBatchId.get(largestBatchId);\n    if (batch === undefined) {\n      batch = documentKeySet();\n      this.overlayByBatchId.set(largestBatchId, batch);\n    }\n    this.overlayByBatchId.set(largestBatchId, batch.add(mutation.key));\n  }\n}\n","/**\n * @license\n * Copyright 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<ByteString> {\n    return PersistencePromise.resolve(this.sessionToken);\n  }\n\n  setSessionToken(\n    transaction: PersistenceTransaction,\n    sessionToken: ByteString\n  ): PersistencePromise<void> {\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<boolean> {\n    return PersistencePromise.resolve(this.mutationQueue.length === 0);\n  }\n\n  addMutationBatch(\n    transaction: PersistenceTransaction,\n    localWriteTime: Timestamp,\n    baseMutations: Mutation[],\n    mutations: Mutation[]\n  ): PersistencePromise<MutationBatch> {\n    debugAssert(mutations.length !== 0, 'Mutation batches should not be empty');\n\n    const batchId = this.nextBatchId;\n    this.nextBatchId++;\n\n    if (this.mutationQueue.length > 0) {\n      const prior = this.mutationQueue[this.mutationQueue.length - 1];\n      debugAssert(\n        prior.batchId < batchId,\n        'Mutation batchIDs must be monotonically increasing order'\n      );\n    }\n\n    const batch = new MutationBatch(\n      batchId,\n      localWriteTime,\n      baseMutations,\n      mutations\n    );\n    this.mutationQueue.push(batch);\n\n    // Track references by document key and index collection parents.\n    for (const mutation of mutations) {\n      this.batchesByDocumentKey = this.batchesByDocumentKey.add(\n        new DocReference(mutation.key, batchId)\n      );\n\n      this.indexManager.addToCollectionParentIndex(\n        transaction,\n        mutation.key.path.popLast()\n      );\n    }\n\n    return PersistencePromise.resolve(batch);\n  }\n\n  lookupMutationBatch(\n    transaction: PersistenceTransaction,\n    batchId: BatchId\n  ): PersistencePromise<MutationBatch | null> {\n    return PersistencePromise.resolve(this.findMutationBatch(batchId));\n  }\n\n  getNextMutationBatchAfterBatchId(\n    transaction: PersistenceTransaction,\n    batchId: BatchId\n  ): PersistencePromise<MutationBatch | null> {\n    const nextBatchId = batchId + 1;\n\n    // The requested batchId may still be out of range so normalize it to the\n    // start of the queue.\n    const rawIndex = this.indexOfBatchId(nextBatchId);\n    const index = rawIndex < 0 ? 0 : rawIndex;\n    return PersistencePromise.resolve(\n      this.mutationQueue.length > index ? this.mutationQueue[index] : null\n    );\n  }\n\n  getHighestUnacknowledgedBatchId(): PersistencePromise<BatchId> {\n    return PersistencePromise.resolve(\n      this.mutationQueue.length === 0 ? BATCHID_UNKNOWN : this.nextBatchId - 1\n    );\n  }\n\n  getAllMutationBatches(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<MutationBatch[]> {\n    return PersistencePromise.resolve(this.mutationQueue.slice());\n  }\n\n  getAllMutationBatchesAffectingDocumentKey(\n    transaction: PersistenceTransaction,\n    documentKey: DocumentKey\n  ): PersistencePromise<MutationBatch[]> {\n    const start = new DocReference(documentKey, 0);\n    const end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n    const result: MutationBatch[] = [];\n    this.batchesByDocumentKey.forEachInRange([start, end], ref => {\n      debugAssert(\n        documentKey.isEqual(ref.key),\n        \"Should only iterate over a single key's batches\"\n      );\n      const batch = this.findMutationBatch(ref.targetOrBatchId);\n      debugAssert(\n        batch !== null,\n        'Batches in the index must exist in the main table'\n      );\n      result.push(batch!);\n    });\n\n    return PersistencePromise.resolve(result);\n  }\n\n  getAllMutationBatchesAffectingDocumentKeys(\n    transaction: PersistenceTransaction,\n    documentKeys: SortedMap<DocumentKey, unknown>\n  ): PersistencePromise<MutationBatch[]> {\n    let uniqueBatchIDs = new SortedSet<number>(primitiveComparator);\n\n    documentKeys.forEach(documentKey => {\n      const start = new DocReference(documentKey, 0);\n      const end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n      this.batchesByDocumentKey.forEachInRange([start, end], ref => {\n        debugAssert(\n          documentKey.isEqual(ref.key),\n          \"For each key, should only iterate over a single key's batches\"\n        );\n\n        uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n      });\n    });\n\n    return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n  }\n\n  getAllMutationBatchesAffectingQuery(\n    transaction: PersistenceTransaction,\n    query: Query\n  ): PersistencePromise<MutationBatch[]> {\n    debugAssert(\n      !isCollectionGroupQuery(query),\n      'CollectionGroup queries should be handled in LocalDocumentsView'\n    );\n    // Use the query path as a prefix for testing if a document matches the\n    // query.\n    const prefix = query.path;\n    const immediateChildrenPathLength = prefix.length + 1;\n\n    // Construct a document reference for actually scanning the index. Unlike\n    // the prefix the document key in this reference must have an even number of\n    // segments. The empty segment can be used a suffix of the query path\n    // because it precedes all other segments in an ordered traversal.\n    let startPath = prefix;\n    if (!DocumentKey.isDocumentKey(startPath)) {\n      startPath = startPath.child('');\n    }\n\n    const start = new DocReference(new DocumentKey(startPath), 0);\n\n    // Find unique batchIDs referenced by all documents potentially matching the\n    // query.\n    let uniqueBatchIDs = new SortedSet<number>(primitiveComparator);\n\n    this.batchesByDocumentKey.forEachWhile(ref => {\n      const rowKeyPath = ref.key.path;\n      if (!prefix.isPrefixOf(rowKeyPath)) {\n        return false;\n      } else {\n        // Rows with document keys more than one segment longer than the query\n        // path can't be matches. For example, a query on 'rooms' can't match\n        // the document /rooms/abc/messages/xyx.\n        // TODO(mcg): we'll need a different scanner when we implement\n        // ancestor queries.\n        if (rowKeyPath.length === immediateChildrenPathLength) {\n          uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n        }\n        return true;\n      }\n    }, start);\n\n    return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n  }\n\n  private findMutationBatches(batchIDs: SortedSet<number>): MutationBatch[] {\n    // Construct an array of matching batches, sorted by batchID to ensure that\n    // multiple mutations affecting the same document key are applied in order.\n    const result: MutationBatch[] = [];\n    batchIDs.forEach(batchId => {\n      const batch = this.findMutationBatch(batchId);\n      if (batch !== null) {\n        result.push(batch);\n      }\n    });\n    return result;\n  }\n\n  removeMutationBatch(\n    transaction: PersistenceTransaction,\n    batch: MutationBatch\n  ): PersistencePromise<void> {\n    // Find the position of the first batch for removal.\n    const batchIndex = this.indexOfExistingBatchId(batch.batchId, 'removed');\n    hardAssert(\n      batchIndex === 0,\n      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<boolean> {\n    const ref = new DocReference(key, 0);\n    const firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\n    return PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key));\n  }\n\n  performConsistencyCheck(\n    txn: PersistenceTransaction\n  ): PersistencePromise<void> {\n    if (this.mutationQueue.length === 0) {\n      debugAssert(\n        this.batchesByDocumentKey.isEmpty(),\n        'Document leak -- detected dangling mutation references when queue is empty.'\n      );\n    }\n    return PersistencePromise.resolve();\n  }\n\n  /**\n   * Finds the index of the given batchId in the mutation queue and asserts that\n   * the resulting index is within the bounds of the queue.\n   *\n   * @param batchId - The batchId to search for\n   * @param action - A description of what the caller is doing, phrased in passive\n   * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n   */\n  private indexOfExistingBatchId(batchId: BatchId, action: string): number {\n    const index = this.indexOfBatchId(batchId);\n    debugAssert(\n      index >= 0 && index < this.mutationQueue.length,\n      'Batches must exist to be ' + action\n    );\n    return index;\n  }\n\n  /**\n   * Finds the index of the given batchId in the mutation queue. This operation\n   * is O(1).\n   *\n   * @returns The computed index of the batch with the given batchId, based on\n   * the state of the queue. Note this index can be negative if the requested\n   * batchId has already been 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 { getPipelineCollection } from '../core/pipeline';\nimport { isPipeline, QueryOrPipeline } from '../core/pipeline-util';\nimport { pipelineMatches } from '../core/pipeline_run';\nimport { 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 { ResourcePath } from '../model/path';\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<DocumentKey, MemoryRemoteDocumentCacheEntry>;\nfunction documentEntryMap(): DocumentEntryMap {\n  return new SortedMap<DocumentKey, MemoryRemoteDocumentCacheEntry>(\n    DocumentKey.comparator\n  );\n}\n\nexport interface MemoryRemoteDocumentCache extends RemoteDocumentCache {\n  forEachDocumentKey(\n    transaction: PersistenceTransaction,\n    f: (key: DocumentKey) => PersistencePromise<void>\n  ): PersistencePromise<void>;\n}\n\n/**\n * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newMemoryRemoteDocumentCache()`.\n */\nclass MemoryRemoteDocumentCacheImpl implements MemoryRemoteDocumentCache {\n  /** Underlying cache of documents and their read times. */\n  private docs = documentEntryMap();\n  private indexManager!: IndexManager;\n\n  /** Size of all cached documents. */\n  private size = 0;\n\n  /**\n   * @param sizer - Used to assess the size of a document. For eager GC, this is\n   * expected to just return 0 to avoid unnecessarily doing the work of\n   * calculating the size.\n   */\n  constructor(private readonly sizer: DocumentSizer) {}\n\n  setIndexManager(indexManager: IndexManager): void {\n    this.indexManager = indexManager;\n  }\n\n  /**\n   * Adds the supplied entry to the cache and updates the cache size as appropriate.\n   *\n   * All calls of `addEntry`  are required to go through the RemoteDocumentChangeBuffer\n   * returned by `newChangeBuffer()`.\n   */\n  addEntry(\n    transaction: PersistenceTransaction,\n    doc: MutableDocument\n  ): PersistencePromise<void> {\n    debugAssert(\n      !doc.readTime.isEqual(SnapshotVersion.min()),\n      'Cannot add a document with a read time of zero'\n    );\n\n    const key = doc.key;\n    const entry = this.docs.get(key);\n    const previousSize = entry ? entry.size : 0;\n    const currentSize = this.sizer(doc);\n\n    this.docs = this.docs.insert(key, {\n      document: doc.mutableCopy(),\n      size: currentSize\n    });\n\n    this.size += currentSize - previousSize;\n\n    return this.indexManager.addToCollectionParentIndex(\n      transaction,\n      key.path.popLast()\n    );\n  }\n\n  /**\n   * Removes the specified entry from the cache and updates the cache size as appropriate.\n   *\n   * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n   * returned by `newChangeBuffer()`.\n   */\n  removeEntry(documentKey: DocumentKey): void {\n    const entry = this.docs.get(documentKey);\n    if (entry) {\n      this.docs = this.docs.remove(documentKey);\n      this.size -= entry.size;\n    }\n  }\n\n  getEntry(\n    transaction: PersistenceTransaction,\n    documentKey: DocumentKey\n  ): PersistencePromise<MutableDocument> {\n    const entry = this.docs.get(documentKey);\n    return PersistencePromise.resolve(\n      entry\n        ? entry.document.mutableCopy()\n        : MutableDocument.newInvalidDocument(documentKey)\n    );\n  }\n\n  getEntries(\n    transaction: PersistenceTransaction,\n    documentKeys: DocumentKeySet\n  ): PersistencePromise<MutableDocumentMap> {\n    let results = mutableDocumentMap();\n    documentKeys.forEach(documentKey => {\n      const entry = this.docs.get(documentKey);\n      results = results.insert(\n        documentKey,\n        entry\n          ? entry.document.mutableCopy()\n          : MutableDocument.newInvalidDocument(documentKey)\n      );\n    });\n    return PersistencePromise.resolve(results);\n  }\n\n  getAllEntries(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<MutableDocumentMap> {\n    let results = mutableDocumentMap();\n    this.docs.forEach((k, entry) => {\n      results = results.insert(k, entry.document as MutableDocument);\n    });\n\n    return PersistencePromise.resolve(results);\n  }\n\n  getDocumentsMatchingQuery(\n    transaction: PersistenceTransaction,\n    query: QueryOrPipeline,\n    offset: IndexOffset,\n    mutatedDocs: OverlayMap\n  ): PersistencePromise<MutableDocumentMap> {\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    let collectionPath: ResourcePath;\n    let matcher: (doc: Document) => boolean;\n    if (isPipeline(query)) {\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      collectionPath = ResourcePath.fromString(getPipelineCollection(query)!);\n      matcher = (doc: Document) =>\n        pipelineMatches(query, doc as MutableDocument);\n    } else {\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      collectionPath = query.path;\n      matcher = (doc: Document) => queryMatches(query, doc);\n    }\n\n    let results = mutableDocumentMap();\n\n    // Document keys are ordered first by numeric value (\"__id<Long>__\"),\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) && !matcher(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<MutableDocumentMap> {\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<void>\n  ): PersistencePromise<void> {\n    return PersistencePromise.forEach(this.docs, (key: DocumentKey) => f(key));\n  }\n\n  newChangeBuffer(options?: {\n    trackRemovals: boolean;\n  }): RemoteDocumentChangeBuffer {\n    // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n    // a separate changelog and does not need special handling for removals.\n    return new MemoryRemoteDocumentChangeBuffer(this);\n  }\n\n  getSize(txn: PersistenceTransaction): PersistencePromise<number> {\n    return PersistencePromise.resolve(this.size);\n  }\n}\n\n/**\n * Creates a new memory-only RemoteDocumentCache.\n *\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\nexport function newMemoryRemoteDocumentCache(\n  sizer: DocumentSizer\n): MemoryRemoteDocumentCache {\n  return new MemoryRemoteDocumentCacheImpl(sizer);\n}\n\n/**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\nclass MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n  constructor(private readonly documentCache: MemoryRemoteDocumentCacheImpl) {\n    super();\n  }\n\n  protected applyChanges(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<void> {\n    const promises: Array<PersistencePromise<void>> = [];\n    this.changes.forEach((key, doc) => {\n      if (doc.isValidDocument()) {\n        promises.push(this.documentCache.addEntry(transaction, doc));\n      } else {\n        this.documentCache.removeEntry(key);\n      }\n    });\n    return PersistencePromise.waitFor(promises);\n  }\n\n  protected getFromCache(\n    transaction: PersistenceTransaction,\n    documentKey: DocumentKey\n  ): PersistencePromise<MutableDocument> {\n    return this.documentCache.getEntry(transaction, documentKey);\n  }\n\n  protected getAllFromCache(\n    transaction: PersistenceTransaction,\n    documentKeys: DocumentKeySet\n  ): PersistencePromise<MutableDocumentMap> {\n    return this.documentCache.getEntries(transaction, documentKeys);\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  canonifyTargetOrPipeline,\n  TargetOrPipeline,\n  targetOrPipelineEqual\n} from '../core/pipeline-util';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { 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<TargetOrPipeline, TargetData>(\n    t => canonifyTargetOrPipeline(t),\n    targetOrPipelineEqual\n  );\n\n  /** The last received snapshot version. */\n  private lastRemoteSnapshotVersion = SnapshotVersion.min();\n  /** The highest numbered target ID encountered. */\n  private highestTargetId: TargetId = 0;\n  /** The highest sequence number encountered. */\n  private highestSequenceNumber: ListenSequenceNumber = 0;\n  /**\n   * A ordered bidirectional mapping between documents and the remote target\n   * IDs.\n   */\n  private references = new ReferenceSet();\n\n  private targetCount = 0;\n\n  private targetIdGenerator = TargetIdGenerator.forTargetCache();\n\n  constructor(private readonly persistence: Persistence) {}\n\n  forEachTarget(\n    txn: PersistenceTransaction,\n    f: (q: TargetData) => void\n  ): PersistencePromise<void> {\n    this.targets.forEach((_, targetData) => f(targetData));\n    return PersistencePromise.resolve();\n  }\n\n  getLastRemoteSnapshotVersion(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<SnapshotVersion> {\n    return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);\n  }\n\n  getHighestSequenceNumber(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<ListenSequenceNumber> {\n    return PersistencePromise.resolve(this.highestSequenceNumber);\n  }\n\n  allocateTargetId(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<TargetId> {\n    this.highestTargetId = this.targetIdGenerator.next();\n    return PersistencePromise.resolve(this.highestTargetId);\n  }\n\n  setTargetsMetadata(\n    transaction: PersistenceTransaction,\n    highestListenSequenceNumber: number,\n    lastRemoteSnapshotVersion?: SnapshotVersion\n  ): PersistencePromise<void> {\n    if (lastRemoteSnapshotVersion) {\n      this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n    }\n    if (highestListenSequenceNumber > this.highestSequenceNumber) {\n      this.highestSequenceNumber = highestListenSequenceNumber;\n    }\n    return PersistencePromise.resolve();\n  }\n\n  private saveTargetData(targetData: TargetData): void {\n    this.targets.set(targetData.target, targetData);\n    const targetId = targetData.targetId;\n    if (targetId > this.highestTargetId) {\n      this.targetIdGenerator = new TargetIdGenerator(targetId);\n      this.highestTargetId = targetId;\n    }\n    if (targetData.sequenceNumber > this.highestSequenceNumber) {\n      this.highestSequenceNumber = targetData.sequenceNumber;\n    }\n  }\n\n  addTargetData(\n    transaction: PersistenceTransaction,\n    targetData: TargetData\n  ): PersistencePromise<void> {\n    debugAssert(\n      !this.targets.has(targetData.target),\n      'Adding a target that already exists'\n    );\n    this.saveTargetData(targetData);\n    this.targetCount += 1;\n    return PersistencePromise.resolve();\n  }\n\n  updateTargetData(\n    transaction: PersistenceTransaction,\n    targetData: TargetData\n  ): PersistencePromise<void> {\n    debugAssert(\n      this.targets.has(targetData.target),\n      'Updating a nonexistent target'\n    );\n    this.saveTargetData(targetData);\n    return PersistencePromise.resolve();\n  }\n\n  removeTargetData(\n    transaction: PersistenceTransaction,\n    targetData: TargetData\n  ): PersistencePromise<void> {\n    debugAssert(this.targetCount > 0, 'Removing a target from an empty cache');\n    debugAssert(\n      this.targets.has(targetData.target),\n      'Removing a 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<number> {\n    let count = 0;\n    const removals: Array<PersistencePromise<void>> = [];\n    this.targets.forEach((key, targetData) => {\n      if (\n        targetData.sequenceNumber <= upperBound &&\n        activeTargetIds.get(targetData.targetId) === null\n      ) {\n        this.targets.delete(key);\n        removals.push(\n          this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n        );\n        count++;\n      }\n    });\n    return PersistencePromise.waitFor(removals).next(() => count);\n  }\n\n  getTargetCount(\n    transaction: PersistenceTransaction\n  ): PersistencePromise<number> {\n    return PersistencePromise.resolve(this.targetCount);\n  }\n\n  getTargetData(\n    transaction: PersistenceTransaction,\n    target: TargetOrPipeline\n  ): PersistencePromise<TargetData | null> {\n    const targetData = this.targets.get(target) || null;\n    return PersistencePromise.resolve(targetData);\n  }\n\n  addMatchingKeys(\n    txn: PersistenceTransaction,\n    keys: DocumentKeySet,\n    targetId: TargetId\n  ): PersistencePromise<void> {\n    this.references.addReferences(keys, targetId);\n    return PersistencePromise.resolve();\n  }\n\n  removeMatchingKeys(\n    txn: PersistenceTransaction,\n    keys: DocumentKeySet,\n    targetId: TargetId\n  ): PersistencePromise<void> {\n    this.references.removeReferences(keys, targetId);\n    const referenceDelegate = this.persistence.referenceDelegate;\n    const promises: Array<PersistencePromise<void>> = [];\n    if (referenceDelegate) {\n      keys.forEach(key => {\n        promises.push(referenceDelegate.markPotentiallyOrphaned(txn, key));\n      });\n    }\n    return PersistencePromise.waitFor(promises);\n  }\n\n  removeMatchingKeysForTargetId(\n    txn: PersistenceTransaction,\n    targetId: TargetId\n  ): PersistencePromise<void> {\n    this.references.removeReferencesForId(targetId);\n    return PersistencePromise.resolve();\n  }\n\n  getMatchingKeysForTargetId(\n    txn: PersistenceTransaction,\n    targetId: TargetId\n  ): PersistencePromise<DocumentKeySet> {\n    const matchingKeys = this.references.referencesForId(targetId);\n    return PersistencePromise.resolve(matchingKeys);\n  }\n\n  containsKey(\n    txn: PersistenceTransaction,\n    key: DocumentKey\n  ): PersistencePromise<boolean> {\n    return PersistencePromise.resolve(this.references.containsKey(key));\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { estimateByteSize } from '../model/values';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { fail } from '../util/assert';\nimport { logDebug } from '../util/log';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { 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<void> {\n    return Promise.resolve();\n  }\n\n  shutdown(): Promise<void> {\n    // No durable state to ensure is closed on shutdown.\n    this._started = false;\n    return Promise.resolve();\n  }\n\n  get started(): boolean {\n    return this._started;\n  }\n\n  setDatabaseDeletedListener(): void {\n    // No op.\n  }\n\n  setNetworkEnabled(): void {\n    // No op.\n  }\n\n  getIndexManager(user: User): MemoryIndexManager {\n    // We do not currently support indices for memory persistence, so we can\n    // return the same shared instance of the memory index manager.\n    return this.indexManager;\n  }\n\n  getDocumentOverlayCache(user: User): DocumentOverlayCache {\n    let overlay = this.overlays[user.toKey()];\n    if (!overlay) {\n      overlay = new MemoryDocumentOverlayCache();\n      this.overlays[user.toKey()] = overlay;\n    }\n    return overlay;\n  }\n\n  getMutationQueue(user: User, indexManager: IndexManager): MutationQueue {\n    let queue = this.mutationQueues[user.toKey()];\n    if (!queue) {\n      queue = new MemoryMutationQueue(indexManager, this.referenceDelegate);\n      this.mutationQueues[user.toKey()] = queue;\n    }\n    return queue;\n  }\n\n  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<T>(\n    action: string,\n    mode: PersistenceTransactionMode,\n    transactionOperation: (\n      transaction: PersistenceTransaction\n    ) => PersistencePromise<T>\n  ): Promise<T> {\n    logDebug(LOG_TAG, 'Starting transaction:', action);\n    const txn = new MemoryTransaction(this.listenSequence.next());\n    this.referenceDelegate.onTransactionStarted();\n    return transactionOperation(txn)\n      .next(result => {\n        return this.referenceDelegate\n          .onTransactionCommitted(txn)\n          .next(() => result);\n      })\n      .toPromise()\n      .then(result => {\n        txn.raiseOnCommittedEvent();\n        return result;\n      });\n  }\n\n  mutationQueuesContainKey(\n    transaction: PersistenceTransaction,\n    key: DocumentKey\n  ): PersistencePromise<boolean> {\n    return PersistencePromise.or(\n      Object.values(this.mutationQueues).map(\n        queue => () => queue.containsKey(transaction, key)\n      )\n    );\n  }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */\nexport class MemoryTransaction extends PersistenceTransaction {\n  constructor(readonly currentSequenceNumber: ListenSequenceNumber) {\n    super();\n  }\n}\n\nexport interface MemoryReferenceDelegate extends ReferenceDelegate {\n  documentSize(doc: Document): number;\n  onTransactionStarted(): void;\n  onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise<void>;\n}\n\nexport class MemoryEagerDelegate implements MemoryReferenceDelegate {\n  /** Tracks all documents that are active in Query views. */\n  private localViewReferences: ReferenceSet = new ReferenceSet();\n  /** The list of documents that are potentially GCed after each transaction. */\n  private _orphanedDocuments: Set</* path= */ string> | null = null;\n\n  private constructor(private readonly persistence: MemoryPersistence) {}\n\n  static factory(persistence: MemoryPersistence): MemoryEagerDelegate {\n    return new MemoryEagerDelegate(persistence);\n  }\n\n  private get orphanedDocuments(): Set<string> {\n    if (!this._orphanedDocuments) {\n      throw fail(\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<void> {\n    this.localViewReferences.addReference(key, targetId);\n    this.orphanedDocuments.delete(key.toString());\n    return PersistencePromise.resolve();\n  }\n\n  removeReference(\n    txn: PersistenceTransaction,\n    targetId: TargetId,\n    key: DocumentKey\n  ): PersistencePromise<void> {\n    this.localViewReferences.removeReference(key, targetId);\n    this.orphanedDocuments.add(key.toString());\n    return PersistencePromise.resolve();\n  }\n\n  markPotentiallyOrphaned(\n    txn: PersistenceTransaction,\n    key: DocumentKey\n  ): PersistencePromise<void> {\n    this.orphanedDocuments.add(key.toString());\n    return PersistencePromise.resolve();\n  }\n\n  removeTarget(\n    txn: PersistenceTransaction,\n    targetData: TargetData\n  ): PersistencePromise<void> {\n    const orphaned = this.localViewReferences.removeReferencesForId(\n      targetData.targetId\n    );\n    orphaned.forEach(key => this.orphanedDocuments.add(key.toString()));\n    const cache = this.persistence.getTargetCache();\n    return cache\n      .getMatchingKeysForTargetId(txn, targetData.targetId)\n      .next(keys => {\n        keys.forEach(key => this.orphanedDocuments.add(key.toString()));\n      })\n      .next(() => cache.removeTargetData(txn, targetData));\n  }\n\n  onTransactionStarted(): void {\n    this._orphanedDocuments = new Set<string>();\n  }\n\n  onTransactionCommitted(\n    txn: PersistenceTransaction\n  ): PersistencePromise<void> {\n    // Remove newly orphaned documents.\n    const cache = this.persistence.getRemoteDocumentCache();\n    const changeBuffer = cache.newChangeBuffer();\n    return PersistencePromise.forEach(\n      this.orphanedDocuments,\n      (path: string): PersistencePromise<void> => {\n        const key = DocumentKey.fromPath(path);\n        return this.isReferenced(txn, key).next(isReferenced => {\n          if (!isReferenced) {\n            changeBuffer.removeEntry(key, SnapshotVersion.min());\n          }\n        });\n      }\n    ).next(() => {\n      this._orphanedDocuments = null;\n      return changeBuffer.apply(txn);\n    });\n  }\n\n  updateLimboDocument(\n    txn: PersistenceTransaction,\n    key: DocumentKey\n  ): PersistencePromise<void> {\n    return this.isReferenced(txn, key).next(isReferenced => {\n      if (isReferenced) {\n        this.orphanedDocuments.delete(key.toString());\n      } else {\n        this.orphanedDocuments.add(key.toString());\n      }\n    });\n  }\n\n  documentSize(doc: Document): number {\n    // For eager GC, we don't care about the document size, there are no size thresholds.\n    return 0;\n  }\n\n  private isReferenced(\n    txn: PersistenceTransaction,\n    key: DocumentKey\n  ): PersistencePromise<boolean> {\n    return PersistencePromise.or([\n      () =>\n        PersistencePromise.resolve(this.localViewReferences.containsKey(key)),\n      () => this.persistence.getTargetCache().containsKey(txn, key),\n      () => this.persistence.mutationQueuesContainKey(txn, key)\n    ]);\n  }\n}\n\nexport class MemoryLruDelegate implements ReferenceDelegate, LruDelegate {\n  private orphanedSequenceNumbers: ObjectMap<\n    DocumentKey,\n    ListenSequenceNumber\n  > = new ObjectMap(\n    k => encodeResourcePath(k.path),\n    (l, r) => l.isEqual(r)\n  );\n\n  readonly garbageCollector: LruGarbageCollector;\n\n  constructor(\n    private readonly persistence: MemoryPersistence,\n    lruParams: LruParams\n  ) {\n    this.garbageCollector = newLruGarbageCollector(this, lruParams);\n  }\n\n  static factory(\n    persistence: MemoryPersistence,\n    lruParams: LruParams\n  ): MemoryLruDelegate {\n    return new MemoryLruDelegate(persistence, lruParams);\n  }\n\n  // No-ops, present so memory persistence doesn't have to care which delegate\n  // it has.\n  onTransactionStarted(): void {}\n\n  onTransactionCommitted(\n    txn: PersistenceTransaction\n  ): PersistencePromise<void> {\n    return PersistencePromise.resolve();\n  }\n\n  forEachTarget(\n    txn: PersistenceTransaction,\n    f: (q: TargetData) => void\n  ): PersistencePromise<void> {\n    return this.persistence.getTargetCache().forEachTarget(txn, f);\n  }\n\n  getSequenceNumberCount(\n    txn: PersistenceTransaction\n  ): PersistencePromise<number> {\n    const docCountPromise = this.orphanedDocumentCount(txn);\n    const targetCountPromise = this.persistence\n      .getTargetCache()\n      .getTargetCount(txn);\n    return targetCountPromise.next(targetCount =>\n      docCountPromise.next(docCount => targetCount + docCount)\n    );\n  }\n\n  private orphanedDocumentCount(\n    txn: PersistenceTransaction\n  ): PersistencePromise<number> {\n    let orphanedCount = 0;\n    return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n      orphanedCount++;\n    }).next(() => orphanedCount);\n  }\n\n  forEachOrphanedDocumentSequenceNumber(\n    txn: PersistenceTransaction,\n    f: (sequenceNumber: ListenSequenceNumber) => void\n  ): PersistencePromise<void> {\n    return PersistencePromise.forEach(\n      this.orphanedSequenceNumbers,\n      (key, sequenceNumber) => {\n        // Pass in the exact sequence number as the upper bound so we know it won't be pinned by\n        // being too recent.\n        return this.isPinned(txn, key, sequenceNumber).next(isPinned => {\n          if (!isPinned) {\n            return f(sequenceNumber);\n          } else {\n            return PersistencePromise.resolve();\n          }\n        });\n      }\n    );\n  }\n\n  removeTargets(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber,\n    activeTargetIds: ActiveTargets\n  ): PersistencePromise<number> {\n    return this.persistence\n      .getTargetCache()\n      .removeTargets(txn, upperBound, activeTargetIds);\n  }\n\n  removeOrphanedDocuments(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber\n  ): PersistencePromise<number> {\n    let count = 0;\n    const cache = this.persistence.getRemoteDocumentCache();\n    const changeBuffer = cache.newChangeBuffer();\n    const p = cache.forEachDocumentKey(txn, key => {\n      return this.isPinned(txn, key, upperBound).next(isPinned => {\n        if (!isPinned) {\n          count++;\n          changeBuffer.removeEntry(key, SnapshotVersion.min());\n        }\n      });\n    });\n    return p.next(() => changeBuffer.apply(txn)).next(() => count);\n  }\n\n  markPotentiallyOrphaned(\n    txn: PersistenceTransaction,\n    key: DocumentKey\n  ): PersistencePromise<void> {\n    this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n    return PersistencePromise.resolve();\n  }\n\n  removeTarget(\n    txn: PersistenceTransaction,\n    targetData: TargetData\n  ): PersistencePromise<void> {\n    const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n    return this.persistence.getTargetCache().updateTargetData(txn, updated);\n  }\n\n  addReference(\n    txn: PersistenceTransaction,\n    targetId: TargetId,\n    key: DocumentKey\n  ): PersistencePromise<void> {\n    this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n    return PersistencePromise.resolve();\n  }\n\n  removeReference(\n    txn: PersistenceTransaction,\n    targetId: TargetId,\n    key: DocumentKey\n  ): PersistencePromise<void> {\n    this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n    return PersistencePromise.resolve();\n  }\n\n  updateLimboDocument(\n    txn: PersistenceTransaction,\n    key: DocumentKey\n  ): PersistencePromise<void> {\n    this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n    return PersistencePromise.resolve();\n  }\n\n  documentSize(document: Document): number {\n    let documentSize = document.key.toString().length;\n    if (document.isFoundDocument()) {\n      documentSize += estimateByteSize(document.data.value);\n    }\n    return documentSize;\n  }\n\n  private isPinned(\n    txn: PersistenceTransaction,\n    key: DocumentKey,\n    upperBound: ListenSequenceNumber\n  ): PersistencePromise<boolean> {\n    return PersistencePromise.or([\n      () => this.persistence.mutationQueuesContainKey(txn, key),\n      () => this.persistence.getTargetCache().containsKey(txn, key),\n      () => {\n        const orphanedAt = this.orphanedSequenceNumbers.get(key);\n        return PersistencePromise.resolve(\n          orphanedAt !== undefined && orphanedAt > upperBound\n        );\n      }\n    ]);\n  }\n\n  getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n    return this.persistence.getRemoteDocumentCache().getSize(txn);\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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<void> {\n    debugAssert(\n      fromVersion < toVersion &&\n        fromVersion >= 0 &&\n        toVersion <= SCHEMA_VERSION,\n      `Unexpected schema upgrade from v${fromVersion} to v${toVersion}.`\n    );\n\n    const simpleDbTransaction = new SimpleDbTransaction('createOrUpgrade', txn);\n\n    if (fromVersion < 1 && toVersion >= 1) {\n      createPrimaryClientStore(db);\n      createMutationQueue(db);\n      createQueryCache(db);\n      createLegacyRemoteDocumentCache(db);\n    }\n\n    // Migration 2 to populate the targetGlobal object no longer needed since\n    // migration 3 unconditionally clears it.\n\n    let p = PersistencePromise.resolve();\n    if (fromVersion < 3 && toVersion >= 3) {\n      // Brand new clients don't need to drop and recreate--only clients that\n      // potentially have corrupt data.\n      if (fromVersion !== 0) {\n        dropQueryCache(db);\n        createQueryCache(db);\n      }\n      p = p.next(() => writeEmptyTargetGlobalEntry(simpleDbTransaction));\n    }\n\n    if (fromVersion < 4 && toVersion >= 4) {\n      if (fromVersion !== 0) {\n        // Schema version 3 uses auto-generated keys to generate globally unique\n        // mutation batch IDs (this was previously ensured internally by the\n        // client). To migrate to the new schema, we have to read all mutations\n        // and write them back out. We preserve the existing batch IDs to guarantee\n        // consistency with other object stores. Any further mutation batch IDs will\n        // be auto-generated.\n        p = p.next(() =>\n          upgradeMutationBatchSchemaAndMigrateData(db, simpleDbTransaction)\n        );\n      }\n\n      p = p.next(() => {\n        createClientMetadataStore(db);\n      });\n    }\n\n    if (fromVersion < 5 && toVersion >= 5) {\n      p = p.next(() => this.removeAcknowledgedMutations(simpleDbTransaction));\n    }\n\n    if (fromVersion < 6 && toVersion >= 6) {\n      p = p.next(() => {\n        createDocumentGlobalStore(db);\n        return this.addDocumentGlobal(simpleDbTransaction);\n      });\n    }\n\n    if (fromVersion < 7 && toVersion >= 7) {\n      p = p.next(() => this.ensureSequenceNumbers(simpleDbTransaction));\n    }\n\n    if (fromVersion < 8 && toVersion >= 8) {\n      p = p.next(() =>\n        this.createCollectionParentIndex(db, simpleDbTransaction)\n      );\n    }\n\n    if (fromVersion < 9 && toVersion >= 9) {\n      p = p.next(() => {\n        // Multi-Tab used to manage its own changelog, but this has been moved\n        // to the DbRemoteDocument object store itself. Since the previous change\n        // log only contained transient data, we can drop its object store.\n        dropRemoteDocumentChangesStore(db);\n\n        // Note: Schema version 9 used to create a read time index for the\n        // RemoteDocumentCache. This is now done with schema version 13.\n      });\n    }\n\n    if (fromVersion < 10 && toVersion >= 10) {\n      p = p.next(() => this.rewriteCanonicalIds(simpleDbTransaction));\n    }\n\n    if (fromVersion < 11 && toVersion >= 11) {\n      p = p.next(() => {\n        createBundlesStore(db);\n        createNamedQueriesStore(db);\n      });\n    }\n\n    if (fromVersion < 12 && toVersion >= 12) {\n      p = p.next(() => {\n        createDocumentOverlayStore(db);\n      });\n    }\n\n    if (fromVersion < 13 && toVersion >= 13) {\n      p = p\n        .next(() => createRemoteDocumentCache(db))\n        .next(() => this.rewriteRemoteDocumentCache(db, simpleDbTransaction))\n        .next(() => db.deleteObjectStore(DbRemoteDocumentStoreLegacy));\n    }\n\n    if (fromVersion < 14 && toVersion >= 14) {\n      p = p.next(() => this.runOverlayMigration(db, simpleDbTransaction));\n    }\n\n    if (fromVersion < 15 && toVersion >= 15) {\n      p = p.next(() => createFieldIndex(db));\n    }\n\n    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<void> {\n    let byteSize = 0;\n    return txn\n      .store<DbRemoteDocumentKeyLegacy, DbRemoteDocumentLegacy>(\n        DbRemoteDocumentStoreLegacy\n      )\n      .iterate((_, doc) => {\n        byteSize += dbDocumentSize(doc);\n      })\n      .next(() => {\n        const metadata: DbRemoteDocumentGlobal = { byteSize };\n        return txn\n          .store<DbRemoteDocumentGlobalKey, DbRemoteDocumentGlobal>(\n            DbRemoteDocumentGlobalStore\n          )\n          .put(DbRemoteDocumentGlobalKey, metadata);\n      });\n  }\n\n  private removeAcknowledgedMutations(\n    txn: SimpleDbTransaction\n  ): PersistencePromise<void> {\n    const queuesStore = txn.store<DbMutationQueueKey, DbMutationQueue>(\n      DbMutationQueueStore\n    );\n    const mutationsStore = txn.store<DbMutationBatchKey, DbMutationBatch>(\n      DbMutationBatchStore\n    );\n\n    return queuesStore.loadAll().next(queues => {\n      return PersistencePromise.forEach(queues, (queue: DbMutationQueue) => {\n        const range = IDBKeyRange.bound(\n          [queue.userId, BATCHID_UNKNOWN],\n          [queue.userId, queue.lastAcknowledgedBatchId]\n        );\n\n        return mutationsStore\n          .loadAll(DbMutationBatchUserMutationsIndex, range)\n          .next(dbBatches => {\n            return PersistencePromise.forEach(\n              dbBatches,\n              (dbBatch: DbMutationBatch) => {\n                hardAssert(\n                  dbBatch.userId === queue.userId,\n                  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<void> {\n    const documentTargetStore = txn.store<\n      DbTargetDocumentKey,\n      DbTargetDocument\n    >(DbTargetDocumentStore);\n    const documentsStore = txn.store<\n      DbRemoteDocumentKeyLegacy,\n      DbRemoteDocumentKeyLegacy\n    >(DbRemoteDocumentStoreLegacy);\n    const globalTargetStore = txn.store<DbTargetGlobalKey, DbTargetGlobal>(\n      DbTargetGlobalStore\n    );\n\n    return globalTargetStore.get(DbTargetGlobalKey).next(metadata => {\n      debugAssert(\n        !!metadata,\n        'Metadata should have been written during the version 3 migration'\n      );\n      const writeSentinelKey = (\n        path: ResourcePath\n      ): PersistencePromise<void> => {\n        return documentTargetStore.put({\n          targetId: 0,\n          path: encodeResourcePath(path),\n          sequenceNumber: metadata!.highestListenSequenceNumber!\n        });\n      };\n\n      const promises: Array<PersistencePromise<void>> = [];\n      return documentsStore\n        .iterate((key, doc) => {\n          const path = new ResourcePath(key);\n          const docSentinelKey = sentinelKey(path);\n          promises.push(\n            documentTargetStore.get(docSentinelKey).next(maybeSentinel => {\n              if (!maybeSentinel) {\n                return writeSentinelKey(path);\n              } else {\n                return PersistencePromise.resolve();\n              }\n            })\n          );\n        })\n        .next(() => PersistencePromise.waitFor(promises));\n    });\n  }\n\n  private createCollectionParentIndex(\n    db: IDBDatabase,\n    txn: SimpleDbTransaction\n  ): PersistencePromise<void> {\n    // Create the index.\n    db.createObjectStore(DbCollectionParentStore, {\n      keyPath: DbCollectionParentKeyPath\n    });\n\n    const collectionParentsStore = txn.store<\n      DbCollectionParentKey,\n      DbCollectionParent\n    >(DbCollectionParentStore);\n\n    // Helper to add an index entry iff we haven't already written it.\n    const cache = new MemoryCollectionParentIndex();\n    const addEntry = (\n      collectionPath: ResourcePath\n    ): PersistencePromise<void> | undefined => {\n      if (cache.add(collectionPath)) {\n        const collectionId = collectionPath.lastSegment();\n        const parentPath = collectionPath.popLast();\n        return collectionParentsStore.put({\n          collectionId,\n          parent: encodeResourcePath(parentPath)\n        });\n      }\n    };\n\n    // Index existing remote documents.\n    return txn\n      .store<DbRemoteDocumentKeyLegacy, DbRemoteDocumentLegacy>(\n        DbRemoteDocumentStoreLegacy\n      )\n      .iterate({ keysOnly: true }, (pathSegments, _) => {\n        const path = new ResourcePath(pathSegments);\n        return addEntry(path.popLast());\n      })\n      .next(() => {\n        // Index existing mutations.\n        return txn\n          .store<DbDocumentMutationKey, DbDocumentMutation>(\n            DbDocumentMutationStore\n          )\n          .iterate({ keysOnly: true }, ([userID, encodedPath, batchId], _) => {\n            const path = decodeResourcePath(encodedPath);\n            return addEntry(path.popLast());\n          });\n      });\n  }\n\n  private rewriteCanonicalIds(\n    txn: SimpleDbTransaction\n  ): PersistencePromise<void> {\n    const targetStore = txn.store<DbTargetKey, DbTarget>(DbTargetStore);\n    return targetStore.iterate((key, originalDbTarget) => {\n      const originalTargetData = fromDbTarget(\n        this.serializer,\n        originalDbTarget\n      );\n      const updatedDbTarget = toDbTarget(this.serializer, originalTargetData);\n      return targetStore.put(updatedDbTarget);\n    });\n  }\n\n  private rewriteRemoteDocumentCache(\n    db: IDBDatabase,\n    transaction: SimpleDbTransaction\n  ): PersistencePromise<void> {\n    const legacyRemoteDocumentStore = transaction.store<\n      DbRemoteDocumentKeyLegacy,\n      DbRemoteDocumentLegacy\n    >(DbRemoteDocumentStoreLegacy);\n\n    const writes: Array<PersistencePromise<void>> = [];\n    return legacyRemoteDocumentStore\n      .iterate((_, legacyDocument) => {\n        const remoteDocumentStore = transaction.store<\n          DbRemoteDocumentKey,\n          DbRemoteDocument\n        >(DbRemoteDocumentStore);\n\n        const path = extractKey(legacyDocument).path.toArray();\n        const dbRemoteDocument = {\n          prefixPath: path.slice(0, path.length - 2),\n          collectionGroup: path[path.length - 2],\n          documentId: path[path.length - 1],\n          readTime: legacyDocument.readTime || [0, 0],\n          unknownDocument: legacyDocument.unknownDocument,\n          noDocument: legacyDocument.noDocument,\n          document: legacyDocument.document,\n          hasCommittedMutations: !!legacyDocument.hasCommittedMutations\n        };\n        writes.push(remoteDocumentStore.put(dbRemoteDocument));\n      })\n      .next(() => PersistencePromise.waitFor(writes));\n  }\n\n  private runOverlayMigration(\n    db: IDBDatabase,\n    transaction: SimpleDbTransaction\n  ): PersistencePromise<void> {\n    const mutationsStore = transaction.store<\n      DbMutationBatchKey,\n      DbMutationBatch\n    >(DbMutationBatchStore);\n\n    const remoteDocumentCache = newIndexedDbRemoteDocumentCache(\n      this.serializer\n    );\n    const memoryPersistence = new MemoryPersistence(\n      MemoryEagerDelegate.factory,\n      this.serializer.remoteSerializer\n    );\n\n    return mutationsStore.loadAll().next(dbBatches => {\n      const userToDocumentSet = new Map<string, DocumentKeySet>();\n      dbBatches.forEach(dbBatch => {\n        let documentSet =\n          userToDocumentSet.get(dbBatch.userId) ?? documentKeySet();\n        const batch = fromDbMutationBatch(this.serializer, dbBatch);\n        batch.keys().forEach(key => (documentSet = documentSet.add(key)));\n        userToDocumentSet.set(dbBatch.userId, documentSet);\n      });\n      return PersistencePromise.forEach(\n        userToDocumentSet,\n        (allDocumentKeysForUser, userId) => {\n          const user = new User(userId);\n          const documentOverlayCache = IndexedDbDocumentOverlayCache.forUser(\n            this.serializer,\n            user\n          );\n          // NOTE: The index manager and the reference delegate are\n          // irrelevant for the purpose of recalculating and saving\n          // overlays. We can therefore simply use the memory\n          // implementation.\n          const indexManager = memoryPersistence.getIndexManager(user);\n          const mutationQueue = IndexedDbMutationQueue.forUser(\n            user,\n            this.serializer,\n            indexManager,\n            memoryPersistence.referenceDelegate\n          );\n          const localDocumentsView = new LocalDocumentsView(\n            remoteDocumentCache,\n            mutationQueue,\n            documentOverlayCache,\n            indexManager\n          );\n          return localDocumentsView\n            .recalculateAndSaveOverlaysForDocumentKeys(\n              new IndexedDbTransaction(transaction, ListenSequence.INVALID),\n              allDocumentKeysForUser\n            )\n            .next();\n        }\n      );\n    });\n  }\n}\n\nfunction sentinelKey(path: ResourcePath): DbTargetDocumentKey {\n  return [0, encodeResourcePath(path)];\n}\n\nfunction createPrimaryClientStore(db: IDBDatabase): void {\n  db.createObjectStore(DbPrimaryClientStore);\n}\n\nfunction createMutationQueue(db: IDBDatabase): void {\n  db.createObjectStore(DbMutationQueueStore, {\n    keyPath: DbMutationQueueKeyPath\n  });\n\n  const mutationBatchesStore = db.createObjectStore(DbMutationBatchStore, {\n    keyPath: DbMutationBatchKeyPath,\n    autoIncrement: true\n  });\n  mutationBatchesStore.createIndex(\n    DbMutationBatchUserMutationsIndex,\n    DbMutationBatchUserMutationsKeyPath,\n    { unique: true }\n  );\n\n  db.createObjectStore(DbDocumentMutationStore);\n}\n\n/**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */\nfunction upgradeMutationBatchSchemaAndMigrateData(\n  db: IDBDatabase,\n  txn: SimpleDbTransaction\n): PersistencePromise<void> {\n  const v1MutationsStore = txn.store<[string, number], DbMutationBatch>(\n    DbMutationBatchStore\n  );\n  return v1MutationsStore.loadAll().next(existingMutations => {\n    db.deleteObjectStore(DbMutationBatchStore);\n\n    const mutationsStore = db.createObjectStore(DbMutationBatchStore, {\n      keyPath: DbMutationBatchKeyPath,\n      autoIncrement: true\n    });\n    mutationsStore.createIndex(\n      DbMutationBatchUserMutationsIndex,\n      DbMutationBatchUserMutationsKeyPath,\n      { unique: true }\n    );\n\n    const v3MutationsStore = txn.store<DbMutationBatchKey, DbMutationBatch>(\n      DbMutationBatchStore\n    );\n    const writeAll = existingMutations.map(mutation =>\n      v3MutationsStore.put(mutation)\n    );\n\n    return PersistencePromise.waitFor(writeAll);\n  });\n}\n\nfunction createLegacyRemoteDocumentCache(db: IDBDatabase): void {\n  db.createObjectStore(DbRemoteDocumentStoreLegacy);\n}\n\nfunction createRemoteDocumentCache(db: IDBDatabase): void {\n  const remoteDocumentStore = db.createObjectStore(DbRemoteDocumentStore, {\n    keyPath: DbRemoteDocumentKeyPath\n  });\n  remoteDocumentStore.createIndex(\n    DbRemoteDocumentDocumentKeyIndex,\n    DbRemoteDocumentDocumentKeyIndexPath\n  );\n  remoteDocumentStore.createIndex(\n    DbRemoteDocumentCollectionGroupIndex,\n    DbRemoteDocumentCollectionGroupIndexPath\n  );\n}\n\nfunction createDocumentGlobalStore(db: IDBDatabase): void {\n  db.createObjectStore(DbRemoteDocumentGlobalStore);\n}\n\nfunction createQueryCache(db: IDBDatabase): void {\n  const targetDocumentsStore = db.createObjectStore(DbTargetDocumentStore, {\n    keyPath: DbTargetDocumentKeyPath\n  });\n  targetDocumentsStore.createIndex(\n    DbTargetDocumentDocumentTargetsIndex,\n    DbTargetDocumentDocumentTargetsKeyPath,\n    { unique: true }\n  );\n\n  const targetStore = db.createObjectStore(DbTargetStore, {\n    keyPath: DbTargetKeyPath\n  });\n\n  // NOTE: This is unique only because the TargetId is the suffix.\n  targetStore.createIndex(\n    DbTargetQueryTargetsIndexName,\n    DbTargetQueryTargetsKeyPath,\n    { unique: true }\n  );\n  db.createObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropQueryCache(db: IDBDatabase): void {\n  db.deleteObjectStore(DbTargetDocumentStore);\n  db.deleteObjectStore(DbTargetStore);\n  db.deleteObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropRemoteDocumentChangesStore(db: IDBDatabase): void {\n  if (db.objectStoreNames.contains('remoteDocumentChanges')) {\n    db.deleteObjectStore('remoteDocumentChanges');\n  }\n}\n\n/**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\nfunction writeEmptyTargetGlobalEntry(\n  txn: SimpleDbTransaction\n): PersistencePromise<void> {\n  const globalStore = txn.store<DbTargetGlobalKey, DbTargetGlobal>(\n    DbTargetGlobalStore\n  );\n  const metadata: DbTargetGlobal = {\n    highestTargetId: 0,\n    highestListenSequenceNumber: 0,\n    lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),\n    targetCount: 0\n  };\n  return globalStore.put(DbTargetGlobalKey, metadata);\n}\n\nfunction createClientMetadataStore(db: IDBDatabase): void {\n  db.createObjectStore(DbClientMetadataStore, {\n    keyPath: DbClientMetadataKeyPath\n  });\n}\n\nfunction createBundlesStore(db: IDBDatabase): void {\n  db.createObjectStore(DbBundleStore, {\n    keyPath: DbBundleKeyPath\n  });\n}\n\nfunction createNamedQueriesStore(db: IDBDatabase): void {\n  db.createObjectStore(DbNamedQueryStore, {\n    keyPath: DbNamedQueryKeyPath\n  });\n}\n\nfunction createFieldIndex(db: IDBDatabase): void {\n  const indexConfigurationStore = db.createObjectStore(\n    DbIndexConfigurationStore,\n    {\n      keyPath: DbIndexConfigurationKeyPath,\n      autoIncrement: true\n    }\n  );\n  indexConfigurationStore.createIndex(\n    DbIndexConfigurationCollectionGroupIndex,\n    DbIndexConfigurationCollectionGroupIndexPath,\n    { unique: false }\n  );\n\n  const indexStateStore = db.createObjectStore(DbIndexStateStore, {\n    keyPath: DbIndexStateKeyPath\n  });\n  indexStateStore.createIndex(\n    DbIndexStateSequenceNumberIndex,\n    DbIndexStateSequenceNumberIndexPath,\n    { unique: false }\n  );\n\n  const indexEntryStore = db.createObjectStore(DbIndexEntryStore, {\n    keyPath: DbIndexEntryKeyPath\n  });\n  indexEntryStore.createIndex(\n    DbIndexEntryDocumentKeyIndex,\n    DbIndexEntryDocumentKeyIndexPath,\n    { unique: false }\n  );\n}\n\nfunction createDocumentOverlayStore(db: IDBDatabase): void {\n  const documentOverlayStore = db.createObjectStore(DbDocumentOverlayStore, {\n    keyPath: DbDocumentOverlayKeyPath\n  });\n  documentOverlayStore.createIndex(\n    DbDocumentOverlayCollectionPathOverlayIndex,\n    DbDocumentOverlayCollectionPathOverlayIndexPath,\n    { unique: false }\n  );\n  documentOverlayStore.createIndex(\n    DbDocumentOverlayCollectionGroupOverlayIndex,\n    DbDocumentOverlayCollectionGroupOverlayIndexPath,\n    { unique: false }\n  );\n}\n\nfunction 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_<persistence_prefix>_<instance_key>\nconst ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie';\n\n/**\n * The name of the main (and currently only) IndexedDB database. This name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\nexport const MAIN_DATABASE = 'main';\n\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the \"primary client\". An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * 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<void> | null = null;\n\n  /** The last time we garbage collected the client metadata object store. */\n  private lastGarbageCollectionTime = Number.NEGATIVE_INFINITY;\n\n  /** A listener to notify on primary state changes. */\n  private primaryStateListener: PrimaryStateListener = _ => Promise.resolve();\n\n  private readonly 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<void> {\n    debugAssert(!this.started, 'IndexedDbPersistence double-started!');\n    debugAssert(this.window !== null, \"Expected 'window' to be defined\");\n\n    // NOTE: This is expected to fail sometimes (in the case of another tab\n    // already having the persistence lock), so it's the first thing we should\n    // do.\n    return this.updateClientMetadataAndTryBecomePrimary()\n      .then(() => {\n        if (!this.isPrimary && !this.allowTabSynchronization) {\n          // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n          // obtain the primary lease.\n          throw new FirestoreError(\n            Code.FAILED_PRECONDITION,\n            PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n          );\n        }\n        this.attachVisibilityHandler();\n        this.attachWindowUnloadHook();\n\n        this.scheduleClientMetadataAndPrimaryLeaseRefreshes();\n\n        return this.runTransaction(\n          'getHighestListenSequenceNumber',\n          'readonly',\n          txn => this.targetCache.getHighestSequenceNumber(txn)\n        );\n      })\n      .then(highestListenSequenceNumber => {\n        this.listenSequence = new ListenSequence(\n          highestListenSequenceNumber,\n          this.sequenceNumberSyncer\n        );\n      })\n      .then(() => {\n        this._started = true;\n      })\n      .catch(reason => {\n        this.simpleDb && this.simpleDb.close();\n        return Promise.reject(reason);\n      });\n  }\n\n  /**\n   * Registers a listener that gets called when the primary state of the\n   * instance changes. Upon registering, this listener is invoked immediately\n   * with the current primary state.\n   *\n   * PORTING NOTE: This is only used for Web multi-tab.\n   */\n  setPrimaryStateListener(\n    primaryStateListener: PrimaryStateListener\n  ): Promise<void> {\n    this.primaryStateListener = async primaryState => {\n      if (this.started) {\n        return primaryStateListener(primaryState);\n      }\n    };\n    return primaryStateListener(this.isPrimary);\n  }\n\n  /**\n   * Registers a listener that gets called when the database receives a\n   * version change event indicating that it has deleted.\n   *\n   * PORTING NOTE: This is only used for Web multi-tab.\n   */\n  setDatabaseDeletedListener(\n    databaseDeletedListener: () => Promise<void>\n  ): void {\n    this.simpleDb.setVersionChangeListener(async event => {\n      // Check if an attempt is made to delete IndexedDB.\n      if (event.newVersion === null) {\n        await databaseDeletedListener();\n      }\n    });\n  }\n\n  /**\n   * Adjusts the current network state in the client's metadata, potentially\n   * affecting the primary lease.\n   *\n   * PORTING NOTE: This is only used for Web multi-tab.\n   */\n  setNetworkEnabled(networkEnabled: boolean): void {\n    if (this.networkEnabled !== networkEnabled) {\n      this.networkEnabled = networkEnabled;\n      // Schedule a primary lease refresh for immediate execution. The eventual\n      // lease update will be propagated via `primaryStateListener`.\n      this.queue.enqueueAndForget(async () => {\n        if (this.started) {\n          await this.updateClientMetadataAndTryBecomePrimary();\n        }\n      });\n    }\n  }\n\n  /**\n   * Updates the client metadata in IndexedDb and attempts to either obtain or\n   * extend the primary lease for the local client. Asynchronously notifies the\n   * primary state listener if the client either newly obtained or released its\n   * primary lease.\n   */\n  private updateClientMetadataAndTryBecomePrimary(): Promise<void> {\n    return this.runTransaction(\n      'updateClientMetadataAndTryBecomePrimary',\n      'readwrite',\n      txn => {\n        const metadataStore = clientMetadataStore(txn);\n        return metadataStore\n          .put({\n            clientId: this.clientId,\n            updateTimeMs: Date.now(),\n            networkEnabled: this.networkEnabled,\n            inForeground: this.inForeground\n          })\n          .next(() => {\n            if (this.isPrimary) {\n              return this.verifyPrimaryLease(txn).next(success => {\n                if (!success) {\n                  this.isPrimary = false;\n                  this.queue.enqueueRetryable(() =>\n                    this.primaryStateListener(false)\n                  );\n                }\n              });\n            }\n          })\n          .next(() => this.canActAsPrimary(txn))\n          .next(canActAsPrimary => {\n            if (this.isPrimary && !canActAsPrimary) {\n              return this.releasePrimaryLeaseIfHeld(txn).next(() => false);\n            } else if (canActAsPrimary) {\n              return this.acquireOrExtendPrimaryLease(txn).next(() => true);\n            } else {\n              return /* canActAsPrimary= */ false;\n            }\n          });\n      }\n    )\n      .catch(e => {\n        if (isIndexedDbTransactionError(e)) {\n          logDebug(LOG_TAG, 'Failed to extend owner lease: ', e);\n          // Proceed with the existing state. Any subsequent access to\n          // IndexedDB will verify the lease.\n          return this.isPrimary;\n        }\n\n        if (!this.allowTabSynchronization) {\n          throw e;\n        }\n\n        logDebug(\n          LOG_TAG,\n          'Releasing owner lease after error during lease refresh',\n          e\n        );\n        return /* isPrimary= */ false;\n      })\n      .then(isPrimary => {\n        if (this.isPrimary !== isPrimary) {\n          this.queue.enqueueRetryable(() =>\n            this.primaryStateListener(isPrimary)\n          );\n        }\n        this.isPrimary = isPrimary;\n      });\n  }\n\n  private verifyPrimaryLease(\n    txn: PersistenceTransaction\n  ): PersistencePromise<boolean> {\n    const store = primaryClientStore(txn);\n    return store.get(DbPrimaryClientKey).next(primaryClient => {\n      return PersistencePromise.resolve(this.isLocalClient(primaryClient));\n    });\n  }\n\n  private removeClientMetadata(\n    txn: PersistenceTransaction\n  ): PersistencePromise<void> {\n    const metadataStore = clientMetadataStore(txn);\n    return metadataStore.delete(this.clientId);\n  }\n\n  /**\n   * If the garbage collection threshold has passed, prunes the\n   * RemoteDocumentChanges and the ClientMetadata store based on the last update\n   * time of all clients.\n   */\n  private async maybeGarbageCollectMultiClientState(): Promise<void> {\n    if (\n      this.isPrimary &&\n      !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS)\n    ) {\n      this.lastGarbageCollectionTime = Date.now();\n\n      const inactiveClients = await this.runTransaction(\n        'maybeGarbageCollectMultiClientState',\n        'readwrite-primary',\n        txn => {\n          const metadataStore = getStore<DbClientMetadataKey, DbClientMetadata>(\n            txn,\n            DbClientMetadataStore\n          );\n\n          return metadataStore.loadAll().next(existingClients => {\n            const active = this.filterActiveClients(\n              existingClients,\n              MAX_CLIENT_AGE_MS\n            );\n            const inactive = existingClients.filter(\n              client => active.indexOf(client) === -1\n            );\n\n            // Delete metadata for clients that are no longer considered active.\n            return PersistencePromise.forEach(\n              inactive,\n              (inactiveClient: DbClientMetadata) =>\n                metadataStore.delete(inactiveClient.clientId)\n            ).next(() => inactive);\n          });\n        }\n      ).catch(() => {\n        // Ignore primary lease violations or any other type of error. The next\n        // primary will run `maybeGarbageCollectMultiClientState()` again.\n        // We don't use `ignoreIfPrimaryLeaseLoss()` since we don't want to depend\n        // on LocalStore.\n        return [];\n      });\n\n      // Delete potential leftover entries that may continue to mark the\n      // inactive clients as zombied in LocalStorage.\n      // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n      // the client atomically, but we can't. So we opt to delete the IndexedDb\n      // entries first to avoid potentially reviving a zombied client.\n      if (this.webStorage) {\n        for (const inactiveClient of inactiveClients) {\n          this.webStorage.removeItem(\n            this.zombiedClientLocalStorageKey(inactiveClient.clientId)\n          );\n        }\n      }\n    }\n  }\n\n  /**\n   * Schedules a recurring timer to update the client metadata and to either\n   * extend or acquire the primary lease if the client is eligible.\n   */\n  private scheduleClientMetadataAndPrimaryLeaseRefreshes(): void {\n    this.clientMetadataRefresher = this.queue.enqueueAfterDelay(\n      TimerId.ClientMetadataRefresh,\n      CLIENT_METADATA_REFRESH_INTERVAL_MS,\n      () => {\n        return this.updateClientMetadataAndTryBecomePrimary()\n          .then(() => this.maybeGarbageCollectMultiClientState())\n          .then(() => this.scheduleClientMetadataAndPrimaryLeaseRefreshes());\n      }\n    );\n  }\n\n  /** Checks whether `client` is the local client. */\n  private isLocalClient(client: DbPrimaryClient | null): boolean {\n    return client ? client.ownerId === this.clientId : false;\n  }\n\n  /**\n   * Evaluate the state of all active clients and determine whether the local\n   * client is or can act as the holder of the primary lease. Returns whether\n   * the client is eligible for the lease, but does not actually acquire it.\n   * May return 'false' even if there is no active leaseholder and another\n   * (foreground) client should become leaseholder instead.\n   */\n  private canActAsPrimary(\n    txn: PersistenceTransaction\n  ): PersistencePromise<boolean> {\n    if (this.forceOwningTab) {\n      return PersistencePromise.resolve<boolean>(true);\n    }\n    const store = primaryClientStore(txn);\n    return store\n      .get(DbPrimaryClientKey)\n      .next(currentPrimary => {\n        const currentLeaseIsValid =\n          currentPrimary !== null &&\n          this.isWithinAge(\n            currentPrimary.leaseTimestampMs,\n            MAX_PRIMARY_ELIGIBLE_AGE_MS\n          ) &&\n          !this.isClientZombied(currentPrimary.ownerId);\n\n        // A client is eligible for the primary lease if:\n        // - its network is enabled and the client's tab is in the foreground.\n        // - its network is enabled and no other client's tab is in the\n        //   foreground.\n        // - every clients network is disabled and the client's tab is in the\n        //   foreground.\n        // - every clients network is disabled and no other client's tab is in\n        //   the foreground.\n        // - the `forceOwningTab` setting was passed in.\n        if (currentLeaseIsValid) {\n          if (this.isLocalClient(currentPrimary) && this.networkEnabled) {\n            return true;\n          }\n\n          if (!this.isLocalClient(currentPrimary)) {\n            if (!currentPrimary!.allowTabSynchronization) {\n              // Fail the `canActAsPrimary` check if the current leaseholder has\n              // not opted into multi-tab synchronization. If this happens at\n              // client startup, we reject the Promise returned by\n              // `enablePersistence()` and the user can continue to use Firestore\n              // with in-memory persistence.\n              // If this fails during a lease refresh, we will instead block the\n              // AsyncQueue from executing further operations. Note that this is\n              // acceptable since mixing & matching different `synchronizeTabs`\n              // settings is not supported.\n              //\n              // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n              // no longer be turned off.\n              throw new FirestoreError(\n                Code.FAILED_PRECONDITION,\n                PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n              );\n            }\n\n            return false;\n          }\n        }\n\n        if (this.networkEnabled && this.inForeground) {\n          return true;\n        }\n\n        return clientMetadataStore(txn)\n          .loadAll()\n          .next(existingClients => {\n            // Process all existing clients and determine whether at least one of\n            // them is better suited to obtain the primary lease.\n            const preferredCandidate = this.filterActiveClients(\n              existingClients,\n              MAX_PRIMARY_ELIGIBLE_AGE_MS\n            ).find(otherClient => {\n              if (this.clientId !== otherClient.clientId) {\n                const otherClientHasBetterNetworkState =\n                  !this.networkEnabled && otherClient.networkEnabled;\n                const otherClientHasBetterVisibility =\n                  !this.inForeground && otherClient.inForeground;\n                const otherClientHasSameNetworkState =\n                  this.networkEnabled === otherClient.networkEnabled;\n                if (\n                  otherClientHasBetterNetworkState ||\n                  (otherClientHasBetterVisibility &&\n                    otherClientHasSameNetworkState)\n                ) {\n                  return true;\n                }\n              }\n              return false;\n            });\n            return preferredCandidate === undefined;\n          });\n      })\n      .next(canActAsPrimary => {\n        if (this.isPrimary !== canActAsPrimary) {\n          logDebug(\n            LOG_TAG,\n            `Client ${\n              canActAsPrimary ? 'is' : 'is not'\n            } eligible for a primary lease.`\n          );\n        }\n        return canActAsPrimary;\n      });\n  }\n\n  async shutdown(): Promise<void> {\n    // The shutdown() operations are idempotent and can be called even when\n    // start() aborted (e.g. because it couldn't acquire the persistence lease).\n    this._started = false;\n\n    this.markClientZombied();\n    if (this.clientMetadataRefresher) {\n      this.clientMetadataRefresher.cancel();\n      this.clientMetadataRefresher = null;\n    }\n    this.detachVisibilityHandler();\n    this.detachWindowUnloadHook();\n\n    // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n    // has obtained the primary lease.\n    await this.simpleDb.runTransaction(\n      'shutdown',\n      'readwrite',\n      [DbPrimaryClientStore, DbClientMetadataStore],\n      simpleDbTxn => {\n        const persistenceTransaction = new IndexedDbTransaction(\n          simpleDbTxn,\n          ListenSequence.INVALID\n        );\n        return this.releasePrimaryLeaseIfHeld(persistenceTransaction).next(() =>\n          this.removeClientMetadata(persistenceTransaction)\n        );\n      }\n    );\n    this.simpleDb.close();\n\n    // Remove the entry marking the client as zombied from LocalStorage since\n    // we successfully deleted its metadata from IndexedDb.\n    this.removeClientZombiedEntry();\n  }\n\n  /**\n   * Returns clients that are not zombied and have an updateTime within the\n   * provided threshold.\n   */\n  private filterActiveClients(\n    clients: DbClientMetadata[],\n    activityThresholdMs: number\n  ): DbClientMetadata[] {\n    return clients.filter(\n      client =>\n        this.isWithinAge(client.updateTimeMs, activityThresholdMs) &&\n        !this.isClientZombied(client.clientId)\n    );\n  }\n\n  /**\n   * Returns the IDs of the clients that are currently active. If multi-tab\n   * is not supported, returns an array that only contains the local client's\n   * ID.\n   *\n   * PORTING NOTE: This is only used for Web multi-tab.\n   */\n  getActiveClients(): Promise<ClientId[]> {\n    return this.runTransaction('getActiveClients', 'readonly', txn => {\n      return clientMetadataStore(txn)\n        .loadAll()\n        .next(clients =>\n          this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(\n            clientMetadata => clientMetadata.clientId\n          )\n        );\n    });\n  }\n\n  get started(): boolean {\n    return this._started;\n  }\n\n  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<T>(\n    action: string,\n    mode: PersistenceTransactionMode,\n    transactionOperation: (\n      transaction: PersistenceTransaction\n    ) => PersistencePromise<T>\n  ): Promise<T> {\n    logDebug(LOG_TAG, 'Starting transaction:', action);\n\n    const simpleDbMode = mode === 'readonly' ? 'readonly' : 'readwrite';\n    const objectStores = getObjectStores(this.schemaVersion);\n\n    let persistenceTransaction: PersistenceTransaction;\n\n    // Do all transactions as readwrite against all object stores, since we\n    // are the only reader/writer.\n    return this.simpleDb\n      .runTransaction(action, simpleDbMode, objectStores, simpleDbTxn => {\n        persistenceTransaction = new IndexedDbTransaction(\n          simpleDbTxn,\n          this.listenSequence\n            ? this.listenSequence.next()\n            : ListenSequence.INVALID\n        );\n\n        if (mode === 'readwrite-primary') {\n          // While we merely verify that we have (or can acquire) the lease\n          // immediately, we wait to extend the primary lease until after\n          // executing transactionOperation(). This ensures that even if the\n          // transactionOperation takes a long time, we'll use a recent\n          // leaseTimestampMs in the extended (or newly acquired) lease.\n          return this.verifyPrimaryLease(persistenceTransaction)\n            .next(holdsPrimaryLease => {\n              if (holdsPrimaryLease) {\n                return /* holdsPrimaryLease= */ true;\n              }\n              return this.canActAsPrimary(persistenceTransaction);\n            })\n            .next(holdsPrimaryLease => {\n              if (!holdsPrimaryLease) {\n                logError(\n                  `Failed to obtain primary lease for action '${action}'.`\n                );\n                this.isPrimary = false;\n                this.queue.enqueueRetryable(() =>\n                  this.primaryStateListener(false)\n                );\n                throw new FirestoreError(\n                  Code.FAILED_PRECONDITION,\n                  PRIMARY_LEASE_LOST_ERROR_MSG\n                );\n              }\n              return transactionOperation(persistenceTransaction);\n            })\n            .next(result => {\n              return this.acquireOrExtendPrimaryLease(\n                persistenceTransaction\n              ).next(() => result);\n            });\n        } else {\n          return this.verifyAllowTabSynchronization(\n            persistenceTransaction\n          ).next(() => transactionOperation(persistenceTransaction));\n        }\n      })\n      .then(result => {\n        persistenceTransaction.raiseOnCommittedEvent();\n        return result;\n      });\n  }\n\n  /**\n   * Verifies that the current tab is the primary leaseholder or alternatively\n   * that the leaseholder has opted into multi-tab synchronization.\n   */\n  // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n  // be turned off.\n  private verifyAllowTabSynchronization(\n    txn: PersistenceTransaction\n  ): PersistencePromise<void> {\n    const store = primaryClientStore(txn);\n    return store.get(DbPrimaryClientKey).next(currentPrimary => {\n      const currentLeaseIsValid =\n        currentPrimary !== null &&\n        this.isWithinAge(\n          currentPrimary.leaseTimestampMs,\n          MAX_PRIMARY_ELIGIBLE_AGE_MS\n        ) &&\n        !this.isClientZombied(currentPrimary.ownerId);\n\n      if (currentLeaseIsValid && !this.isLocalClient(currentPrimary)) {\n        if (\n          !this.forceOwningTab &&\n          (!this.allowTabSynchronization ||\n            !currentPrimary!.allowTabSynchronization)\n        ) {\n          throw new FirestoreError(\n            Code.FAILED_PRECONDITION,\n            PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n          );\n        }\n      }\n    });\n  }\n\n  /**\n   * Obtains or extends the new primary lease for the local client. This\n   * method does not verify that the client is eligible for this lease.\n   */\n  private acquireOrExtendPrimaryLease(\n    txn: PersistenceTransaction\n  ): PersistencePromise<void> {\n    const newPrimary: DbPrimaryClient = {\n      ownerId: this.clientId,\n      allowTabSynchronization: this.allowTabSynchronization,\n      leaseTimestampMs: Date.now()\n    };\n    return primaryClientStore(txn).put(DbPrimaryClientKey, newPrimary);\n  }\n\n  static isAvailable(): boolean {\n    return SimpleDb.isAvailable();\n  }\n\n  /** Checks the primary lease and removes it if we are the current primary. */\n  private releasePrimaryLeaseIfHeld(\n    txn: PersistenceTransaction\n  ): PersistencePromise<void> {\n    const store = primaryClientStore(txn);\n    return store.get(DbPrimaryClientKey).next(primaryClient => {\n      if (this.isLocalClient(primaryClient)) {\n        logDebug(LOG_TAG, 'Releasing primary lease.');\n        return store.delete(DbPrimaryClientKey);\n      } else {\n        return PersistencePromise.resolve();\n      }\n    });\n  }\n\n  /** Verifies that `updateTimeMs` is within `maxAgeMs`. */\n  private isWithinAge(updateTimeMs: number, maxAgeMs: number): boolean {\n    const now = Date.now();\n    const minAcceptable = now - maxAgeMs;\n    const maxAcceptable = now;\n    if (updateTimeMs < minAcceptable) {\n      return false;\n    } else if (updateTimeMs > maxAcceptable) {\n      logError(\n        `Detected an update time that is in the future: ${updateTimeMs} > ${maxAcceptable}`\n      );\n      return false;\n    }\n\n    return true;\n  }\n\n  private attachVisibilityHandler(): void {\n    if (\n      this.document !== null &&\n      typeof this.document.addEventListener === 'function'\n    ) {\n      this.documentVisibilityHandler = () => {\n        this.queue.enqueueAndForget(() => {\n          this.inForeground = this.document!.visibilityState === 'visible';\n          return this.updateClientMetadataAndTryBecomePrimary();\n        });\n      };\n\n      this.document.addEventListener(\n        'visibilitychange',\n        this.documentVisibilityHandler\n      );\n\n      this.inForeground = this.document.visibilityState === 'visible';\n    }\n  }\n\n  private detachVisibilityHandler(): void {\n    if (this.documentVisibilityHandler) {\n      debugAssert(\n        this.document !== null &&\n          typeof this.document.addEventListener === 'function',\n        \"Expected 'document.addEventListener' to be a function\"\n      );\n      this.document.removeEventListener(\n        'visibilitychange',\n        this.documentVisibilityHandler\n      );\n      this.documentVisibilityHandler = null;\n    }\n  }\n\n  /**\n   * Attaches a window.unload handler that will synchronously write our\n   * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n   * by tabs trying to acquire the primary lease to determine that the lease\n   * is no longer valid even if the timestamp is recent. This is particularly\n   * important for the refresh case (so the tab correctly re-acquires the\n   * primary lease). LocalStorage is used for this rather than IndexedDb because\n   * it is a synchronous API and so can be used reliably from  an unload\n   * handler.\n   */\n  private attachWindowUnloadHook(): void {\n    if (typeof this.window?.addEventListener === 'function') {\n      this.windowUnloadHandler = () => {\n        // Note: In theory, this should be scheduled on the AsyncQueue since it\n        // accesses internal state. We execute this code directly during shutdown\n        // to make sure it gets a chance to run.\n        this.markClientZombied();\n\n        const safariIndexdbBugVersionRegex = /(?:Version|Mobile)\\/1[456]/;\n        if (\n          isSafari() &&\n          (navigator.appVersion.match(safariIndexdbBugVersionRegex) ||\n            navigator.userAgent.match(safariIndexdbBugVersionRegex))\n        ) {\n          // On Safari 14, 15, and 16, we do not run any cleanup actions as it might\n          // trigger a bug that prevents Safari from re-opening IndexedDB during\n          // the next page load.\n          // See https://bugs.webkit.org/show_bug.cgi?id=226547\n          this.queue.enterRestrictedMode(/* purgeExistingTasks= */ true);\n        }\n\n        this.queue.enqueueAndForget(() => {\n          // Attempt graceful shutdown (including releasing our primary lease),\n          // but there's no guarantee it will complete.\n          return this.shutdown();\n        });\n      };\n      this.window.addEventListener('pagehide', this.windowUnloadHandler);\n    }\n  }\n\n  private detachWindowUnloadHook(): void {\n    if (this.windowUnloadHandler) {\n      debugAssert(\n        typeof this.window?.removeEventListener === 'function',\n        \"Expected 'window.removeEventListener' to be a function\"\n      );\n      this.window!.removeEventListener('pagehide', this.windowUnloadHandler);\n      this.windowUnloadHandler = null;\n    }\n  }\n\n  /**\n   * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n   * Clients become zombied when their tab closes without running all of the\n   * cleanup logic in `shutdown()`.\n   */\n  private isClientZombied(clientId: ClientId): boolean {\n    try {\n      const isZombied =\n        this.webStorage?.getItem(\n          this.zombiedClientLocalStorageKey(clientId)\n        ) !== null;\n      logDebug(\n        LOG_TAG,\n        `Client '${clientId}' ${\n          isZombied ? 'is' : 'is not'\n        } zombied in LocalStorage`\n      );\n      return isZombied;\n    } catch (e) {\n      // Gracefully handle if LocalStorage isn't working.\n      logError(LOG_TAG, 'Failed to get zombied client id.', e);\n      return false;\n    }\n  }\n\n  /**\n   * Record client as zombied (a client that had its tab closed). Zombied\n   * clients are ignored during primary tab selection.\n   */\n  private markClientZombied(): void {\n    if (!this.webStorage) {\n      return;\n    }\n    try {\n      this.webStorage.setItem(\n        this.zombiedClientLocalStorageKey(this.clientId),\n        String(Date.now())\n      );\n    } catch (e) {\n      // Gracefully handle if LocalStorage isn't available / working.\n      logError('Failed to set zombie client id.', e);\n    }\n  }\n\n  /** Removes the zombied client entry if it exists. */\n  private removeClientZombiedEntry(): void {\n    if (!this.webStorage) {\n      return;\n    }\n    try {\n      this.webStorage.removeItem(\n        this.zombiedClientLocalStorageKey(this.clientId)\n      );\n    } catch (e) {\n      // Ignore\n    }\n  }\n\n  private zombiedClientLocalStorageKey(clientId: ClientId): string {\n    return `${ZOMBIED_CLIENTS_KEY_PREFIX}_${this.persistenceKey}_${clientId}`;\n  }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */\nfunction primaryClientStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbPrimaryClientKey, DbPrimaryClient> {\n  return getStore<DbPrimaryClientKey, DbPrimaryClient>(\n    txn,\n    DbPrimaryClientStore\n  );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */\nfunction clientMetadataStore(\n  txn: PersistenceTransaction\n): SimpleDbStore<DbClientMetadataKey, DbClientMetadata> {\n  return getStore<DbClientMetadataKey, DbClientMetadata>(\n    txn,\n    DbClientMetadataStore\n  );\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\nexport function indexedDbStoragePrefix(\n  databaseId: DatabaseId,\n  persistenceKey: string\n): string {\n  // Use two different prefix formats:\n  //\n  //   * firestore / persistenceKey / projectID . databaseID / ...\n  //   * firestore / persistenceKey / projectID / ...\n  //\n  // projectIDs are DNS-compatible names and cannot contain dots\n  // so there's no danger of collisions.\n  let database = databaseId.projectId;\n  if (!databaseId.isDefaultDatabase) {\n    database += '.' + databaseId.database;\n  }\n\n  return 'firestore/' + persistenceKey + '/' + database + '/';\n}\n\nexport async function indexedDbClearPersistence(\n  persistenceKey: string\n): Promise<void> {\n  if (!SimpleDb.isAvailable()) {\n    return Promise.resolve();\n  }\n  const dbName = persistenceKey + MAIN_DATABASE;\n  await SimpleDb.delete(dbName);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 { CorePipeline, getPipelineDocuments } from '../core/pipeline';\nimport {\n  canonifyTargetOrPipeline,\n  isPipeline,\n  QueryOrPipeline,\n  TargetOrPipeline,\n  targetOrPipelineEqual\n} from '../core/pipeline-util';\nimport { newQueryForPath, queryToTarget } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Target } from '../core/target';\nimport { BatchId, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n  convertOverlayedDocumentMapToDocumentMap,\n  documentKeySet,\n  DocumentKeySet,\n  DocumentMap,\n  mutableDocumentMap,\n  MutableDocumentMap,\n  OverlayedDocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n  FieldIndex,\n  fieldIndexSemanticComparator,\n  INITIAL_LARGEST_BATCH_ID,\n  newIndexOffsetSuccessorFromReadTime\n} from '../model/field_index';\nimport {\n  mutationExtractBaseValue,\n  Mutation,\n  PatchMutation,\n  Precondition\n} from '../model/mutation';\nimport { MutationBatch, MutationBatchResult } from '../model/mutation_batch';\nimport { extractFieldMask } from '../model/object_value';\nimport { ResourcePath } from '../model/path';\nimport {\n  BundleMetadata,\n  NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport { fromVersion, JsonProtoSerializer } from '../remote/serializer';\nimport { diffArrays } from '../util/array';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { BundleCache } from './bundle_cache';\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { IndexedDbPersistence } from './indexeddb_persistence';\nimport { IndexedDbTargetCache } from './indexeddb_target_cache';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { fromBundledQuery } from './local_serializer';\nimport { LocalStore } from './local_store';\nimport { LocalViewChanges } from './local_view_changes';\nimport { LruGarbageCollector, LruResults } from './lru_garbage_collector';\nimport { MutationQueue } from './mutation_queue';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryEngine } from './query_engine';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { ClientId } from './shared_client_state';\nimport { isIndexedDbTransactionError } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData, TargetPurpose } from './target_data';\n\nexport const LOG_TAG = 'LocalStore';\n\n/**\n * The maximum time to leave a resume token buffered without writing it out.\n * This value is arbitrary: it's long enough to avoid several writes\n * (possibly indefinitely if updates come more frequently than this) but\n * short enough that restarting after crashing will still have a pretty\n * recent resume token.\n */\nconst RESUME_TOKEN_MAX_AGE_MICROS = 5 * 60 * 1e6;\n\n/** The result of a write to the local store. */\nexport interface LocalWriteResult {\n  batchId: BatchId;\n  changes: DocumentMap;\n}\n\n/** The result of a user-change operation in the local store. */\nexport interface UserChangeResult {\n  readonly affectedDocuments: DocumentMap;\n  readonly removedBatchIds: BatchId[];\n  readonly addedBatchIds: BatchId[];\n}\n\n/** The result of executing a query against the local store. */\nexport interface QueryResult {\n  readonly documents: DocumentMap;\n  readonly remoteKeys: DocumentKeySet;\n}\n\n/**\n * Implements `LocalStore` interface.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass LocalStoreImpl implements LocalStore {\n  /**\n   * The set of all mutations that have been sent but not yet been applied to\n   * the backend.\n   */\n  mutationQueue!: MutationQueue;\n\n  /**\n   * The overlays that can be used to short circuit applying all mutations from\n   * mutation queue.\n   */\n  documentOverlayCache!: DocumentOverlayCache;\n\n  /** The set of all cached remote documents. */\n  remoteDocuments: RemoteDocumentCache;\n\n  /**\n   * The \"local\" view of all documents (layering mutationQueue on top of\n   * remoteDocumentCache).\n   */\n  localDocuments!: LocalDocumentsView;\n\n  /** Manages the list of active field and collection indices. */\n  indexManager!: IndexManager;\n\n  /** The set of all cached bundle metadata and named queries. */\n  bundleCache: BundleCache;\n\n  /** Maps a target to its `TargetData`. */\n  targetCache: TargetCache;\n\n  /**\n   * Maps a targetID to data about its target.\n   *\n   * PORTING NOTE: We are using an immutable data structure on Web to make re-runs\n   * of `applyRemoteEvent()` idempotent.\n   */\n  targetDataByTarget = new SortedMap<TargetId, TargetData>(primitiveComparator);\n\n  /** Maps a target to its targetID. */\n  // TODO(wuandy): Evaluate if TargetId can be part of Target.\n  targetIdByTarget = new ObjectMap<TargetOrPipeline, TargetId>(\n    t => canonifyTargetOrPipeline(t),\n    targetOrPipelineEqual\n  );\n\n  /**\n   * A per collection group index of the last read time processed by\n   * `getNewDocumentChanges()`.\n   *\n   * PORTING NOTE: This is only used for multi-tab synchronization.\n   */\n  collectionGroupReadTime = new Map<string, SnapshotVersion>();\n\n  constructor(\n    /** Manages our in-memory or durable persistence. */\n    readonly persistence: Persistence,\n    readonly queryEngine: QueryEngine,\n    initialUser: User,\n    readonly serializer: JsonProtoSerializer\n  ) {\n    debugAssert(\n      persistence.started,\n      'LocalStore was passed an unstarted persistence implementation'\n    );\n    this.remoteDocuments = persistence.getRemoteDocumentCache();\n    this.targetCache = persistence.getTargetCache();\n    this.bundleCache = persistence.getBundleCache();\n\n    this.initializeUserComponents(initialUser);\n  }\n\n  initializeUserComponents(user: User): void {\n    // TODO(indexing): Add spec tests that test these components change after a\n    // user change\n    this.documentOverlayCache = this.persistence.getDocumentOverlayCache(user);\n    this.indexManager = this.persistence.getIndexManager(user);\n    this.mutationQueue = this.persistence.getMutationQueue(\n      user,\n      this.indexManager\n    );\n    this.localDocuments = new LocalDocumentsView(\n      this.remoteDocuments,\n      this.mutationQueue,\n      this.documentOverlayCache,\n      this.indexManager\n    );\n    this.remoteDocuments.setIndexManager(this.indexManager);\n    this.queryEngine.initialize(this.localDocuments, this.indexManager);\n  }\n\n  collectGarbage(garbageCollector: LruGarbageCollector): Promise<LruResults> {\n    return this.persistence.runTransaction(\n      'Collect garbage',\n      'readwrite-primary',\n      txn => garbageCollector.collect(txn, this.targetDataByTarget)\n    );\n  }\n}\n\ninterface DocumentChangeResult {\n  changedDocuments: MutableDocumentMap;\n  existenceChangedKeys: DocumentKeySet;\n}\n\nexport function newLocalStore(\n  /** Manages our in-memory or durable persistence. */\n  persistence: Persistence,\n  queryEngine: QueryEngine,\n  initialUser: User,\n  serializer: JsonProtoSerializer\n): LocalStore {\n  return new LocalStoreImpl(persistence, queryEngine, initialUser, serializer);\n}\n\n/**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n// PORTING NOTE: Android and iOS only return the documents affected by the\n// change.\nexport async function localStoreHandleUserChange(\n  localStore: LocalStore,\n  user: User\n): Promise<UserChangeResult> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n\n  const result = await localStoreImpl.persistence.runTransaction(\n    'Handle user change',\n    'readonly',\n    txn => {\n      // Swap out the mutation queue, grabbing the pending mutation batches\n      // before and after.\n      let oldBatches: MutationBatch[];\n      return localStoreImpl.mutationQueue\n        .getAllMutationBatches(txn)\n        .next(promisedOldBatches => {\n          oldBatches = promisedOldBatches;\n          localStoreImpl.initializeUserComponents(user);\n          return localStoreImpl.mutationQueue.getAllMutationBatches(txn);\n        })\n        .next(newBatches => {\n          const removedBatchIds: BatchId[] = [];\n          const addedBatchIds: BatchId[] = [];\n\n          // Union the old/new changed keys.\n          let changedKeys = documentKeySet();\n\n          for (const batch of oldBatches) {\n            removedBatchIds.push(batch.batchId);\n            for (const mutation of batch.mutations) {\n              changedKeys = changedKeys.add(mutation.key);\n            }\n          }\n\n          for (const batch of newBatches) {\n            addedBatchIds.push(batch.batchId);\n            for (const mutation of batch.mutations) {\n              changedKeys = changedKeys.add(mutation.key);\n            }\n          }\n\n          // Return the set of all (potentially) changed documents and the list\n          // of mutation batch IDs that were affected by change.\n          return localStoreImpl.localDocuments\n            .getDocuments(txn, changedKeys)\n            .next(affectedDocuments => {\n              return {\n                affectedDocuments,\n                removedBatchIds,\n                addedBatchIds\n              };\n            });\n        });\n    }\n  );\n\n  return result;\n}\n\n/* Accepts locally generated Mutations and commit them to storage. */\nexport function localStoreWriteLocally(\n  localStore: LocalStore,\n  mutations: Mutation[]\n): Promise<LocalWriteResult> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  const localWriteTime = Timestamp.now();\n  const keys = mutations.reduce((keys, m) => keys.add(m.key), documentKeySet());\n\n  let overlayedDocuments: OverlayedDocumentMap;\n  let mutationBatch: MutationBatch;\n\n  return localStoreImpl.persistence\n    .runTransaction('Locally write mutations', 'readwrite', txn => {\n      // Figure out which keys do not have a remote version in the cache, this\n      // is needed to create the right overlay mutation: if no remote version\n      // presents, we do not need to create overlays as patch mutations.\n      // TODO(Overlay): Is there a better way to determine this? Using the\n      //  document version does not work because local mutations set them back\n      //  to 0.\n      let remoteDocs = mutableDocumentMap();\n      let docsWithoutRemoteVersion = documentKeySet();\n      return localStoreImpl.remoteDocuments\n        .getEntries(txn, keys)\n        .next(docs => {\n          remoteDocs = docs;\n          remoteDocs.forEach((key, doc) => {\n            if (!doc.isValidDocument()) {\n              docsWithoutRemoteVersion = docsWithoutRemoteVersion.add(key);\n            }\n          });\n        })\n        .next(() => {\n          // Load and apply all existing mutations. This lets us compute the\n          // current base state for all non-idempotent transforms before applying\n          // any additional user-provided writes.\n          return localStoreImpl.localDocuments.getOverlayedDocuments(\n            txn,\n            remoteDocs\n          );\n        })\n        .next((docs: OverlayedDocumentMap) => {\n          overlayedDocuments = docs;\n\n          // For non-idempotent mutations (such as `FieldValue.increment()`),\n          // we record the base state in a separate patch mutation. This is\n          // later used to guarantee consistent values and prevents flicker\n          // even if the backend sends us an update that already includes our\n          // transform.\n          const baseMutations: Mutation[] = [];\n\n          for (const mutation of mutations) {\n            const baseValue = mutationExtractBaseValue(\n              mutation,\n              overlayedDocuments.get(mutation.key)!.overlayedDocument\n            );\n            if (baseValue != null) {\n              // NOTE: The base state should only be applied if there's some\n              // existing document to override, so use a Precondition of\n              // exists=true\n              baseMutations.push(\n                new PatchMutation(\n                  mutation.key,\n                  baseValue,\n                  extractFieldMask(baseValue.value.mapValue),\n                  Precondition.exists(true)\n                )\n              );\n            }\n          }\n\n          return localStoreImpl.mutationQueue.addMutationBatch(\n            txn,\n            localWriteTime,\n            baseMutations,\n            mutations\n          );\n        })\n        .next(batch => {\n          mutationBatch = batch;\n          const overlays = batch.applyToLocalDocumentSet(\n            overlayedDocuments,\n            docsWithoutRemoteVersion\n          );\n          return localStoreImpl.documentOverlayCache.saveOverlays(\n            txn,\n            batch.batchId,\n            overlays\n          );\n        });\n    })\n    .then(() => ({\n      batchId: mutationBatch.batchId,\n      changes: convertOverlayedDocumentMapToDocumentMap(overlayedDocuments)\n    }));\n}\n\n/**\n * Acknowledges the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n *  + remove the batch from the mutation queue;\n *  + apply the changes to the remote document cache;\n *  + recalculate the latency compensated view implied by those changes (there\n *    may be mutations in the queue that affect the documents but haven't been\n *    acknowledged yet); and\n *  + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\nexport function localStoreAcknowledgeBatch(\n  localStore: LocalStore,\n  batchResult: MutationBatchResult\n): Promise<DocumentMap> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  return localStoreImpl.persistence.runTransaction(\n    'Acknowledge batch',\n    'readwrite-primary',\n    txn => {\n      const affected = batchResult.batch.keys();\n      const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n        trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n      });\n      return applyWriteToRemoteDocuments(\n        localStoreImpl,\n        txn,\n        batchResult,\n        documentBuffer\n      )\n        .next(() => documentBuffer.apply(txn))\n        .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn))\n        .next(() =>\n          localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(\n            txn,\n            affected,\n            batchResult.batch.batchId\n          )\n        )\n        .next(() =>\n          localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(\n            txn,\n            getKeysWithTransformResults(batchResult)\n          )\n        )\n        .next(() => localStoreImpl.localDocuments.getDocuments(txn, affected));\n    }\n  );\n}\n\nfunction getKeysWithTransformResults(\n  batchResult: MutationBatchResult\n): DocumentKeySet {\n  let result = documentKeySet();\n\n  for (let i = 0; i < batchResult.mutationResults.length; ++i) {\n    const mutationResult = batchResult.mutationResults[i];\n    if (mutationResult.transformResults.length > 0) {\n      result = result.add(batchResult.batch.mutations[i].key);\n    }\n  }\n  return result;\n}\n\n/**\n * Removes mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\nexport function localStoreRejectBatch(\n  localStore: LocalStore,\n  batchId: BatchId\n): Promise<DocumentMap> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  return localStoreImpl.persistence.runTransaction(\n    'Reject batch',\n    'readwrite-primary',\n    txn => {\n      let affectedKeys: DocumentKeySet;\n      return localStoreImpl.mutationQueue\n        .lookupMutationBatch(txn, batchId)\n        .next((batch: MutationBatch | null) => {\n          hardAssert(\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<BatchId> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  return localStoreImpl.persistence.runTransaction(\n    'Get highest unacknowledged batch id',\n    'readonly',\n    txn => localStoreImpl.mutationQueue.getHighestUnacknowledgedBatchId(txn)\n  );\n}\n\n/**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\nexport function localStoreGetLastRemoteSnapshotVersion(\n  localStore: LocalStore\n): Promise<SnapshotVersion> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  return localStoreImpl.persistence.runTransaction(\n    'Get last remote snapshot version',\n    'readonly',\n    txn => localStoreImpl.targetCache.getLastRemoteSnapshotVersion(txn)\n  );\n}\n\n/**\n * Updates the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nexport function localStoreApplyRemoteEventToLocalCache(\n  localStore: LocalStore,\n  remoteEvent: RemoteEvent\n): Promise<DocumentMap> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  const remoteVersion = remoteEvent.snapshotVersion;\n  let newTargetDataByTargetMap = localStoreImpl.targetDataByTarget;\n\n  return localStoreImpl.persistence\n    .runTransaction('Apply remote event', 'readwrite-primary', txn => {\n      const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n        trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n      });\n\n      // Reset newTargetDataByTargetMap in case this transaction gets re-run.\n      newTargetDataByTargetMap = localStoreImpl.targetDataByTarget;\n\n      const promises = [] as Array<PersistencePromise<void>>;\n      remoteEvent.targetChanges.forEach((change, targetId) => {\n        const oldTargetData = newTargetDataByTargetMap.get(targetId);\n        if (!oldTargetData) {\n          return;\n        }\n\n        // Only update the remote keys if the target is still active. This\n        // ensures that we can persist the updated target data along with\n        // the updated assignment.\n        promises.push(\n          localStoreImpl.targetCache\n            .removeMatchingKeys(txn, change.removedDocuments, targetId)\n            .next(() => {\n              return localStoreImpl.targetCache.addMatchingKeys(\n                txn,\n                change.addedDocuments,\n                targetId\n              );\n            })\n        );\n\n        let newTargetData = oldTargetData.withSequenceNumber(\n          txn.currentSequenceNumber\n        );\n        if (remoteEvent.targetMismatches.get(targetId) !== null) {\n          newTargetData = newTargetData\n            .withResumeToken(\n              ByteString.EMPTY_BYTE_STRING,\n              SnapshotVersion.min()\n            )\n            .withLastLimboFreeSnapshotVersion(SnapshotVersion.min());\n        } else if (change.resumeToken.approximateByteSize() > 0) {\n          newTargetData = newTargetData.withResumeToken(\n            change.resumeToken,\n            remoteVersion\n          );\n        }\n\n        newTargetDataByTargetMap = newTargetDataByTargetMap.insert(\n          targetId,\n          newTargetData\n        );\n\n        // Update the target data if there are target changes (or if\n        // sufficient time has passed since the last update).\n        if (shouldPersistTargetData(oldTargetData, newTargetData, change)) {\n          promises.push(\n            localStoreImpl.targetCache.updateTargetData(txn, newTargetData)\n          );\n        }\n      });\n\n      let changedDocs = mutableDocumentMap();\n      let existenceChangedKeys = documentKeySet();\n      remoteEvent.documentUpdates.forEach(key => {\n        if (remoteEvent.resolvedLimboDocuments.has(key)) {\n          promises.push(\n            localStoreImpl.persistence.referenceDelegate.updateLimboDocument(\n              txn,\n              key\n            )\n          );\n        }\n      });\n\n      // Each loop iteration only affects its \"own\" doc, so it's safe to get all\n      // the remote documents in advance in a single call.\n      promises.push(\n        populateDocumentChangeBuffer(\n          txn,\n          documentBuffer,\n          remoteEvent.documentUpdates\n        ).next(result => {\n          changedDocs = result.changedDocuments;\n          existenceChangedKeys = result.existenceChangedKeys;\n        })\n      );\n\n      // HACK: The only reason we allow a null snapshot version is so that we\n      // can synthesize remote events when we get permission denied errors while\n      // trying to resolve the state of a locally cached document that is in\n      // limbo.\n      if (!remoteVersion.isEqual(SnapshotVersion.min())) {\n        const updateRemoteVersion = localStoreImpl.targetCache\n          .getLastRemoteSnapshotVersion(txn)\n          .next(lastRemoteSnapshotVersion => {\n            debugAssert(\n              remoteVersion.compareTo(lastRemoteSnapshotVersion) >= 0,\n              'Watch stream reverted to previous snapshot?? ' +\n                remoteVersion +\n                ' < ' +\n                lastRemoteSnapshotVersion\n            );\n            return localStoreImpl.targetCache.setTargetsMetadata(\n              txn,\n              txn.currentSequenceNumber,\n              remoteVersion\n            );\n          });\n        promises.push(updateRemoteVersion);\n      }\n\n      return PersistencePromise.waitFor(promises)\n        .next(() => documentBuffer.apply(txn))\n        .next(() =>\n          localStoreImpl.localDocuments.getLocalViewOfDocuments(\n            txn,\n            changedDocs,\n            existenceChangedKeys\n          )\n        )\n        .next(() => changedDocs);\n    })\n    .then(changedDocs => {\n      localStoreImpl.targetDataByTarget = newTargetDataByTargetMap;\n      return changedDocs;\n    });\n}\n\n/**\n * Populates document change buffer with documents from backend or a bundle.\n * Returns the document changes resulting from applying those documents, and\n * also a set of documents whose existence state are changed as a result.\n *\n * @param txn - Transaction to use to read existing documents from storage.\n * @param documentBuffer - Document buffer to collect the resulted changes to be\n *        applied to storage.\n * @param documents - Documents to be applied.\n */\nfunction populateDocumentChangeBuffer(\n  txn: PersistenceTransaction,\n  documentBuffer: RemoteDocumentChangeBuffer,\n  documents: MutableDocumentMap\n): PersistencePromise<DocumentChangeResult> {\n  let updatedKeys = documentKeySet();\n  let existenceChangedKeys = documentKeySet();\n  documents.forEach(k => (updatedKeys = updatedKeys.add(k)));\n  return documentBuffer.getEntries(txn, updatedKeys).next(existingDocs => {\n    let changedDocuments = mutableDocumentMap();\n    documents.forEach((key, doc) => {\n      const existingDoc = existingDocs.get(key)!;\n\n      // Check if see if there is a existence state change for this document.\n      if (doc.isFoundDocument() !== existingDoc.isFoundDocument()) {\n        existenceChangedKeys = existenceChangedKeys.add(key);\n      }\n\n      // Note: The order of the steps below is important, since we want\n      // to ensure that rejected limbo resolutions (which fabricate\n      // NoDocuments with SnapshotVersion.min()) never add documents to\n      // cache.\n      if (doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min())) {\n        // NoDocuments with SnapshotVersion.min() are used in manufactured\n        // events. We remove these documents from cache since we lost\n        // access.\n        documentBuffer.removeEntry(key, doc.readTime);\n        changedDocuments = changedDocuments.insert(key, doc);\n      } else if (\n        !existingDoc.isValidDocument() ||\n        doc.version.compareTo(existingDoc.version) > 0 ||\n        (doc.version.compareTo(existingDoc.version) === 0 &&\n          existingDoc.hasPendingWrites)\n      ) {\n        debugAssert(\n          !SnapshotVersion.min().isEqual(doc.readTime),\n          'Cannot add a document when the remote version is zero'\n        );\n        documentBuffer.addEntry(doc);\n        changedDocuments = changedDocuments.insert(key, doc);\n      } else {\n        logDebug(\n          LOG_TAG,\n          'Ignoring outdated watch update for ',\n          key,\n          '. Current version:',\n          existingDoc.version,\n          ' Watch version:',\n          doc.version\n        );\n      }\n    });\n    return { changedDocuments, existenceChangedKeys };\n  });\n}\n\n/**\n * Returns true if the newTargetData should be persisted during an update of\n * an active target. TargetData should always be persisted when a target is\n * being released and should not call this function.\n *\n * While the target is active, TargetData updates can be omitted when nothing\n * about the target has changed except metadata like the resume token or\n * snapshot version. Occasionally it's worth the extra write to prevent these\n * values from getting too stale after a crash, but this doesn't have to be\n * too frequent.\n */\nfunction shouldPersistTargetData(\n  oldTargetData: TargetData,\n  newTargetData: TargetData,\n  change: TargetChange\n): boolean {\n  // Always persist target data if we don't already have a resume token.\n  if (oldTargetData.resumeToken.approximateByteSize() === 0) {\n    return true;\n  }\n\n  // Don't allow resume token changes to be buffered indefinitely. This\n  // allows us to be reasonably up-to-date after a crash and avoids needing\n  // to loop over all active queries on shutdown. Especially in the browser\n  // we may not get time to do anything interesting while the current tab is\n  // closing.\n  const timeDelta =\n    newTargetData.snapshotVersion.toMicroseconds() -\n    oldTargetData.snapshotVersion.toMicroseconds();\n  if (timeDelta >= RESUME_TOKEN_MAX_AGE_MICROS) {\n    return true;\n  }\n\n  // Otherwise if the only thing that has changed about a target is its resume\n  // token it's not worth persisting. Note that the RemoteStore keeps an\n  // in-memory view of the currently active targets which includes the current\n  // resume token, so stream failure or user changes will still use an\n  // up-to-date resume token regardless of what we do here.\n  const changes =\n    change.addedDocuments.size +\n    change.modifiedDocuments.size +\n    change.removedDocuments.size;\n  return changes > 0;\n}\n\n/**\n * Notifies local store of the changed views to locally pin documents.\n */\nexport async function localStoreNotifyLocalViewChanges(\n  localStore: LocalStore,\n  viewChanges: LocalViewChanges[]\n): Promise<void> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  try {\n    await localStoreImpl.persistence.runTransaction(\n      'notifyLocalViewChanges',\n      'readwrite',\n      txn => {\n        return PersistencePromise.forEach(\n          viewChanges,\n          (viewChange: LocalViewChanges) => {\n            return PersistencePromise.forEach(\n              viewChange.addedKeys,\n              (key: DocumentKey) =>\n                localStoreImpl.persistence.referenceDelegate.addReference(\n                  txn,\n                  viewChange.targetId,\n                  key\n                )\n            ).next(() =>\n              PersistencePromise.forEach(\n                viewChange.removedKeys,\n                (key: DocumentKey) =>\n                  localStoreImpl.persistence.referenceDelegate.removeReference(\n                    txn,\n                    viewChange.targetId,\n                    key\n                  )\n              )\n            );\n          }\n        );\n      }\n    );\n  } catch (e) {\n    if (isIndexedDbTransactionError(e as Error)) {\n      // If `notifyLocalViewChanges` fails, we did not advance the sequence\n      // number for the documents that were included in this transaction.\n      // This might trigger them to be deleted earlier than they otherwise\n      // would have, but it should not invalidate the integrity of the data.\n      logDebug(LOG_TAG, 'Failed to update sequence numbers: ' + e);\n    } else {\n      throw e;\n    }\n  }\n\n  for (const viewChange of viewChanges) {\n    const targetId = viewChange.targetId;\n\n    if (!viewChange.fromCache) {\n      const targetData = localStoreImpl.targetDataByTarget.get(targetId);\n      debugAssert(\n        targetData !== null,\n        `Can't set limbo-free snapshot version for unknown target: ${targetId}`\n      );\n\n      // Advance the last limbo free snapshot version\n      const lastLimboFreeSnapshotVersion = targetData.snapshotVersion;\n      const updatedTargetData = targetData.withLastLimboFreeSnapshotVersion(\n        lastLimboFreeSnapshotVersion\n      );\n      localStoreImpl.targetDataByTarget =\n        localStoreImpl.targetDataByTarget.insert(targetId, updatedTargetData);\n\n      // TODO(b/272564316): Apply the optimization done on other platforms.\n      // This is a problem for web because saving the updated targetData from\n      // non-primary client conflicts with what primary client saved.\n    }\n  }\n}\n\n/**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId - If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\nexport function localStoreGetNextMutationBatch(\n  localStore: LocalStore,\n  afterBatchId?: BatchId\n): Promise<MutationBatch | null> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  return localStoreImpl.persistence.runTransaction(\n    'Get next mutation batch',\n    'readonly',\n    txn => {\n      if (afterBatchId === undefined) {\n        afterBatchId = BATCHID_UNKNOWN;\n      }\n      return localStoreImpl.mutationQueue.getNextMutationBatchAfterBatchId(\n        txn,\n        afterBatchId\n      );\n    }\n  );\n}\n\n/**\n * Reads the current value of a Document with a given key or null if not\n * found - used for testing.\n */\nexport function localStoreReadDocument(\n  localStore: LocalStore,\n  key: DocumentKey\n): Promise<Document> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  return localStoreImpl.persistence.runTransaction(\n    'read document',\n    'readonly',\n    txn => localStoreImpl.localDocuments.getDocument(txn, key)\n  );\n}\n\n/**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */\nexport function localStoreAllocateTarget(\n  localStore: LocalStore,\n  target: TargetOrPipeline\n): Promise<TargetData> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n\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: TargetOrPipeline\n): PersistencePromise<TargetData | null> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  const targetId = localStoreImpl.targetIdByTarget.get(target);\n  if (targetId !== undefined) {\n    return PersistencePromise.resolve<TargetData | null>(\n      localStoreImpl.targetDataByTarget.get(targetId)\n    );\n  } else {\n    return localStoreImpl.targetCache.getTargetData(transaction, target);\n  }\n}\n\n/**\n * Unpins all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */\n// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\nexport async function localStoreReleaseTarget(\n  localStore: LocalStore,\n  targetId: number,\n  keepPersistedTargetData: boolean\n): Promise<void> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  const targetData = localStoreImpl.targetDataByTarget.get(targetId);\n\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  // TODO(pipeline): This needs to handle pipeline properly.\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: QueryOrPipeline,\n  usePreviousResults: boolean\n): Promise<QueryResult> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  let lastLimboFreeSnapshotVersion = SnapshotVersion.min();\n  let remoteKeys = documentKeySet();\n\n  return localStoreImpl.persistence.runTransaction(\n    'Execute query',\n    'readwrite', // Use readwrite instead of readonly so indexes can be created\n    txn => {\n      return localStoreGetTargetData(\n        localStoreImpl,\n        txn,\n        isPipeline(query) ? query : queryToTarget(query)\n      )\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          // TODO(pipeline): this needs to be adapted to support other pipeline flavors.\n          // For now, only 'exact' flavor is supported and it is enough.\n          setMaxReadTime(localStoreImpl, documents);\n\n          return { documents, remoteKeys };\n        });\n    }\n  );\n}\n\nfunction applyWriteToRemoteDocuments(\n  localStoreImpl: LocalStoreImpl,\n  txn: PersistenceTransaction,\n  batchResult: MutationBatchResult,\n  documentBuffer: RemoteDocumentChangeBuffer\n): PersistencePromise<void> {\n  const batch = batchResult.batch;\n  const docKeys = batch.keys();\n  let promiseChain = PersistencePromise.resolve();\n  docKeys.forEach(docKey => {\n    promiseChain = promiseChain\n      .next(() => documentBuffer.getEntry(txn, docKey))\n      .next(doc => {\n        const ackVersion = batchResult.docVersions.get(docKey);\n        hardAssert(\n          ackVersion !== null,\n          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<DocumentMap | null> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  const mutationQueueImpl = debugCast(\n    localStoreImpl.mutationQueue,\n    IndexedDbMutationQueue // We only support IndexedDb in multi-tab mode.\n  );\n  return localStoreImpl.persistence.runTransaction(\n    'Lookup mutation documents',\n    'readonly',\n    txn => {\n      return mutationQueueImpl.lookupMutationKeys(txn, batchId).next(keys => {\n        if (keys) {\n          return localStoreImpl.localDocuments.getDocuments(\n            txn,\n            keys\n          ) as PersistencePromise<DocumentMap | null>;\n        } else {\n          return PersistencePromise.resolve<DocumentMap | null>(null);\n        }\n      });\n    }\n  );\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreRemoveCachedMutationBatchMetadata(\n  localStore: LocalStore,\n  batchId: BatchId\n): void {\n  const mutationQueueImpl = debugCast(\n    debugCast(localStore, LocalStoreImpl).mutationQueue,\n    IndexedDbMutationQueue // We only support IndexedDb in multi-tab mode.\n  );\n  mutationQueueImpl.removeCachedMutationKeys(batchId);\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetActiveClients(\n  localStore: LocalStore\n): Promise<ClientId[]> {\n  const persistenceImpl = debugCast(\n    debugCast(localStore, LocalStoreImpl).persistence,\n    IndexedDbPersistence // We only support IndexedDb in multi-tab mode.\n  );\n  return persistenceImpl.getActiveClients();\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetCachedTarget(\n  localStore: LocalStore,\n  targetId: TargetId\n): Promise<TargetOrPipeline | null> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  const targetCacheImpl = debugCast(\n    localStoreImpl.targetCache,\n    IndexedDbTargetCache // We only support IndexedDb in multi-tab mode.\n  );\n  const cachedTargetData = localStoreImpl.targetDataByTarget.get(targetId);\n  if (cachedTargetData) {\n    return Promise.resolve(cachedTargetData.target ?? null);\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?.target ?? null);\n      }\n    );\n  }\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetDocuments(\n  localStore: LocalStore,\n  pipeline: CorePipeline\n): Promise<DocumentMap> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n\n  const keys = getPipelineDocuments(pipeline)!;\n  const keySet = documentKeySet(...keys.map(k => DocumentKey.fromPath(k)));\n  return localStoreImpl.persistence\n    .runTransaction('Get documents for pipeline', 'readonly', txn =>\n      localStoreImpl.remoteDocuments.getEntries(txn, keySet)\n    )\n    .then(changedDocs => {\n      return changedDocs;\n    });\n}\n\n/**\n * Returns the set of documents that have been updated since the last call.\n * If this is the first call, returns the set of changes since client\n * initialization. Further invocations will return document that have changed\n * since the prior call.\n */\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetNewDocumentChanges(\n  localStore: LocalStore,\n  collectionGroup: string\n): Promise<DocumentMap> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n\n  // Get the current maximum read time for the collection. This should always\n  // exist, but to reduce the chance for regressions we default to\n  // SnapshotVersion.Min()\n  // TODO(indexing): Consider removing the default value.\n  const readTime =\n    localStoreImpl.collectionGroupReadTime.get(collectionGroup) ||\n    SnapshotVersion.min();\n\n  return localStoreImpl.persistence\n    .runTransaction('Get new document changes', 'readonly', txn =>\n      localStoreImpl.remoteDocuments.getAllFromCollectionGroup(\n        txn,\n        collectionGroup,\n        newIndexOffsetSuccessorFromReadTime(readTime, INITIAL_LARGEST_BATCH_ID),\n        /* limit= */ Number.MAX_SAFE_INTEGER\n      )\n    )\n    .then(changedDocs => {\n      setMaxReadTime(localStoreImpl, 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  changedDocs: SortedMap<DocumentKey, Document>\n): void {\n  changedDocs.forEach((_, doc) => {\n    const collectionGroup = doc.key.getCollectionGroup();\n    const readTime =\n      localStoreImpl.collectionGroupReadTime.get(collectionGroup) ||\n      SnapshotVersion.min();\n    if (doc.readTime.compareTo(readTime) > 0) {\n      localStoreImpl.collectionGroupReadTime.set(collectionGroup, doc.readTime);\n    }\n  });\n}\n\n/**\n * Creates a new target using the given bundle name, which will be used to\n * hold the keys of all documents from the bundle in query-document mappings.\n * This ensures that the loaded documents do not get garbage collected\n * right away.\n */\nfunction umbrellaTarget(bundleName: string): Target {\n  // It is OK that the path used for the query is not valid, because this will\n  // not be read and queried.\n  return queryToTarget(\n    newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${bundleName}`))\n  );\n}\n\n/**\n * Applies the documents from a bundle to the \"ground-state\" (remote)\n * documents.\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nexport async function localStoreApplyBundledDocuments(\n  localStore: LocalStore,\n  bundleConverter: BundleConverter,\n  documents: BundledDocuments,\n  bundleName: string\n): Promise<DocumentMap> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  let documentKeys = documentKeySet();\n  let documentMap = mutableDocumentMap();\n  for (const bundleDoc of documents) {\n    const documentKey = bundleConverter.toDocumentKey(bundleDoc.metadata.name!);\n    if (bundleDoc.document) {\n      documentKeys = documentKeys.add(documentKey);\n    }\n    const doc = bundleConverter.toMutableDocument(bundleDoc);\n    doc.setReadTime(\n      bundleConverter.toSnapshotVersion(bundleDoc.metadata.readTime!)\n    );\n    documentMap = documentMap.insert(documentKey, doc);\n  }\n\n  const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n    trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n  });\n\n  // Allocates a target to hold all document keys from the bundle, such that\n  // they will not get garbage collected right away.\n  const umbrellaTargetData = await localStoreAllocateTarget(\n    localStoreImpl,\n    umbrellaTarget(bundleName)\n  );\n  return localStoreImpl.persistence.runTransaction(\n    'Apply bundle documents',\n    'readwrite',\n    txn => {\n      return populateDocumentChangeBuffer(txn, documentBuffer, documentMap)\n        .next(documentChangeResult => {\n          documentBuffer.apply(txn);\n          return documentChangeResult;\n        })\n        .next(documentChangeResult => {\n          return localStoreImpl.targetCache\n            .removeMatchingKeysForTargetId(txn, umbrellaTargetData.targetId)\n            .next(() =>\n              localStoreImpl.targetCache.addMatchingKeys(\n                txn,\n                documentKeys,\n                umbrellaTargetData.targetId\n              )\n            )\n            .next(() =>\n              localStoreImpl.localDocuments.getLocalViewOfDocuments(\n                txn,\n                documentChangeResult.changedDocuments,\n                documentChangeResult.existenceChangedKeys\n              )\n            )\n            .next(() => documentChangeResult.changedDocuments);\n        });\n    }\n  );\n}\n\n/**\n * Returns a promise of a boolean to indicate if the given bundle has already\n * been loaded and the create time is newer than the current loading bundle.\n */\nexport function localStoreHasNewerBundle(\n  localStore: LocalStore,\n  bundleMetadata: BundleMetadata\n): Promise<boolean> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  const currentReadTime = fromVersion(bundleMetadata.createTime!);\n  return localStoreImpl.persistence\n    .runTransaction('hasNewerBundle', 'readonly', transaction => {\n      return localStoreImpl.bundleCache.getBundleMetadata(\n        transaction,\n        bundleMetadata.id!\n      );\n    })\n    .then(cached => {\n      return !!cached && cached.createTime!.compareTo(currentReadTime) >= 0;\n    });\n}\n\n/**\n * Saves the given `BundleMetadata` to local persistence.\n */\nexport function localStoreSaveBundle(\n  localStore: LocalStore,\n  bundleMetadata: BundleMetadata\n): Promise<void> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  return localStoreImpl.persistence.runTransaction(\n    'Save bundle',\n    'readwrite',\n    transaction => {\n      return localStoreImpl.bundleCache.saveBundleMetadata(\n        transaction,\n        bundleMetadata\n      );\n    }\n  );\n}\n\n/**\n * Returns a promise of a `NamedQuery` associated with given query name. Promise\n * resolves to undefined if no persisted data can be found.\n */\nexport function localStoreGetNamedQuery(\n  localStore: LocalStore,\n  queryName: string\n): Promise<NamedQuery | undefined> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  return localStoreImpl.persistence.runTransaction(\n    'Get named query',\n    'readonly',\n    transaction =>\n      localStoreImpl.bundleCache.getNamedQuery(transaction, queryName)\n  );\n}\n\n/**\n * Saves the given `NamedQuery` to local persistence.\n */\nexport async function localStoreSaveNamedQuery(\n  localStore: LocalStore,\n  query: ProtoNamedQuery,\n  documents: DocumentKeySet = documentKeySet()\n): Promise<void> {\n  // Allocate a target for the named query such that it can be resumed\n  // from associated read time if users use it to listen.\n  // NOTE: this also means if no corresponding target exists, the new target\n  // will remain active and will not get collected, unless users happen to\n  // unlisten the query somehow.\n  const allocated = await localStoreAllocateTarget(\n    localStore,\n    queryToTarget(fromBundledQuery(query.bundledQuery!))\n  );\n\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  return localStoreImpl.persistence.runTransaction(\n    'Save named query',\n    'readwrite',\n    transaction => {\n      const readTime = fromVersion(query.readTime!);\n      // Simply save the query itself if it is older than what the SDK already\n      // has.\n      if (allocated.snapshotVersion.compareTo(readTime) >= 0) {\n        return localStoreImpl.bundleCache.saveNamedQuery(transaction, query);\n      }\n\n      // Update existing target data because the query from the bundle is newer.\n      const newTargetData = allocated.withResumeToken(\n        ByteString.EMPTY_BYTE_STRING,\n        readTime\n      );\n      localStoreImpl.targetDataByTarget =\n        localStoreImpl.targetDataByTarget.insert(\n          newTargetData.targetId,\n          newTargetData\n        );\n      return localStoreImpl.targetCache\n        .updateTargetData(transaction, newTargetData)\n        .next(() =>\n          localStoreImpl.targetCache.removeMatchingKeysForTargetId(\n            transaction,\n            allocated.targetId\n          )\n        )\n        .next(() =>\n          localStoreImpl.targetCache.addMatchingKeys(\n            transaction,\n            documents,\n            allocated.targetId\n          )\n        )\n        .next(() =>\n          localStoreImpl.bundleCache.saveNamedQuery(transaction, query)\n        );\n    }\n  );\n}\n\nexport async function localStoreConfigureFieldIndexes(\n  localStore: LocalStore,\n  newFieldIndexes: FieldIndex[]\n): Promise<void> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  const indexManager = localStoreImpl.indexManager;\n  const promises: Array<PersistencePromise<void>> = [];\n  return localStoreImpl.persistence.runTransaction(\n    'Configure indexes',\n    'readwrite',\n    transaction =>\n      indexManager\n        .getFieldIndexes(transaction)\n        .next(oldFieldIndexes =>\n          diffArrays(\n            oldFieldIndexes,\n            newFieldIndexes,\n            fieldIndexSemanticComparator,\n            fieldIndex => {\n              promises.push(\n                indexManager.addFieldIndex(transaction, fieldIndex)\n              );\n            },\n            fieldIndex => {\n              promises.push(\n                indexManager.deleteFieldIndex(transaction, fieldIndex)\n              );\n            }\n          )\n        )\n        .next(() => PersistencePromise.waitFor(promises))\n  );\n}\n\nexport function localStoreSetIndexAutoCreationEnabled(\n  localStore: LocalStore,\n  isEnabled: boolean\n): void {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  localStoreImpl.queryEngine.indexAutoCreationEnabled = isEnabled;\n}\n\nexport function localStoreDeleteAllFieldIndexes(\n  localStore: LocalStore\n): Promise<void> {\n  const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n  const indexManager = localStoreImpl.indexManager;\n  return localStoreImpl.persistence.runTransaction(\n    'Delete All Indexes',\n    'readwrite',\n    transaction => indexManager.deleteAllFieldIndexes(transaction)\n  );\n}\n\n/**\n * Test-only hooks into the SDK for use exclusively by tests.\n */\nexport class TestingHooks {\n  private constructor() {\n    throw new Error('creating instances is not supported');\n  }\n\n  static setIndexAutoCreationSettings(\n    localStore: LocalStore,\n    settings: {\n      indexAutoCreationMinCollectionSize?: number;\n      relativeIndexReadCostPerDocument?: number;\n    }\n  ): void {\n    const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n    if (settings.indexAutoCreationMinCollectionSize !== undefined) {\n      localStoreImpl.queryEngine.indexAutoCreationMinCollectionSize =\n        settings.indexAutoCreationMinCollectionSize;\n    }\n    if (settings.relativeIndexReadCostPerDocument !== undefined) {\n      localStoreImpl.queryEngine.relativeIndexReadCostPerDocument =\n        settings.relativeIndexReadCostPerDocument;\n    }\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 './document';\nimport { DocumentKey } from './document_key';\n\nexport type DocumentComparator = (doc1: Document, doc2: Document) => number;\n\nexport function compareByKey(doc1: Document, doc2: Document): number {\n  return DocumentKey.comparator(doc1.key, doc2.key);\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  isPipeline,\n  pipelineHasRanges,\n  QueryOrPipeline,\n  stringifyQueryOrPipeline\n} from '../core/pipeline-util';\nimport {\n  pipelineMatches,\n  pipelineMatchesAllDocuments\n} from '../core/pipeline_run';\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, MutableDocument } from '../model/document';\nimport { compareByKey } from '../model/document_comparator';\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: QueryOrPipeline,\n    lastLimboFreeSnapshotVersion: SnapshotVersion,\n    remoteKeys: DocumentKeySet\n  ): PersistencePromise<DocumentMap> {\n    debugAssert(this.initialized, 'initialize() not called');\n\n    // Stores the result from executing the query; using this object is more\n    // convenient than passing the result between steps of the persistence\n    // transaction and improves readability comparatively.\n    const queryResult: { result: DocumentMap | null } = { result: null };\n\n    return this.performQueryUsingIndex(transaction, query)\n      .next(result => {\n        queryResult.result = result;\n      })\n      .next(() => {\n        if (queryResult.result) {\n          return;\n        }\n        return this.performQueryUsingRemoteKeys(\n          transaction,\n          query,\n          remoteKeys,\n          lastLimboFreeSnapshotVersion\n        ).next(result => {\n          queryResult.result = result;\n        });\n      })\n      .next(() => {\n        if (queryResult.result) {\n          return;\n        }\n        const context = new QueryContext();\n        return this.executeFullCollectionScan(transaction, query, context).next(\n          result => {\n            queryResult.result = result;\n            if (this.indexAutoCreationEnabled) {\n              return this.createCacheIndexes(\n                transaction,\n                query,\n                context,\n                result.size\n              );\n            }\n          }\n        );\n      })\n      .next(() => queryResult.result!);\n  }\n\n  createCacheIndexes(\n    transaction: PersistenceTransaction,\n    query: QueryOrPipeline,\n    context: QueryContext,\n    resultSize: number\n  ): PersistencePromise<void> {\n    if (isPipeline(query)) {\n      return PersistencePromise.resolve();\n    }\n\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    queryOrPipeline: QueryOrPipeline\n  ): PersistencePromise<DocumentMap | null> {\n    if (isPipeline(queryOrPipeline)) {\n      return PersistencePromise.resolve<DocumentMap | null>(null);\n    }\n\n    let query: Query = queryOrPipeline;\n\n    if (queryMatchesAllDocuments(query)) {\n      // Queries that match all documents don't benefit from using\n      // key-based lookups. It is more efficient to scan all documents in a\n      // collection, rather than to perform individual lookups.\n      return PersistencePromise.resolve<DocumentMap | null>(null);\n    }\n\n    let target = queryToTarget(query);\n    return this.indexManager\n      .getIndexType(transaction, target)\n      .next(indexType => {\n        if (indexType === IndexType.NONE) {\n          // The target cannot be served from any index.\n          return null;\n        }\n\n        if (query.limit !== null && indexType === IndexType.PARTIAL) {\n          // We cannot apply a limit for targets that are served using a partial\n          // index. If a partial index will be used to serve the target, the\n          // query may return a superset of documents that match the target\n          // (e.g. if the index doesn't include all the target's filters), or\n          // may return the correct set of documents in the wrong order (e.g. if\n          // the index doesn't include a segment for one of the orderBys).\n          // Therefore, a limit should not be applied in such cases.\n          query = queryWithLimit(query, null, LimitType.First);\n          target = queryToTarget(query);\n        }\n\n        return this.indexManager\n          .getDocumentsMatchingTarget(transaction, target)\n          .next(keys => {\n            debugAssert(\n              !!keys,\n              'Index manager must return results for partial and full indexes.'\n            );\n            const sortedKeys = documentKeySet(...keys);\n            return this.localDocumentsView\n              .getDocuments(transaction, sortedKeys)\n              .next(indexedDocuments => {\n                return this.indexManager\n                  .getMinOffset(transaction, target)\n                  .next(offset => {\n                    const previousResults = this.applyQuery(\n                      query,\n                      indexedDocuments\n                    );\n\n                    if (\n                      this.needsRefill(\n                        query,\n                        previousResults,\n                        sortedKeys,\n                        offset.readTime\n                      )\n                    ) {\n                      // A limit query whose boundaries change due to local\n                      // edits can be re-run against the cache by excluding the\n                      // limit. This ensures that all documents that match the\n                      // query's filters are included in the result set. The SDK\n                      // can then apply the limit once all local edits are\n                      // incorporated.\n                      return this.performQueryUsingIndex(\n                        transaction,\n                        queryWithLimit(query, null, LimitType.First)\n                      );\n                    }\n\n                    return this.appendRemainingResults(\n                      transaction,\n                      previousResults,\n                      query as Query,\n                      offset\n                    ) as PersistencePromise<DocumentMap | null>;\n                  });\n              });\n          });\n      });\n  }\n\n  /**\n   * Performs a query based on the target's persisted query mapping. Returns\n   * `null` if the mapping is not available or cannot be used.\n   */\n  private performQueryUsingRemoteKeys(\n    transaction: PersistenceTransaction,\n    query: QueryOrPipeline,\n    remoteKeys: DocumentKeySet,\n    lastLimboFreeSnapshotVersion: SnapshotVersion\n  ): PersistencePromise<DocumentMap | null> {\n    if (\n      isPipeline(query)\n        ? pipelineMatchesAllDocuments(query)\n        : queryMatchesAllDocuments(query)\n    ) {\n      // Queries that match all documents don't benefit from using\n      // key-based lookups. It is more efficient to scan all documents in a\n      // collection, rather than to perform individual lookups.\n      return PersistencePromise.resolve<DocumentMap | null>(null);\n    }\n\n    // Queries that have never seen a snapshot without limbo free documents\n    // should also be run as a full collection scan.\n    if (lastLimboFreeSnapshotVersion.isEqual(SnapshotVersion.min())) {\n      return PersistencePromise.resolve<DocumentMap | null>(null);\n    }\n\n    return this.localDocumentsView!.getDocuments(transaction, remoteKeys).next(\n      documents => {\n        const previousResults = this.applyQuery(query, documents);\n\n        if (\n          this.needsRefill(\n            query,\n            previousResults,\n            remoteKeys,\n            lastLimboFreeSnapshotVersion\n          )\n        ) {\n          return PersistencePromise.resolve<DocumentMap | null>(null);\n        }\n\n        if (getLogLevel() <= LogLevel.DEBUG) {\n          logDebug(\n            'QueryEngine',\n            'Re-using previous result from %s to execute query: %s',\n            lastLimboFreeSnapshotVersion.toString(),\n            stringifyQueryOrPipeline(query)\n          );\n        }\n\n        // Retrieve all results for documents that were updated since the last\n        // limbo-document free remote snapshot.\n        return this.appendRemainingResults(\n          transaction,\n          previousResults,\n          query,\n          newIndexOffsetSuccessorFromReadTime(\n            lastLimboFreeSnapshotVersion,\n            INITIAL_LARGEST_BATCH_ID\n          )\n        ).next<DocumentMap | null>(results => results);\n      }\n    );\n  }\n\n  /** Applies the query filter and sorting to the provided documents.  */\n  private applyQuery(\n    query: QueryOrPipeline,\n    documents: DocumentMap\n  ): SortedSet<Document> {\n    let queryResults: SortedSet<Document>;\n    let matcher: (doc: Document) => boolean;\n    if (isPipeline(query)) {\n      // TODO(pipeline): the order here does not actually matter, not until we implement\n      // refill logic for pipelines as well.\n      queryResults = new SortedSet<Document>(compareByKey);\n      matcher = doc => pipelineMatches(query, doc as MutableDocument);\n    } else {\n      // Sort the documents and re-apply the query filter since previously\n      // matching documents do not necessarily still match the query.\n      queryResults = new SortedSet<Document>(newQueryComparator(query));\n      matcher = doc => queryMatches(query, doc);\n    }\n\n    documents.forEach((_, maybeDoc) => {\n      if (matcher(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: QueryOrPipeline,\n    sortedPreviousResults: SortedSet<Document>,\n    remoteKeys: DocumentKeySet,\n    limboFreeSnapshotVersion: SnapshotVersion\n  ): boolean {\n    // TODO(pipeline): For pipelines it is simple for now, we refill for all limit/offset.\n    // we should implement a similar approach for query at some point.\n    if (isPipeline(query)) {\n      return pipelineHasRanges(query);\n    }\n\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: QueryOrPipeline,\n    context: QueryContext\n  ): PersistencePromise<DocumentMap> {\n    if (getLogLevel() <= LogLevel.DEBUG) {\n      logDebug(\n        'QueryEngine',\n        'Using full collection scan to execute query:',\n        stringifyQueryOrPipeline(query)\n      );\n    }\n\n    return this.localDocumentsView!.getDocumentsMatchingQuery(\n      transaction,\n      query,\n      IndexOffset.min(),\n      context\n    );\n  }\n\n  /**\n   * Combines the results from an indexed execution with the remaining documents\n   * that have not yet been indexed.\n   */\n  private appendRemainingResults(\n    transaction: PersistenceTransaction,\n    indexedResults: Iterable<Document>,\n    query: QueryOrPipeline,\n    offset: IndexOffset\n  ): PersistencePromise<DocumentMap> {\n    // Retrieve all results for documents that were updated since the offset.\n    return this.localDocumentsView\n      .getDocumentsMatchingQuery(transaction, query, offset)\n      .next(remainingResults => {\n        // Merge with existing results\n        indexedResults.forEach(d => {\n          remainingResults = remainingResults.insert(d.key, d);\n        });\n        return remainingResults;\n      });\n  }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { BatchId, MutationBatchState, TargetId } from '../core/types';\nimport { debugAssert } from '../util/assert';\n\nimport { ClientId } from './shared_client_state';\nimport { QueryTargetState } from './shared_client_state_syncer';\n\n// The format of the LocalStorage key that stores the client state is:\n//     firestore_clients_<persistence_prefix>_<instance_key>\nexport const CLIENT_STATE_KEY_PREFIX = 'firestore_clients';\n\n/** Assembles the key for a client state in WebStorage */\nexport function createWebStorageClientStateKey(\n  persistenceKey: string,\n  clientId: ClientId\n): string {\n  debugAssert(\n    clientId.indexOf('_') === -1,\n    `Client key cannot contain '_', but was '${clientId}'`\n  );\n\n  return `${CLIENT_STATE_KEY_PREFIX}_${persistenceKey}_${clientId}`;\n}\n\n/**\n * The JSON representation of a clients's metadata as used during WebStorage\n * serialization. The ClientId is omitted here as it is encoded as part of the\n * key.\n */\nexport interface ClientStateSchema {\n  activeTargetIds: number[];\n  updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n//     firestore_mutations_<persistence_prefix>_<batch_id>\n//     (for unauthenticated users)\n// or: firestore_mutations_<persistence_prefix>_<batch_id>_<user_uid>\n//\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\nexport const MUTATION_BATCH_KEY_PREFIX = 'firestore_mutations';\n\n/** Assembles the key for a mutation batch in WebStorage */\nexport function createWebStorageMutationBatchKey(\n  persistenceKey: string,\n  user: User,\n  batchId: BatchId\n): string {\n  let mutationKey = `${MUTATION_BATCH_KEY_PREFIX}_${persistenceKey}_${batchId}`;\n\n  if (user.isAuthenticated()) {\n    mutationKey += `_${user.uid}`;\n  }\n\n  return mutationKey;\n}\n\n/**\n * The JSON representation of a mutation batch's metadata as used during\n * WebStorage serialization. The UserId and BatchId is omitted as it is\n * encoded as part of the key.\n */\nexport interface MutationMetadataSchema {\n  state: MutationBatchState;\n  error?: { code: string; message: string }; // Only set when state === 'rejected'\n  updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n//     firestore_targets_<persistence_prefix>_<target_id>\nexport const QUERY_TARGET_KEY_PREFIX = 'firestore_targets';\n\n/** Assembles the key for a query state in WebStorage */\nexport function createWebStorageQueryTargetMetadataKey(\n  persistenceKey: string,\n  targetId: TargetId\n): string {\n  return `${QUERY_TARGET_KEY_PREFIX}_${persistenceKey}_${targetId}`;\n}\n\n/**\n * The JSON representation of a query target's state as used during WebStorage\n * serialization. The TargetId is omitted as it is encoded as part of the key.\n */\nexport interface QueryTargetStateSchema {\n  state: QueryTargetState;\n  error?: { code: string; message: string }; // Only set when state === 'rejected'\n  updateTimeMs: number;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n//     firestore_online_state_<persistence_prefix>\nexport const ONLINE_STATE_KEY_PREFIX = 'firestore_online_state';\n\n/** Assembles the key for the online state of the primary tab. */\nexport function createWebStorageOnlineStateKey(persistenceKey: string): string {\n  return `${ONLINE_STATE_KEY_PREFIX}_${persistenceKey}`;\n}\n\n// The WebStorage prefix that plays as a event to indicate the remote documents\n// might have changed due to some secondary tabs loading a bundle.\n// format of the key is:\n//     firestore_bundle_loaded_v2_<persistenceKey>\n// The version ending with \"v2\" stores the list of modified collection groups.\nexport const BUNDLE_LOADED_KEY_PREFIX = 'firestore_bundle_loaded_v2';\nexport function createBundleLoadedKey(persistenceKey: string): string {\n  return `${BUNDLE_LOADED_KEY_PREFIX}_${persistenceKey}`;\n}\n\n/**\n * The JSON representation of the system's online state, as written by the\n * primary client.\n */\nexport interface SharedOnlineStateSchema {\n  /**\n   * The clientId of the client that wrote this onlineState value. Tracked so\n   * that on startup, clients can check if this client is still active when\n   * determining whether to apply this value or not.\n   */\n  readonly clientId: string;\n  readonly onlineState: string;\n}\n\n// The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n// looks like 'firestore_sequence_number_<persistence_prefix>'.\nexport const SEQUENCE_NUMBER_KEY_PREFIX = 'firestore_sequence_number';\n\n/** Assembles the key for the current sequence number. */\nexport function createWebStorageSequenceNumberKey(\n  persistenceKey: string\n): string {\n  return `${SEQUENCE_NUMBER_KEY_PREFIX}_${persistenceKey}`;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport {\n  BatchId,\n  ListenSequenceNumber,\n  MutationBatchState,\n  OnlineState,\n  TargetId\n} from '../core/types';\nimport { TargetIdSet, targetIdSet } from '../model/collections';\nimport { hardAssert, debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { isSafeInteger, WindowLike } from '../util/types';\n\nimport {\n  CLIENT_STATE_KEY_PREFIX,\n  ClientStateSchema,\n  createBundleLoadedKey,\n  createWebStorageClientStateKey,\n  createWebStorageMutationBatchKey,\n  createWebStorageOnlineStateKey,\n  createWebStorageQueryTargetMetadataKey,\n  createWebStorageSequenceNumberKey,\n  MUTATION_BATCH_KEY_PREFIX,\n  MutationMetadataSchema,\n  QUERY_TARGET_KEY_PREFIX,\n  QueryTargetStateSchema,\n  SharedOnlineStateSchema\n} from './shared_client_state_schema';\nimport {\n  QueryTargetState,\n  SharedClientStateSyncer\n} from './shared_client_state_syncer';\n\nconst LOG_TAG = 'SharedClientState';\n\n/**\n * A randomly-generated key assigned to each Firestore instance at startup.\n */\nexport type ClientId = string;\n\n/**\n * A `SharedClientState` keeps track of the global state of the mutations\n * and query targets for all active clients with the same persistence key (i.e.\n * project ID and FirebaseApp name). It relays local changes to other clients\n * and updates its local state as new state is observed.\n *\n * `SharedClientState` is primarily used for synchronization in Multi-Tab\n * environments. Each tab is responsible for registering its active query\n * targets and mutations. `SharedClientState` will then notify the listener\n * assigned to `.syncEngine` for updates to mutations and queries that\n * originated in other clients.\n *\n * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be\n * assigned before calling `start()`.\n */\nexport interface SharedClientState {\n  onlineStateHandler: ((onlineState: OnlineState) => void) | null;\n  sequenceNumberHandler:\n    | ((sequenceNumber: ListenSequenceNumber) => void)\n    | null;\n\n  /** Registers the Mutation Batch ID of a newly pending mutation. */\n  addPendingMutation(batchId: BatchId): void;\n\n  /**\n   * Records that a pending mutation has been acknowledged or rejected.\n   * Called by the primary client to notify secondary clients of mutation\n   * results as they come back from the backend.\n   */\n  updateMutationState(\n    batchId: BatchId,\n    state: 'acknowledged' | 'rejected',\n    error?: FirestoreError\n  ): void;\n\n  /**\n   * Associates a new Query Target ID with the local Firestore client. Returns\n   * the new query state for the query (which can be 'current' if the query is\n   * already associated with another tab).\n   *\n   * If the target id is already associated with local client, the method simply\n   * returns its `QueryTargetState`.\n   */\n  addLocalQueryTarget(\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<TargetId>;\n\n  /**\n   * Checks whether the provided target ID is currently being listened to by\n   * any of the active clients.\n   *\n   * The implementation may require O(n*log m) runtime, where 'n' is the number\n   * of clients and 'm' the number of targets.\n   */\n  isActiveQueryTarget(targetId: TargetId): boolean;\n\n  /**\n   * Starts the SharedClientState, reads existing client data and registers\n   * listeners for updates to new and existing clients.\n   */\n  start(): Promise<void>;\n\n  /** Shuts down the `SharedClientState` and its listeners. */\n  shutdown(): void;\n\n  /**\n   * Changes the active user and removes all existing user-specific data. The\n   * user change does not call back into SyncEngine (for example, no mutations\n   * will be marked as removed).\n   */\n  handleUserChange(\n    user: User,\n    removedBatchIds: BatchId[],\n    addedBatchIds: BatchId[]\n  ): void;\n\n  /** Changes the shared online state of all clients. */\n  setOnlineState(onlineState: OnlineState): void;\n\n  writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n\n  /**\n   * Notifies other clients when remote documents have changed due to loading\n   * a bundle.\n   *\n   * @param collectionGroups - The collection groups affected by this bundle.\n   */\n  notifyBundleLoaded(collectionGroups: Set<string>): void;\n}\n\n/**\n * Holds the state of a mutation batch, including its user ID, batch ID and\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\n */\n// Visible for testing\nexport class MutationMetadata {\n  constructor(\n    readonly user: User,\n    readonly batchId: BatchId,\n    readonly state: MutationBatchState,\n    readonly error?: FirestoreError\n  ) {\n    debugAssert(\n      (error !== undefined) === (state === 'rejected'),\n      `MutationMetadata must contain an error iff state is 'rejected'`\n    );\n  }\n\n  /**\n   * Parses a MutationMetadata from its JSON representation in WebStorage.\n   * Logs a warning and returns null if the format of the data is not valid.\n   */\n  static fromWebStorageEntry(\n    user: User,\n    batchId: BatchId,\n    value: string\n  ): MutationMetadata | null {\n    const mutationBatch = JSON.parse(value) as MutationMetadataSchema;\n\n    let validData =\n      typeof mutationBatch === 'object' &&\n      ['pending', 'acknowledged', 'rejected'].indexOf(mutationBatch.state) !==\n        -1 &&\n      (mutationBatch.error === undefined ||\n        typeof mutationBatch.error === 'object');\n\n    let firestoreError: FirestoreError | undefined = undefined;\n\n    if (validData && mutationBatch.error) {\n      validData =\n        typeof mutationBatch.error.message === 'string' &&\n        typeof mutationBatch.error.code === 'string';\n      if (validData) {\n        firestoreError = new FirestoreError(\n          mutationBatch.error.code as Code,\n          mutationBatch.error.message\n        );\n      }\n    }\n\n    if (validData) {\n      return new MutationMetadata(\n        user,\n        batchId,\n        mutationBatch.state,\n        firestoreError\n      );\n    } else {\n      logError(\n        LOG_TAG,\n        `Failed to parse mutation state for ID '${batchId}': ${value}`\n      );\n      return null;\n    }\n  }\n\n  toWebStorageJSON(): string {\n    const batchMetadata: MutationMetadataSchema = {\n      state: this.state,\n      updateTimeMs: Date.now() // Modify the existing value to trigger update.\n    };\n\n    if (this.error) {\n      batchMetadata.error = {\n        code: this.error.code,\n        message: this.error.message\n      };\n    }\n\n    return JSON.stringify(batchMetadata);\n  }\n}\n\n/**\n * Holds the state of a query target, including its target ID and whether the\n * target is 'not-current', 'current' or 'rejected'.\n */\n// Visible for testing\nexport class QueryTargetMetadata {\n  constructor(\n    readonly targetId: TargetId,\n    readonly state: QueryTargetState,\n    readonly error?: FirestoreError\n  ) {\n    debugAssert(\n      (error !== undefined) === (state === 'rejected'),\n      `QueryTargetMetadata must contain an error iff state is 'rejected'`\n    );\n  }\n\n  /**\n   * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\n   * Logs a warning and returns null if the format of the data is not valid.\n   */\n  static fromWebStorageEntry(\n    targetId: TargetId,\n    value: string\n  ): QueryTargetMetadata | null {\n    const targetState = JSON.parse(value) as QueryTargetStateSchema;\n\n    let validData =\n      typeof targetState === 'object' &&\n      ['not-current', 'current', 'rejected'].indexOf(targetState.state) !==\n        -1 &&\n      (targetState.error === undefined ||\n        typeof targetState.error === 'object');\n\n    let firestoreError: FirestoreError | undefined = undefined;\n\n    if (validData && targetState.error) {\n      validData =\n        typeof targetState.error.message === 'string' &&\n        typeof targetState.error.code === 'string';\n      if (validData) {\n        firestoreError = new FirestoreError(\n          targetState.error.code as Code,\n          targetState.error.message\n        );\n      }\n    }\n\n    if (validData) {\n      return new QueryTargetMetadata(\n        targetId,\n        targetState.state,\n        firestoreError\n      );\n    } else {\n      logError(\n        LOG_TAG,\n        `Failed to parse target state for ID '${targetId}': ${value}`\n      );\n      return null;\n    }\n  }\n\n  toWebStorageJSON(): string {\n    const targetState: QueryTargetStateSchema = {\n      state: this.state,\n      updateTimeMs: Date.now() // Modify the existing value to trigger update.\n    };\n\n    if (this.error) {\n      targetState.error = {\n        code: this.error.code,\n        message: this.error.message\n      };\n    }\n\n    return JSON.stringify(targetState);\n  }\n}\n\n/**\n * Metadata state of a single client denoting the query targets it is actively\n * listening to 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<string, ClientState>(\n    primitiveComparator\n  );\n  private started = false;\n  private currentUser: User;\n\n  /**\n   * Captures WebStorage events that occur before `start()` is called. These\n   * events are replayed once `WebStorageSharedClientState` is started.\n   */\n  private earlyEvents: StorageEvent[] = [];\n\n  constructor(\n    private readonly window: WindowLike,\n    private readonly queue: AsyncQueue,\n    private readonly persistenceKey: string,\n    private readonly localClientId: ClientId,\n    initialUser: User\n  ) {\n    // Escape the special characters mentioned here:\n    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n    const escapedPersistenceKey = persistenceKey.replace(\n      /[.*+?^${}()|[\\]\\\\]/g,\n      '\\\\$&'\n    );\n\n    this.storage = this.window.localStorage;\n    this.currentUser = initialUser;\n    this.localClientStorageKey = createWebStorageClientStateKey(\n      this.persistenceKey,\n      this.localClientId\n    );\n    this.sequenceNumberKey = createWebStorageSequenceNumberKey(\n      this.persistenceKey\n    );\n    this.activeClients = this.activeClients.insert(\n      this.localClientId,\n      new LocalClientState()\n    );\n\n    this.clientStateKeyRe = new RegExp(\n      `^${CLIENT_STATE_KEY_PREFIX}_${escapedPersistenceKey}_([^_]*)$`\n    );\n    this.mutationBatchKeyRe = new RegExp(\n      `^${MUTATION_BATCH_KEY_PREFIX}_${escapedPersistenceKey}_(\\\\d+)(?:_(.*))?$`\n    );\n    this.queryTargetKeyRe = new RegExp(\n      `^${QUERY_TARGET_KEY_PREFIX}_${escapedPersistenceKey}_(\\\\d+)$`\n    );\n\n    this.onlineStateKey = createWebStorageOnlineStateKey(this.persistenceKey);\n\n    this.bundleLoadedKey = createBundleLoadedKey(this.persistenceKey);\n\n    // Rather than adding the storage observer during start(), we add the\n    // storage observer during initialization. This ensures that we collect\n    // events before other components populate their initial state (during their\n    // respective start() calls). Otherwise, we might for example miss a\n    // mutation that is added after LocalStore's start() processed the existing\n    // mutations but before we observe WebStorage events.\n    this.window.addEventListener('storage', this.storageListener);\n  }\n\n  /** Returns 'true' if WebStorage is available in the current environment. */\n  static isAvailable(window: WindowLike | null): window is WindowLike {\n    return !!(window && window.localStorage);\n  }\n\n  async start(): Promise<void> {\n    debugAssert(!this.started, 'WebStorageSharedClientState already started');\n    debugAssert(\n      this.syncEngine !== null,\n      'syncEngine property must be set before calling start()'\n    );\n    debugAssert(\n      this.onlineStateHandler !== null,\n      'onlineStateHandler property must be set before calling start()'\n    );\n\n    // Retrieve the list of existing clients to backfill the data in\n    // SharedClientState.\n    const existingClients = await this.syncEngine!.getActiveClients();\n\n    for (const clientId of existingClients) {\n      if (clientId === this.localClientId) {\n        continue;\n      }\n\n      const storageItem = this.getItem(\n        createWebStorageClientStateKey(this.persistenceKey, clientId)\n      );\n      if (storageItem) {\n        const clientState = RemoteClientState.fromWebStorageEntry(\n          clientId,\n          storageItem\n        );\n        if (clientState) {\n          this.activeClients = this.activeClients.insert(\n            clientState.clientId,\n            clientState\n          );\n        }\n      }\n    }\n\n    this.persistClientState();\n\n    // Check if there is an existing online state and call the callback handler\n    // if applicable.\n    const onlineStateJSON = this.storage.getItem(this.onlineStateKey);\n    if (onlineStateJSON) {\n      const onlineState = this.fromWebStorageOnlineState(onlineStateJSON);\n      if (onlineState) {\n        this.handleOnlineStateEvent(onlineState);\n      }\n    }\n\n    for (const event of this.earlyEvents) {\n      this.handleWebStorageEvent(event);\n    }\n\n    this.earlyEvents = [];\n\n    // Register a window unload hook to remove the client metadata entry from\n    // WebStorage even if `shutdown()` was not called.\n    this.window.addEventListener('pagehide', () => this.shutdown());\n\n    this.started = true;\n  }\n\n  writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void {\n    this.setItem(this.sequenceNumberKey, JSON.stringify(sequenceNumber));\n  }\n\n  getAllActiveQueryTargets(): TargetIdSet {\n    return this.extractActiveQueryTargets(this.activeClients);\n  }\n\n  isActiveQueryTarget(targetId: TargetId): boolean {\n    let found = false;\n    this.activeClients.forEach((key, value) => {\n      if (value.activeTargetIds.has(targetId)) {\n        found = true;\n      }\n    });\n    return found;\n  }\n\n  addPendingMutation(batchId: BatchId): void {\n    this.persistMutationState(batchId, 'pending');\n  }\n\n  updateMutationState(\n    batchId: BatchId,\n    state: 'acknowledged' | 'rejected',\n    error?: FirestoreError\n  ): void {\n    this.persistMutationState(batchId, state, error);\n\n    // Once a final mutation result is observed by other clients, they no longer\n    // access the mutation's metadata entry. Since WebStorage replays events\n    // in order, it is safe to delete the entry right after updating it.\n    this.removeMutationState(batchId);\n  }\n\n  addLocalQueryTarget(\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<string>): void {\n    this.persistBundleLoadedState(collectionGroups);\n  }\n\n  shutdown(): void {\n    if (this.started) {\n      this.window.removeEventListener('storage', this.storageListener);\n      this.removeItem(this.localClientStorageKey);\n      this.started = false;\n    }\n  }\n\n  private getItem(key: string): string | null {\n    const value = this.storage.getItem(key);\n    logDebug(LOG_TAG, 'READ', key, value);\n    return value;\n  }\n\n  private setItem(key: string, value: string): void {\n    logDebug(LOG_TAG, 'SET', key, value);\n    this.storage.setItem(key, value);\n  }\n\n  private removeItem(key: string): void {\n    logDebug(LOG_TAG, 'REMOVE', key);\n    this.storage.removeItem(key);\n  }\n\n  private handleWebStorageEvent(event: Event): void {\n    // Note: The function is typed to take Event to be interface-compatible with\n    // `Window.addEventListener`.\n    const storageEvent = event as StorageEvent;\n    if (storageEvent.storageArea === this.storage) {\n      logDebug(LOG_TAG, 'EVENT', storageEvent.key, storageEvent.newValue);\n\n      if (storageEvent.key === this.localClientStorageKey) {\n        logError(\n          'Received WebStorage notification for local change. Another client might have ' +\n            'garbage-collected our state'\n        );\n        return;\n      }\n\n      this.queue.enqueueRetryable(async () => {\n        if (!this.started) {\n          this.earlyEvents.push(storageEvent);\n          return;\n        }\n\n        if (storageEvent.key === null) {\n          return;\n        }\n\n        if (this.clientStateKeyRe.test(storageEvent.key)) {\n          if (storageEvent.newValue != null) {\n            const clientState = this.fromWebStorageClientState(\n              storageEvent.key,\n              storageEvent.newValue\n            );\n            if (clientState) {\n              return this.handleClientStateEvent(\n                clientState.clientId,\n                clientState\n              );\n            }\n          } else {\n            const clientId = this.fromWebStorageClientStateKey(\n              storageEvent.key\n            )!;\n            return this.handleClientStateEvent(clientId, null);\n          }\n        } else if (this.mutationBatchKeyRe.test(storageEvent.key)) {\n          if (storageEvent.newValue !== null) {\n            const mutationMetadata = this.fromWebStorageMutationMetadata(\n              storageEvent.key,\n              storageEvent.newValue\n            );\n            if (mutationMetadata) {\n              return this.handleMutationBatchEvent(mutationMetadata);\n            }\n          }\n        } else if (this.queryTargetKeyRe.test(storageEvent.key)) {\n          if (storageEvent.newValue !== null) {\n            const queryTargetMetadata = this.fromWebStorageQueryTargetMetadata(\n              storageEvent.key,\n              storageEvent.newValue\n            );\n            if (queryTargetMetadata) {\n              return this.handleQueryTargetEvent(queryTargetMetadata);\n            }\n          }\n        } else if (storageEvent.key === this.onlineStateKey) {\n          if (storageEvent.newValue !== null) {\n            const onlineState = this.fromWebStorageOnlineState(\n              storageEvent.newValue\n            );\n            if (onlineState) {\n              return this.handleOnlineStateEvent(onlineState);\n            }\n          }\n        } else if (storageEvent.key === this.sequenceNumberKey) {\n          debugAssert(\n            !!this.sequenceNumberHandler,\n            'Missing sequenceNumberHandler'\n          );\n          const sequenceNumber = fromWebStorageSequenceNumber(\n            storageEvent.newValue\n          );\n          if (sequenceNumber !== ListenSequence.INVALID) {\n            this.sequenceNumberHandler!(sequenceNumber);\n          }\n        } else if (storageEvent.key === this.bundleLoadedKey) {\n          const collectionGroups = this.fromWebStoreBundleLoadedState(\n            storageEvent.newValue!\n          );\n          await Promise.all(\n            collectionGroups.map(cg =>\n              this.syncEngine!.synchronizeWithChangedDocuments(cg)\n            )\n          );\n        }\n      });\n    }\n  }\n\n  private get localClientState(): LocalClientState {\n    return this.activeClients.get(this.localClientId) as LocalClientState;\n  }\n\n  private persistClientState(): void {\n    this.setItem(\n      this.localClientStorageKey,\n      this.localClientState.toWebStorageJSON()\n    );\n  }\n\n  private persistMutationState(\n    batchId: BatchId,\n    state: MutationBatchState,\n    error?: FirestoreError\n  ): void {\n    const mutationState = new MutationMetadata(\n      this.currentUser,\n      batchId,\n      state,\n      error\n    );\n    const mutationKey = createWebStorageMutationBatchKey(\n      this.persistenceKey,\n      this.currentUser,\n      batchId\n    );\n    this.setItem(mutationKey, mutationState.toWebStorageJSON());\n  }\n\n  private removeMutationState(batchId: BatchId): void {\n    const mutationKey = createWebStorageMutationBatchKey(\n      this.persistenceKey,\n      this.currentUser,\n      batchId\n    );\n    this.removeItem(mutationKey);\n  }\n\n  private persistOnlineState(onlineState: OnlineState): void {\n    const entry: SharedOnlineStateSchema = {\n      clientId: this.localClientId,\n      onlineState\n    };\n    this.storage.setItem(this.onlineStateKey, JSON.stringify(entry));\n  }\n\n  private persistQueryTargetState(\n    targetId: TargetId,\n    state: QueryTargetState,\n    error?: FirestoreError\n  ): void {\n    const targetKey = createWebStorageQueryTargetMetadataKey(\n      this.persistenceKey,\n      targetId\n    );\n    const targetMetadata = new QueryTargetMetadata(targetId, state, error);\n    this.setItem(targetKey, targetMetadata.toWebStorageJSON());\n  }\n\n  private persistBundleLoadedState(collectionGroups: Set<string>): void {\n    const json = JSON.stringify(Array.from(collectionGroups));\n    this.setItem(this.bundleLoadedKey, json);\n  }\n\n  /**\n   * Parses a client state key in WebStorage. Returns null if the key does not\n   * match the expected key format.\n   */\n  private fromWebStorageClientStateKey(key: string): ClientId | null {\n    const match = this.clientStateKeyRe.exec(key);\n    return match ? match[1] : null;\n  }\n\n  /**\n   * Parses a client state in WebStorage. Returns 'null' if the value could not\n   * be parsed.\n   */\n  private fromWebStorageClientState(\n    key: string,\n    value: string\n  ): RemoteClientState | null {\n    const clientId = this.fromWebStorageClientStateKey(key);\n    debugAssert(clientId !== null, `Cannot parse client state key '${key}'`);\n    return RemoteClientState.fromWebStorageEntry(clientId, value);\n  }\n\n  /**\n   * Parses a mutation batch state in WebStorage. Returns 'null' if the value\n   * could not be parsed.\n   */\n  private fromWebStorageMutationMetadata(\n    key: string,\n    value: string\n  ): MutationMetadata | null {\n    const match = this.mutationBatchKeyRe.exec(key);\n    debugAssert(match !== null, `Cannot parse mutation batch key '${key}'`);\n\n    const batchId = Number(match[1]);\n    const userId = match[2] !== undefined ? match[2] : null;\n    return MutationMetadata.fromWebStorageEntry(\n      new User(userId),\n      batchId,\n      value\n    );\n  }\n\n  /**\n   * Parses a query target state from WebStorage. Returns 'null' if the value\n   * could not be parsed.\n   */\n  private fromWebStorageQueryTargetMetadata(\n    key: string,\n    value: string\n  ): QueryTargetMetadata | null {\n    const match = this.queryTargetKeyRe.exec(key);\n    debugAssert(match !== null, `Cannot parse query target key '${key}'`);\n\n    const targetId = Number(match[1]);\n    return QueryTargetMetadata.fromWebStorageEntry(targetId, value);\n  }\n\n  /**\n   * Parses an online state from WebStorage. Returns 'null' if the value\n   * could not be parsed.\n   */\n  private fromWebStorageOnlineState(value: string): SharedOnlineState | null {\n    return SharedOnlineState.fromWebStorageEntry(value);\n  }\n\n  private fromWebStoreBundleLoadedState(value: string): string[] {\n    return JSON.parse(value) as string[];\n  }\n\n  private async handleMutationBatchEvent(\n    mutationBatch: MutationMetadata\n  ): Promise<void> {\n    if (mutationBatch.user.uid !== this.currentUser.uid) {\n      logDebug(\n        LOG_TAG,\n        `Ignoring mutation for non-active user ${mutationBatch.user.uid}`\n      );\n      return;\n    }\n\n    return this.syncEngine!.applyBatchState(\n      mutationBatch.batchId,\n      mutationBatch.state,\n      mutationBatch.error\n    );\n  }\n\n  private handleQueryTargetEvent(\n    targetMetadata: QueryTargetMetadata\n  ): Promise<void> {\n    return this.syncEngine!.applyTargetState(\n      targetMetadata.targetId,\n      targetMetadata.state,\n      targetMetadata.error\n    );\n  }\n\n  private handleClientStateEvent(\n    clientId: ClientId,\n    clientState: RemoteClientState | null\n  ): Promise<void> {\n    const updatedClients = clientState\n      ? this.activeClients.insert(clientId, clientState)\n      : this.activeClients.remove(clientId);\n\n    const existingTargets = this.extractActiveQueryTargets(this.activeClients);\n    const newTargets = this.extractActiveQueryTargets(updatedClients);\n\n    const addedTargets: TargetId[] = [];\n    const removedTargets: TargetId[] = [];\n\n    newTargets.forEach(targetId => {\n      if (!existingTargets.has(targetId)) {\n        addedTargets.push(targetId);\n      }\n    });\n\n    existingTargets.forEach(targetId => {\n      if (!newTargets.has(targetId)) {\n        removedTargets.push(targetId);\n      }\n    });\n\n    return this.syncEngine!.applyActiveTargetsChange(\n      addedTargets,\n      removedTargets\n    ).then(() => {\n      this.activeClients = updatedClients;\n    });\n  }\n\n  private handleOnlineStateEvent(onlineState: SharedOnlineState): void {\n    // We check whether the client that wrote this online state is still active\n    // by comparing its client ID to the list of clients kept active in\n    // IndexedDb. If a client does not update their IndexedDb client state\n    // within 5 seconds, it is considered inactive and we don't emit an online\n    // state event.\n    if (this.activeClients.get(onlineState.clientId)) {\n      this.onlineStateHandler!(onlineState.onlineState);\n    }\n  }\n\n  private extractActiveQueryTargets(\n    clients: SortedMap<string, ClientState>\n  ): SortedSet<TargetId> {\n    let activeTargets = targetIdSet();\n    clients.forEach((kev, value) => {\n      activeTargets = activeTargets.unionWith(value.activeTargetIds);\n    });\n    return activeTargets;\n  }\n}\n\nfunction fromWebStorageSequenceNumber(\n  seqString: string | null\n): ListenSequenceNumber {\n  let sequenceNumber = ListenSequence.INVALID;\n  if (seqString != null) {\n    try {\n      const parsed = JSON.parse(seqString);\n      hardAssert(\n        typeof parsed === 'number',\n        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<void> {\n    this.localState = new LocalClientState();\n    return Promise.resolve();\n  }\n\n  handleUserChange(\n    user: User,\n    removedBatchIds: BatchId[],\n    addedBatchIds: BatchId[]\n  ): void {\n    // No op.\n  }\n\n  setOnlineState(onlineState: OnlineState): void {\n    // No op.\n  }\n\n  shutdown(): void {}\n\n  writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void {}\n\n  notifyBundleLoaded(collectionGroups: Set<string>): void {\n    // No op.\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OnlineState } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\n\nconst LOG_TAG = 'OnlineStateTracker';\n\n// To deal with transient failures, we allow multiple stream attempts before\n// giving up and transitioning from OnlineState.Unknown to Offline.\n// TODO(mikelehen): This used to be set to 2 as a mitigation for b/66228394.\n// @jdimond thinks that bug is sufficiently fixed so that we can set this back\n// to 1. If that works okay, we could potentially remove this logic entirely.\nconst MAX_WATCH_STREAM_FAILURES = 1;\n\n// To deal with stream attempts that don't succeed or fail in a timely manner,\n// we have a timeout for OnlineState to reach Online or Offline.\n// If the timeout is reached, we transition to Offline rather than waiting\n// indefinitely.\nconst ONLINE_STATE_TIMEOUT_MS = 10 * 1000;\n\n/**\n * A component used by the RemoteStore to track the OnlineState (that is,\n * whether or not the client as a whole should be considered to be online or\n * offline), implementing the appropriate heuristics.\n *\n * In particular, when the client is trying to connect to the backend, we\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\n * a connection to succeed. If we have too many failures or the timeout elapses,\n * then we set the OnlineState to Offline, and the client will behave as if\n * it is offline (get()s will return cached data, etc.).\n */\nexport class OnlineStateTracker {\n  /** The current OnlineState. */\n  private state = OnlineState.Unknown;\n\n  /**\n   * A count of consecutive failures to open the stream. If it reaches the\n   * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\n   * Offline.\n   */\n  private watchStreamFailures = 0;\n\n  /**\n   * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\n   * transition from OnlineState.Unknown to OnlineState.Offline without waiting\n   * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\n   */\n  private onlineStateTimer: DelayedOperation<void> | null = null;\n\n  /**\n   * Whether the client should log a warning message if it fails to connect to\n   * the backend (initially true, cleared after a successful stream, or if we've\n   * logged the message already).\n   */\n  private shouldWarnClientIsOffline = true;\n\n  constructor(\n    private asyncQueue: AsyncQueue,\n    private onlineStateHandler: (onlineState: OnlineState) => void\n  ) {}\n\n  /**\n   * Called by RemoteStore when a watch stream is started (including on each\n   * backoff attempt).\n   *\n   * If this is the first attempt, it sets the OnlineState to Unknown and starts\n   * the onlineStateTimer.\n   */\n  handleWatchStreamStart(): void {\n    if (this.watchStreamFailures === 0) {\n      this.setAndBroadcast(OnlineState.Unknown);\n\n      debugAssert(\n        this.onlineStateTimer === null,\n        `onlineStateTimer shouldn't be started yet`\n      );\n      this.onlineStateTimer = this.asyncQueue.enqueueAfterDelay(\n        TimerId.OnlineStateTimeout,\n        ONLINE_STATE_TIMEOUT_MS,\n        () => {\n          this.onlineStateTimer = null;\n          debugAssert(\n            this.state === OnlineState.Unknown,\n            'Timer should be canceled if we transitioned to a different state.'\n          );\n          this.logClientOfflineWarningIfNecessary(\n            `Backend didn't respond within ${ONLINE_STATE_TIMEOUT_MS / 1000} ` +\n              `seconds.`\n          );\n          this.setAndBroadcast(OnlineState.Offline);\n\n          // NOTE: handleWatchStreamFailure() will continue to increment\n          // watchStreamFailures even though we are already marked Offline,\n          // but this is non-harmful.\n\n          return Promise.resolve();\n        }\n      );\n    }\n  }\n\n  /**\n   * Updates our OnlineState as appropriate after the watch stream reports a\n   * failure. The first failure moves us to the 'Unknown' state. We then may\n   * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\n   * actually transition to the 'Offline' state.\n   */\n  handleWatchStreamFailure(error: FirestoreError): void {\n    if (this.state === OnlineState.Online) {\n      this.setAndBroadcast(OnlineState.Unknown);\n\n      // To get to OnlineState.Online, set() must have been called which would\n      // have reset our heuristics.\n      debugAssert(\n        this.watchStreamFailures === 0,\n        'watchStreamFailures must be 0'\n      );\n      debugAssert(\n        this.onlineStateTimer === null,\n        'onlineStateTimer must be null'\n      );\n    } else {\n      this.watchStreamFailures++;\n      if (this.watchStreamFailures >= MAX_WATCH_STREAM_FAILURES) {\n        this.clearOnlineStateTimer();\n\n        this.logClientOfflineWarningIfNecessary(\n          `Connection failed ${MAX_WATCH_STREAM_FAILURES} ` +\n            `times. Most recent error: ${error.toString()}`\n        );\n\n        this.setAndBroadcast(OnlineState.Offline);\n      }\n    }\n  }\n\n  /**\n   * Explicitly sets the OnlineState to the specified state.\n   *\n   * Note that this resets our timers / failure counters, etc. used by our\n   * Offline heuristics, so must not be used in place of\n   * handleWatchStreamStart() and handleWatchStreamFailure().\n   */\n  set(newState: OnlineState): void {\n    this.clearOnlineStateTimer();\n    this.watchStreamFailures = 0;\n\n    if (newState === OnlineState.Online) {\n      // We've connected to watch at least once. Don't warn the developer\n      // about being offline going forward.\n      this.shouldWarnClientIsOffline = false;\n    }\n\n    this.setAndBroadcast(newState);\n  }\n\n  private setAndBroadcast(newState: OnlineState): void {\n    if (newState !== this.state) {\n      this.state = newState;\n      this.onlineStateHandler(newState);\n    }\n  }\n\n  private logClientOfflineWarningIfNecessary(details: string): void {\n    const message =\n      `Could not reach Cloud Firestore backend. ${details}\\n` +\n      `This typically indicates that your device does not have a healthy ` +\n      `Internet connection at the moment. The client will operate in offline ` +\n      `mode until it is able to successfully connect to the backend.`;\n    if (this.shouldWarnClientIsOffline) {\n      logError(message);\n      this.shouldWarnClientIsOffline = false;\n    } else {\n      logDebug(LOG_TAG, message);\n    }\n  }\n\n  private clearOnlineStateTimer(): void {\n    if (this.onlineStateTimer !== null) {\n      this.onlineStateTimer.cancel();\n      this.onlineStateTimer = null;\n    }\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { OnlineState, RemoteTargetId, 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, TargetPurpose } from '../local/target_data';\nimport { documentKeySet } from '../model/collections';\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 { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\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 { RemoteEvent, TargetChange } from './remote_event';\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<RemoteTargetId, TargetData<RemoteTargetId>>();\n\n  targetIdMapSdkToRemote = new Map<TargetId, RemoteTargetId>();\n  targetIdMapRemoteToSdk = new Map<RemoteTargetId, TargetId>();\n  targetCacheTargetIdGenerator = new TargetIdGenerator<RemoteTargetId>(1000);\n  syncEngineTargetIdGenerator = new TargetIdGenerator<RemoteTargetId>(1001);\n\n  connectivityMonitor: ConnectivityMonitor;\n  watchStream?: PersistentListenStream;\n  writeStream?: PersistentWriteStream;\n  watchChangeAggregator?: WatchChangeAggregator;\n\n  /**\n   * A set of reasons for why the RemoteStore may be offline. If empty, the\n   * RemoteStore may start its network connections.\n   */\n  offlineCauses = new Set<OfflineCause>();\n\n  /**\n   * Event handlers that get called when the network is disabled or enabled.\n   *\n   * PORTING NOTE: These functions are used on the Web client to create the\n   * underlying streams (to support tree-shakeable streams). On Android and iOS,\n   * the streams are created during construction of RemoteStore.\n   */\n  onNetworkStatusChange: Array<(enabled: boolean) => Promise<void>> = [];\n\n  onlineStateTracker: OnlineStateTracker;\n\n  constructor(\n    /**\n     * The local store, used to fill the write pipeline with outbound mutations.\n     */\n    readonly localStore: LocalStore,\n    /** The client-side proxy for interacting with the backend. */\n    readonly datastore: Datastore,\n    readonly asyncQueue: AsyncQueue,\n    onlineStateHandler: (onlineState: OnlineState) => void,\n    connectivityMonitor: ConnectivityMonitor\n  ) {\n    this.connectivityMonitor = connectivityMonitor;\n    this.connectivityMonitor.addCallback((_: NetworkStatus) => {\n      asyncQueue.enqueueAndForget(async () => {\n        // Porting Note: Unlike iOS, `restartNetwork()` is called even when the\n        // network becomes unreachable as we don't have any other way to tear\n        // down our streams.\n        if (canUseNetwork(this)) {\n          logDebug(\n            LOG_TAG,\n            'Restarting streams for network reachability change.'\n          );\n          await restartNetwork(this);\n        }\n      });\n    });\n\n    this.onlineStateTracker = new OnlineStateTracker(\n      asyncQueue,\n      onlineStateHandler\n    );\n  }\n}\n\nexport function newRemoteStore(\n  localStore: LocalStore,\n  datastore: Datastore,\n  asyncQueue: AsyncQueue,\n  onlineStateHandler: (onlineState: OnlineState) => void,\n  connectivityMonitor: ConnectivityMonitor\n): RemoteStore {\n  return new RemoteStoreImpl(\n    localStore,\n    datastore,\n    asyncQueue,\n    onlineStateHandler,\n    connectivityMonitor\n  );\n}\n\n/** Re-enables the network. Idempotent. */\nexport function remoteStoreEnableNetwork(\n  remoteStore: RemoteStore\n): Promise<void> {\n  const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n  remoteStoreImpl.offlineCauses.delete(OfflineCause.UserDisabled);\n  return enableNetworkInternal(remoteStoreImpl);\n}\n\nasync function enableNetworkInternal(\n  remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n  if (canUseNetwork(remoteStoreImpl)) {\n    for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) {\n      await networkStatusHandler(/* enabled= */ true);\n    }\n  }\n}\n\n/**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */\nexport async function remoteStoreDisableNetwork(\n  remoteStore: RemoteStore\n): Promise<void> {\n  const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n  remoteStoreImpl.offlineCauses.add(OfflineCause.UserDisabled);\n  await disableNetworkInternal(remoteStoreImpl);\n\n  // Set the OnlineState to Offline so get()s return from cache, etc.\n  remoteStoreImpl.onlineStateTracker.set(OnlineState.Offline);\n}\n\nasync function disableNetworkInternal(\n  remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n  for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) {\n    await networkStatusHandler(/* enabled= */ false);\n  }\n}\n\nexport async function remoteStoreShutdown(\n  remoteStore: RemoteStore\n): Promise<void> {\n  const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n  logDebug(LOG_TAG, 'RemoteStore shutting down.');\n  remoteStoreImpl.offlineCauses.add(OfflineCause.Shutdown);\n  await disableNetworkInternal(remoteStoreImpl);\n  remoteStoreImpl.connectivityMonitor.shutdown();\n\n  // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n  // triggering spurious listener events with cached data, etc.\n  remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n}\n\n/**\n * Returns the remote target ID currently mapped to this\n * sdkTargetId. Or returns `0` if the SDK target ID\n * is not currently mapped.\n * @param remoteStoreImpl\n * @param sdkTargetId\n */\nfunction getRemoteTargetId(\n  remoteStoreImpl: RemoteStoreImpl,\n  sdkTargetId: TargetId\n): RemoteTargetId | undefined {\n  return remoteStoreImpl.targetIdMapSdkToRemote.get(sdkTargetId) || undefined;\n}\n\n/**\n * Returns the remote target ID currently mapped to this\n * sdkTargetId. Exposed for testing.\n */\nexport function remoteStoreGetRemoteTargetId(\n  remoteStore: RemoteStore,\n  sdkTargetId: TargetId\n): RemoteTargetId | undefined {\n  const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n  return getRemoteTargetId(remoteStoreImpl, sdkTargetId);\n}\n\n/**\n * Generates a new remote target ID that is acceptable\n * to map to the given SDK target ID.\n * @param remoteStoreImpl\n * @param sdkTargetId\n */\nfunction generateRemoteTargetId(\n  remoteStoreImpl: RemoteStoreImpl,\n  sdkTargetId: TargetId\n): RemoteTargetId {\n  // If the given sdkTargetId is odd, map it to an odd (sync engine) target ID\n  if (sdkTargetId % 2 !== 0) {\n    return remoteStoreImpl.syncEngineTargetIdGenerator.next();\n  } else {\n    // If the given sdkTargetId is even, map it to an even (target cache) target ID\n    return remoteStoreImpl.targetCacheTargetIdGenerator.next();\n  }\n}\n\n/**\n * Generate a new remote target ID for the given SDK target ID.\n * Re-map the given SDK to the new remote ID.\n * Delete any mapping of the old remote ID, if given.\n * @param remoteStoreImpl\n * @param sdkTargetId\n * @return The new remote ID.\n */\nfunction allocateRemoteTargetId(\n  remoteStoreImpl: RemoteStoreImpl,\n  sdkTargetId: TargetId\n): RemoteTargetId {\n  const currentRemoteTargetId = getRemoteTargetId(remoteStoreImpl, sdkTargetId);\n\n  if (currentRemoteTargetId !== undefined) {\n    // If there was an existing remote target ID mapped to that SDK target ID, forget about the old remote ID.\n    remoteStoreImpl.targetIdMapRemoteToSdk.delete(currentRemoteTargetId);\n  }\n\n  // Generate a new unique remote target ID\n  const newRemoteTargetId = generateRemoteTargetId(\n    remoteStoreImpl,\n    sdkTargetId\n  );\n\n  remoteStoreImpl.targetIdMapSdkToRemote.set(sdkTargetId, newRemoteTargetId);\n  remoteStoreImpl.targetIdMapRemoteToSdk.set(newRemoteTargetId, sdkTargetId);\n  return newRemoteTargetId;\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  // Get any remote target ID currently mapped to the targetData\n  const currentRemoteTargetId = getRemoteTargetId(\n    remoteStoreImpl,\n    targetData.targetId\n  );\n\n  // If remote store is still listening for this remote target ID, this is a no-op.\n  if (\n    currentRemoteTargetId !== undefined &&\n    remoteStoreImpl.listenTargets.has(currentRemoteTargetId)\n  ) {\n    return;\n  }\n\n  // Generate and map a new remote ID to the SDK target ID\n  const remoteTargetId = allocateRemoteTargetId(\n    remoteStoreImpl,\n    targetData.targetId\n  );\n\n  logDebug(\n    LOG_TAG,\n    'remoteStoreListen mapping SDK target ID to remote',\n    targetData.targetId,\n    remoteTargetId\n  );\n\n  // Create a new TargetData for remote use, which uses\n  // the remote TargetID.\n  const remoteTargetData = new TargetData(\n    targetData.target,\n    remoteTargetId,\n    targetData.purpose,\n    targetData.sequenceNumber,\n    targetData.snapshotVersion,\n    targetData.lastLimboFreeSnapshotVersion,\n    targetData.resumeToken\n  );\n\n  // Mark this as something the client is currently listening for.\n  remoteStoreImpl.listenTargets.set(remoteTargetId, remoteTargetData);\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, remoteTargetData);\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  const remoteTargetId = getRemoteTargetId(remoteStoreImpl, targetId);\n  logDebug(\n    LOG_TAG,\n    'remoteStoreUnlisten removing mapping of SDK target ID to remote',\n    targetId,\n    remoteTargetId\n  );\n\n  debugAssert(\n    remoteTargetId !== undefined &&\n      remoteStoreImpl.listenTargets.has(remoteTargetId),\n    `unlisten called on target not currently watched: ${remoteTargetId}`\n  );\n\n  remoteStoreImpl.listenTargets.delete(remoteTargetId);\n  remoteStoreImpl.targetIdMapSdkToRemote.delete(targetId);\n  remoteStoreImpl.targetIdMapRemoteToSdk.delete(remoteTargetId);\n\n  if (watchStream.isOpen()) {\n    sendUnwatchRequest(remoteStoreImpl, remoteTargetId);\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  remoteTargetData: TargetData<RemoteTargetId>\n): void {\n  remoteStoreImpl.watchChangeAggregator!.recordPendingTargetRequest(\n    remoteTargetData.targetId\n  );\n\n  if (\n    remoteTargetData.resumeToken.approximateByteSize() > 0 ||\n    remoteTargetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0\n  ) {\n    const sdkTargetId = remoteStoreImpl.targetIdMapRemoteToSdk.get(\n      remoteTargetData.targetId as RemoteTargetId\n    );\n\n    if (sdkTargetId === undefined) {\n      logDebug(\n        LOG_TAG,\n        'SDK target ID not found for remote ID: ' + remoteTargetData.targetId\n      );\n\n      // There's already a new remoteStoreListen request for the original\n      // target, so ignore this.\n      return;\n    }\n\n    const expectedCount =\n      remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget!(sdkTargetId).size;\n    remoteTargetData = remoteTargetData.withExpectedCount(expectedCount);\n  }\n\n  ensureWatchStream(remoteStoreImpl).watch(remoteTargetData);\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: RemoteTargetId\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: remoteTargetId => {\n      // Remote syncer uses SDK target IDs, so we need to map the remote\n      // id to external id\n      const sdkTargetId =\n        remoteStoreImpl.targetIdMapRemoteToSdk.get(remoteTargetId);\n\n      // If no sdkTargetId is mapped, return an empty key set\n      return sdkTargetId !== undefined\n        ? remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget!(sdkTargetId)\n        : documentKeySet();\n    },\n    getTargetDataForTarget: remoteTargetId =>\n      remoteStoreImpl.listenTargets.get(remoteTargetId) || 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<void> {\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<void> {\n  remoteStoreImpl.listenTargets.forEach((remoteTargetData, targetId) => {\n    sendWatchRequest(remoteStoreImpl, remoteTargetData);\n  });\n}\n\nasync function onWatchStreamClose(\n  remoteStoreImpl: RemoteStoreImpl,\n  error?: FirestoreError\n): Promise<void> {\n  if (error === undefined) {\n    // Graceful stop (due to stop() or idle timeout). Make sure that's\n    // desirable.\n    debugAssert(\n      !shouldStartWatchStream(remoteStoreImpl),\n      'Watch stream was stopped gracefully while still needed.'\n    );\n  }\n\n  cleanUpWatchStreamState(remoteStoreImpl);\n\n  // If we still need the watch stream, retry the connection.\n  if (shouldStartWatchStream(remoteStoreImpl)) {\n    remoteStoreImpl.onlineStateTracker.handleWatchStreamFailure(error!);\n\n    startWatchStream(remoteStoreImpl);\n  } else {\n    // No need to restart watch stream because there are no active targets.\n    // The online state is set to unknown because there is no active attempt\n    // at establishing a connection\n    remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n  }\n}\n\nasync function onWatchStreamChange(\n  remoteStoreImpl: RemoteStoreImpl,\n  watchChange: WatchChange,\n  snapshotVersion: SnapshotVersion\n): Promise<void> {\n  // Mark the client as online since we got a message from the server\n  remoteStoreImpl.onlineStateTracker.set(OnlineState.Online);\n\n  if (\n    watchChange instanceof WatchTargetChange &&\n    watchChange.state === WatchTargetChangeState.Removed &&\n    watchChange.cause\n  ) {\n    // There was an error on a target, don't wait for a consistent snapshot\n    // to raise events\n    try {\n      await handleTargetError(remoteStoreImpl, watchChange);\n    } catch (e) {\n      logDebug(\n        LOG_TAG,\n        'Failed to remove targets %s: %s ',\n        watchChange.targetIds.join(','),\n        e\n      );\n      await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n    }\n    return;\n  }\n\n  if (watchChange instanceof DocumentWatchChange) {\n    remoteStoreImpl.watchChangeAggregator!.handleDocumentChange(watchChange);\n  } else if (watchChange instanceof ExistenceFilterChange) {\n    remoteStoreImpl.watchChangeAggregator!.handleExistenceFilter(watchChange);\n  } else {\n    debugAssert(\n      watchChange instanceof WatchTargetChange,\n      'Expected watchChange to be an instance of WatchTargetChange'\n    );\n    remoteStoreImpl.watchChangeAggregator!.handleTargetChange(watchChange);\n  }\n\n  if (!snapshotVersion.isEqual(SnapshotVersion.min())) {\n    try {\n      const lastRemoteSnapshotVersion =\n        await localStoreGetLastRemoteSnapshotVersion(\n          remoteStoreImpl.localStore\n        );\n      if (snapshotVersion.compareTo(lastRemoteSnapshotVersion) >= 0) {\n        // We have received a target change with a global snapshot if the snapshot\n        // version is not equal to SnapshotVersion.min().\n        await raiseWatchSnapshot(remoteStoreImpl, snapshotVersion);\n      }\n    } catch (e) {\n      logDebug(LOG_TAG, 'Failed to raise snapshot:', e);\n      await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n    }\n  }\n}\n\n/**\n * Recovery logic for IndexedDB errors that takes the network offline until\n * `op` succeeds. Retries are scheduled with backoff using\n * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is\n * validated via a generic operation.\n *\n * The returned Promise is resolved once the network is disabled and before\n * any retry attempt.\n */\nasync function disableNetworkUntilRecovery(\n  remoteStoreImpl: RemoteStoreImpl,\n  e: FirestoreError,\n  op?: () => Promise<unknown>\n): Promise<void> {\n  if (isIndexedDbTransactionError(e)) {\n    debugAssert(\n      !remoteStoreImpl.offlineCauses.has(OfflineCause.IndexedDbFailed),\n      'Unexpected network event when IndexedDB was marked failed.'\n    );\n    remoteStoreImpl.offlineCauses.add(OfflineCause.IndexedDbFailed);\n\n    // Disable network and raise offline snapshots\n    await disableNetworkInternal(remoteStoreImpl);\n    remoteStoreImpl.onlineStateTracker.set(OnlineState.Offline);\n\n    if (!op) {\n      // Use a simple read operation to determine if IndexedDB recovered.\n      // Ideally, we would expose a health check directly on SimpleDb, but\n      // RemoteStore only has access to persistence through LocalStore.\n      op = () =>\n        localStoreGetLastRemoteSnapshotVersion(remoteStoreImpl.localStore);\n    }\n\n    // Probe IndexedDB periodically and re-enable network\n    remoteStoreImpl.asyncQueue.enqueueRetryable(async () => {\n      logDebug(LOG_TAG, 'Retrying IndexedDB access');\n      await op!();\n      remoteStoreImpl.offlineCauses.delete(OfflineCause.IndexedDbFailed);\n      await enableNetworkInternal(remoteStoreImpl);\n    });\n  } else {\n    throw e;\n  }\n}\n\n/**\n * Executes `op`. If `op` fails, takes the network offline until `op`\n * succeeds. Returns after the first attempt.\n */\nfunction executeWithRecovery(\n  remoteStoreImpl: RemoteStoreImpl,\n  op: () => Promise<void>\n): Promise<void> {\n  return op().catch(e => disableNetworkUntilRecovery(remoteStoreImpl, e, op));\n}\n\n/**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\nfunction raiseWatchSnapshot(\n  remoteStoreImpl: RemoteStoreImpl,\n  snapshotVersion: SnapshotVersion\n): Promise<void> {\n  debugAssert(\n    !snapshotVersion.isEqual(SnapshotVersion.min()),\n    \"Can't raise event for unknown SnapshotVersion\"\n  );\n  const remoteEvent =\n    remoteStoreImpl.watchChangeAggregator!.createRemoteEvent(snapshotVersion);\n\n  // Update in-memory resume tokens. LocalStore will update the\n  // persistent view of these when applying the completed RemoteEvent.\n  remoteEvent.targetChanges.forEach((change, remoteTargetId) => {\n    if (change.resumeToken.approximateByteSize() > 0) {\n      const targetData = remoteStoreImpl.listenTargets.get(remoteTargetId);\n      // A watched target might have been removed already.\n      if (targetData) {\n        remoteStoreImpl.listenTargets.set(\n          remoteTargetId,\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  // TODO ideally this would use a new remote target ID\n  remoteEvent.targetMismatches.forEach((remoteTargetId, targetPurpose) => {\n    const targetData = remoteStoreImpl.listenTargets.get(remoteTargetId);\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      remoteTargetId,\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, remoteTargetId);\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      remoteTargetId,\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\n  const sdkEvent = toSdkRemoteEvent(remoteStoreImpl, remoteEvent);\n\n  return remoteStoreImpl.remoteSyncer.applyRemoteEvent!(sdkEvent);\n}\n\n/**\n * Convert a RemoteEvent with remote IDs to a RemoteEvent with\n * SDK IDs and dropped updates\n * for any targets we no longer track.\n *\n * @param remoteStoreImpl\n * @param remoteEvent\n * @return a new RemoteEvent with SDK IDs and dropped updates\n * for any targets we no longer track.\n */\nfunction toSdkRemoteEvent(\n  remoteStoreImpl: RemoteStoreImpl,\n  remoteEvent: RemoteEvent<RemoteTargetId>\n): RemoteEvent<TargetId> {\n  // Map TargetChanges to TargetChanges with SDK ID\n  const sdkTargetChanges = new Map<TargetId, TargetChange>();\n  remoteEvent.targetChanges.forEach((change, remoteTargetId) => {\n    // If we no longer track the remote ID, then drop the TargetChange\n    // otherwise propagate the TargetChange\n    const sdkTargetId =\n      remoteStoreImpl.targetIdMapRemoteToSdk.get(remoteTargetId);\n    if (sdkTargetId !== undefined) {\n      sdkTargetChanges.set(sdkTargetId, change);\n    }\n  });\n\n  // Map target mismatches to target mismatches with SDK ID\n  let sdkTargetMismatches = new SortedMap<TargetId, TargetPurpose>(\n    primitiveComparator\n  );\n  remoteEvent.targetMismatches.forEach((remoteTargetId, purpose) => {\n    // If we no longer track the remote ID, then drop the target mismatch\n    // otherwise propagate the target mismatch\n    const sdkTargetId =\n      remoteStoreImpl.targetIdMapRemoteToSdk.get(remoteTargetId);\n    if (sdkTargetId !== undefined) {\n      sdkTargetMismatches = sdkTargetMismatches.insert(sdkTargetId, purpose);\n    }\n  });\n\n  return new RemoteEvent(\n    remoteEvent.snapshotVersion,\n    sdkTargetChanges,\n    sdkTargetMismatches,\n    remoteEvent.documentUpdates,\n    remoteEvent.augmentedDocumentUpdates,\n    remoteEvent.resolvedLimboDocuments\n  );\n}\n\n/** Handles an error on a target */\nasync function handleTargetError(\n  remoteStoreImpl: RemoteStoreImpl,\n  watchChange: WatchTargetChange\n): Promise<void> {\n  debugAssert(\n    !!remoteStoreImpl.remoteSyncer.rejectListen,\n    'rejectListen() not set'\n  );\n  debugAssert(!!watchChange.cause, 'Handling target error without a cause');\n  const error = watchChange.cause!;\n  for (const targetId of watchChange.targetIds) {\n    // A watched target might have been removed already.\n    if (remoteStoreImpl.listenTargets.has(targetId)) {\n      const sdkTargetId = remoteStoreImpl.targetIdMapRemoteToSdk.get(targetId);\n\n      // If we still track the remote target ID, then notify the remoteSyncer\n      // of the error and then free up the remote ID.\n      if (sdkTargetId !== undefined) {\n        await remoteStoreImpl.remoteSyncer.rejectListen!(sdkTargetId, error);\n        remoteStoreImpl.targetIdMapSdkToRemote.delete(sdkTargetId);\n        remoteStoreImpl.targetIdMapRemoteToSdk.delete(targetId);\n      }\n      remoteStoreImpl.listenTargets.delete(targetId);\n    }\n    remoteStoreImpl.watchChangeAggregator!.removeTarget(targetId);\n  }\n}\n\n/**\n * Attempts to fill our write pipeline with writes from the LocalStore.\n *\n * Called internally to bootstrap or refill the write pipeline and by\n * SyncEngine whenever there are new mutations to process.\n *\n * Starts the write stream if necessary.\n */\nexport async function fillWritePipeline(\n  remoteStore: RemoteStore\n): Promise<void> {\n  const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n  const writeStream = ensureWriteStream(remoteStoreImpl);\n\n  let lastBatchIdRetrieved =\n    remoteStoreImpl.writePipeline.length > 0\n      ? remoteStoreImpl.writePipeline[remoteStoreImpl.writePipeline.length - 1]\n          .batchId\n      : BATCHID_UNKNOWN;\n\n  while (canAddToWritePipeline(remoteStoreImpl)) {\n    try {\n      const batch = await localStoreGetNextMutationBatch(\n        remoteStoreImpl.localStore,\n        lastBatchIdRetrieved\n      );\n\n      if (batch === null) {\n        if (remoteStoreImpl.writePipeline.length === 0) {\n          writeStream.markIdle();\n        }\n        break;\n      } else {\n        lastBatchIdRetrieved = batch.batchId;\n        addToWritePipeline(remoteStoreImpl, batch);\n      }\n    } catch (e) {\n      await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n    }\n  }\n\n  if (shouldStartWriteStream(remoteStoreImpl)) {\n    startWriteStream(remoteStoreImpl);\n  }\n}\n\n/**\n * Returns true if we can add to the write pipeline (i.e. the network is\n * enabled and the write pipeline is not full).\n */\nfunction canAddToWritePipeline(remoteStoreImpl: RemoteStoreImpl): boolean {\n  return (\n    canUseNetwork(remoteStoreImpl) &&\n    remoteStoreImpl.writePipeline.length < MAX_PENDING_WRITES\n  );\n}\n\n// For testing\nexport function outstandingWrites(remoteStore: RemoteStore): number {\n  const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n  return remoteStoreImpl.writePipeline.length;\n}\n\n/**\n * Queues additional writes to be sent to the write stream, sending them\n * immediately if the write stream is established.\n */\nfunction addToWritePipeline(\n  remoteStoreImpl: RemoteStoreImpl,\n  batch: MutationBatch\n): void {\n  debugAssert(\n    canAddToWritePipeline(remoteStoreImpl),\n    'addToWritePipeline called when pipeline is full'\n  );\n  remoteStoreImpl.writePipeline.push(batch);\n\n  const writeStream = ensureWriteStream(remoteStoreImpl);\n  if (writeStream.isOpen() && writeStream.handshakeComplete) {\n    writeStream.writeMutations(batch.mutations);\n  }\n}\n\nfunction shouldStartWriteStream(remoteStoreImpl: RemoteStoreImpl): boolean {\n  return (\n    canUseNetwork(remoteStoreImpl) &&\n    !ensureWriteStream(remoteStoreImpl).isStarted() &&\n    remoteStoreImpl.writePipeline.length > 0\n  );\n}\n\nfunction startWriteStream(remoteStoreImpl: RemoteStoreImpl): void {\n  debugAssert(\n    shouldStartWriteStream(remoteStoreImpl),\n    'startWriteStream() called when shouldStartWriteStream() is false.'\n  );\n  ensureWriteStream(remoteStoreImpl).start();\n}\n\nasync function onWriteStreamOpen(\n  remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n  ensureWriteStream(remoteStoreImpl).writeHandshake();\n}\n\nasync function onWriteHandshakeComplete(\n  remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n  const writeStream = ensureWriteStream(remoteStoreImpl);\n  // Send the write pipeline now that the stream is established.\n  for (const batch of remoteStoreImpl.writePipeline) {\n    writeStream.writeMutations(batch.mutations);\n  }\n}\n\nasync function onMutationResult(\n  remoteStoreImpl: RemoteStoreImpl,\n  commitVersion: SnapshotVersion,\n  results: MutationResult[]\n): Promise<void> {\n  // This is a response to a write containing mutations and should be\n  // correlated to the first write in our write pipeline.\n  debugAssert(\n    remoteStoreImpl.writePipeline.length > 0,\n    'Got result for empty write pipeline'\n  );\n  const batch = remoteStoreImpl.writePipeline.shift()!;\n  const success = MutationBatchResult.from(batch, commitVersion, results);\n\n  debugAssert(\n    !!remoteStoreImpl.remoteSyncer.applySuccessfulWrite,\n    'applySuccessfulWrite() not set'\n  );\n  await executeWithRecovery(remoteStoreImpl, () =>\n    remoteStoreImpl.remoteSyncer.applySuccessfulWrite!(success)\n  );\n\n  // It's possible that with the completion of this mutation another\n  // slot has freed up.\n  await fillWritePipeline(remoteStoreImpl);\n}\n\nasync function onWriteStreamClose(\n  remoteStoreImpl: RemoteStoreImpl,\n  error?: FirestoreError\n): Promise<void> {\n  if (error === undefined) {\n    // Graceful stop (due to stop() or idle timeout). Make sure that's\n    // desirable.\n    debugAssert(\n      !shouldStartWriteStream(remoteStoreImpl),\n      'Write stream was stopped gracefully while still needed.'\n    );\n  }\n\n  // If the write stream closed after the write handshake completes, a write\n  // operation failed and we fail the pending operation.\n  if (error && ensureWriteStream(remoteStoreImpl).handshakeComplete) {\n    // This error affects the actual write.\n    await handleWriteError(remoteStoreImpl, error!);\n  }\n\n  // The write stream might have been started by refilling the write\n  // pipeline for failed writes\n  if (shouldStartWriteStream(remoteStoreImpl)) {\n    startWriteStream(remoteStoreImpl);\n  }\n}\n\nasync function handleWriteError(\n  remoteStoreImpl: RemoteStoreImpl,\n  error: FirestoreError\n): Promise<void> {\n  // Only handle permanent errors here. If it's transient, just let the retry\n  // logic kick in.\n  if (isPermanentWriteError(error.code)) {\n    // This was a permanent error, the request itself was the problem\n    // so it's not going to succeed if we resend it.\n    const batch = remoteStoreImpl.writePipeline.shift()!;\n\n    // In this case it's also unlikely that the server itself is melting\n    // down -- this was just a bad request so inhibit backoff on the next\n    // restart.\n    ensureWriteStream(remoteStoreImpl).inhibitBackoff();\n\n    debugAssert(\n      !!remoteStoreImpl.remoteSyncer.rejectFailedWrite,\n      'rejectFailedWrite() not set'\n    );\n    await executeWithRecovery(remoteStoreImpl, () =>\n      remoteStoreImpl.remoteSyncer.rejectFailedWrite!(batch.batchId, error)\n    );\n\n    // It's possible that with the completion of this mutation\n    // another slot has freed up.\n    await fillWritePipeline(remoteStoreImpl);\n  } else {\n    // Transient error, just let the retry logic kick in.\n  }\n}\n\nasync function restartNetwork(remoteStore: RemoteStore): Promise<void> {\n  const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n  remoteStoreImpl.offlineCauses.add(OfflineCause.ConnectivityChange);\n  await disableNetworkInternal(remoteStoreImpl);\n  remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n  remoteStoreImpl.offlineCauses.delete(OfflineCause.ConnectivityChange);\n  await enableNetworkInternal(remoteStoreImpl);\n}\n\nexport async function remoteStoreHandleCredentialChange(\n  remoteStore: RemoteStore,\n  user: User\n): Promise<void> {\n  const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n  remoteStoreImpl.asyncQueue.verifyOperationInProgress();\n  debugAssert(\n    !!remoteStoreImpl.remoteSyncer.handleCredentialChange,\n    'handleCredentialChange() not set'\n  );\n\n  logDebug(LOG_TAG, 'RemoteStore received new credentials');\n  const usesNetwork = canUseNetwork(remoteStoreImpl);\n\n  // Tear down and re-create our network streams. This will ensure we get a\n  // fresh auth token for the new user and re-fill the write pipeline with\n  // new mutations from the LocalStore (since mutations are per-user).\n  remoteStoreImpl.offlineCauses.add(OfflineCause.CredentialChange);\n  await disableNetworkInternal(remoteStoreImpl);\n  if (usesNetwork) {\n    // Don't set the network status to Unknown if we are offline.\n    remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n  }\n  await remoteStoreImpl.remoteSyncer.handleCredentialChange(user);\n  remoteStoreImpl.offlineCauses.delete(OfflineCause.CredentialChange);\n  await enableNetworkInternal(remoteStoreImpl);\n}\n\n/**\n * Toggles the network state when the client gains or loses its primary lease.\n */\nexport async function remoteStoreApplyPrimaryState(\n  remoteStore: RemoteStore,\n  isPrimary: boolean\n): Promise<void> {\n  const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n  if (isPrimary) {\n    remoteStoreImpl.offlineCauses.delete(OfflineCause.IsSecondary);\n    await enableNetworkInternal(remoteStoreImpl);\n  } else if (!isPrimary) {\n    remoteStoreImpl.offlineCauses.add(OfflineCause.IsSecondary);\n    await disableNetworkInternal(remoteStoreImpl);\n    remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n  }\n}\n\n/**\n * If not yet initialized, registers the WatchStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */\nfunction ensureWatchStream(\n  remoteStoreImpl: RemoteStoreImpl\n): PersistentListenStream {\n  if (!remoteStoreImpl.watchStream) {\n    // Create stream (but note that it is not started yet).\n    remoteStoreImpl.watchStream = newPersistentWatchStream(\n      remoteStoreImpl.datastore,\n      remoteStoreImpl.asyncQueue,\n      {\n        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<T extends unknown> implements PromiseLike<T> {\n  // handle for use with clearTimeout(), or null if the operation has been\n  // executed or canceled already.\n  private timerHandle: TimerHandle | null;\n\n  private readonly deferred = new Deferred<T>();\n\n  private constructor(\n    private readonly asyncQueue: AsyncQueue,\n    readonly timerId: TimerId,\n    readonly targetTimeMs: number,\n    private readonly op: () => Promise<T>,\n    private readonly removalCallback: (op: DelayedOperation<T>) => void\n  ) {\n    // It's normal for the deferred promise to be canceled (due to cancellation)\n    // and so we attach a dummy catch callback to avoid\n    // 'UnhandledPromiseRejectionWarning' log spam.\n    this.deferred.promise.catch(err => {});\n  }\n\n  get promise(): Promise<T> {\n    return this.deferred.promise;\n  }\n\n  /**\n   * Creates and returns a DelayedOperation that has been scheduled to be\n   * executed on the provided asyncQueue after the provided delayMs.\n   *\n   * @param asyncQueue - The queue to schedule the operation on.\n   * @param id - A Timer ID identifying the type of operation this is.\n   * @param delayMs - The delay (ms) before the operation should be scheduled.\n   * @param op - The operation to run.\n   * @param removalCallback - A callback to be called synchronously once the\n   *   operation is executed or canceled, notifying the AsyncQueue to remove it\n   *   from its delayedOperations list.\n   *   PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n   *   the DelayedOperation class public.\n   */\n  static createAndSchedule<R extends unknown>(\n    asyncQueue: AsyncQueue,\n    timerId: TimerId,\n    delayMs: number,\n    op: () => Promise<R>,\n    removalCallback: (op: DelayedOperation<R>) => void\n  ): DelayedOperation<R> {\n    const targetTime = Date.now() + delayMs;\n    const delayedOp = new DelayedOperation(\n      asyncQueue,\n      timerId,\n      targetTime,\n      op,\n      removalCallback\n    );\n    delayedOp.start(delayMs);\n    return delayedOp;\n  }\n\n  /**\n   * Starts the timer. This is called immediately after construction by\n   * createAndSchedule().\n   */\n  private start(delayMs: number): void {\n    this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);\n  }\n\n  /**\n   * Queues the operation to run immediately (if it hasn't already been run or\n   * canceled).\n   */\n  skipDelay(): void {\n    return this.handleDelayElapsed();\n  }\n\n  /**\n   * Cancels the operation if it hasn't already been executed or canceled. The\n   * promise will be rejected.\n   *\n   * As long as the operation has not yet been run, calling cancel() provides a\n   * guarantee that the operation will not be run.\n   */\n  cancel(reason?: string): void {\n    if (this.timerHandle !== null) {\n      this.clearTimeout();\n      this.deferred.reject(\n        new FirestoreError(\n          Code.CANCELLED,\n          'Operation cancelled' + (reason ? ': ' + reason : '')\n        )\n      );\n    }\n  }\n\n  then = this.deferred.promise.then.bind(this.deferred.promise);\n\n  private handleDelayElapsed(): void {\n    this.asyncQueue.enqueueAndForget(() => {\n      if (this.timerHandle !== null) {\n        this.clearTimeout();\n        return this.op().then(result => {\n          return this.deferred.resolve(result);\n        });\n      } else {\n        return Promise.resolve();\n      }\n    });\n  }\n\n  private clearTimeout(): void {\n    if (this.timerHandle !== null) {\n      this.removalCallback(this);\n      clearTimeout(this.timerHandle);\n      this.timerHandle = null;\n    }\n  }\n}\n\nexport interface AsyncQueue {\n  // Is this AsyncQueue being shut down? If true, this instance will not enqueue\n  // any new operations, Promises from enqueue requests will not resolve.\n  readonly isShuttingDown: boolean;\n\n  /**\n   * Adds a new operation to the queue without waiting for it to complete (i.e.\n   * we ignore the Promise result).\n   */\n  enqueueAndForget<T extends unknown>(op: () => Promise<T>): void;\n\n  /**\n   * Regardless if the queue has initialized shutdown, adds a new operation to the\n   * queue without waiting for it to complete (i.e. we ignore the Promise result).\n   */\n  enqueueAndForgetEvenWhileRestricted<T extends unknown>(\n    op: () => Promise<T>\n  ): void;\n\n  /**\n   * Initialize the shutdown of this queue. Once this method is called, the\n   * only possible way to request running an operation is through\n   * `enqueueEvenWhileRestricted()`.\n   *\n   * @param purgeExistingTasks - Whether already enqueued tasked should be\n   * rejected (unless enqueued 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<T extends unknown>(op: () => Promise<T>): Promise<T>;\n\n  /**\n   * Enqueue a retryable operation.\n   *\n   * A retryable operation is rescheduled with backoff if it fails with a\n   * IndexedDbTransactionError (the error type used by SimpleDb). All\n   * retryable operations are executed in order and only run if all prior\n   * operations were retried successfully.\n   */\n  enqueueRetryable(op: () => Promise<void>): void;\n\n  /**\n   * Schedules an operation to be queued on the AsyncQueue once the specified\n   * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel\n   * or fast-forward the operation prior to its running.\n   */\n  enqueueAfterDelay<T extends unknown>(\n    timerId: TimerId,\n    delayMs: number,\n    op: () => Promise<T>\n  ): DelayedOperation<T>;\n\n  /**\n   * Verifies there's an operation currently in-progress on the AsyncQueue.\n   * Unfortunately we can't verify that the running code is in the promise chain\n   * of that operation, so this isn't a foolproof check, but it should be enough\n   * to catch some bugs.\n   */\n  verifyOperationInProgress(): void;\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */\nexport function wrapInUserErrorIfRecoverable(\n  e: Error,\n  msg: string\n): FirestoreError {\n  logError(LOG_TAG, `${msg}: ${e}`);\n  if (isIndexedDbTransactionError(e)) {\n    return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`);\n  } else {\n    throw e;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap } from '../util/sorted_map';\n\nimport { documentMap } from './collections';\nimport { Document } from './document';\nimport { DocumentComparator } from './document_comparator';\nimport { DocumentKey } from './document_key';\n\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */\n\nexport class DocumentSet {\n  /**\n   * Returns an empty copy of the existing DocumentSet, using the same\n   * comparator.\n   */\n  static emptySet(oldSet: DocumentSet): DocumentSet {\n    return new DocumentSet(oldSet.comparator);\n  }\n\n  private comparator: DocumentComparator;\n  private keyedMap: SortedMap<DocumentKey, Document>;\n  private sortedSet: SortedMap<Document, null>;\n\n  /** The default ordering is by key if the comparator is omitted */\n  constructor(comp?: DocumentComparator) {\n    // We are adding document key comparator to the end as it's the only\n    // guaranteed unique property of a document.\n    if (comp) {\n      this.comparator = (d1: Document, d2: Document) =>\n        comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key);\n    } else {\n      this.comparator = (d1: Document, d2: Document) =>\n        DocumentKey.comparator(d1.key, d2.key);\n    }\n\n    this.keyedMap = documentMap();\n    this.sortedSet = new SortedMap<Document, null>(this.comparator);\n  }\n\n  has(key: DocumentKey): boolean {\n    return this.keyedMap.get(key) != null;\n  }\n\n  get(key: DocumentKey): Document | null {\n    return this.keyedMap.get(key);\n  }\n\n  first(): Document | null {\n    return this.sortedSet.minKey();\n  }\n\n  last(): Document | null {\n    return this.sortedSet.maxKey();\n  }\n\n  isEmpty(): boolean {\n    return this.sortedSet.isEmpty();\n  }\n\n  /**\n   * Returns the index of the provided key in the document set, or -1 if the\n   * document key is not present in the set;\n   */\n  indexOf(key: DocumentKey): number {\n    const doc = this.keyedMap.get(key);\n    return doc ? this.sortedSet.indexOf(doc) : -1;\n  }\n\n  get size(): number {\n    return this.sortedSet.size;\n  }\n\n  /** Iterates documents in order defined by \"comparator\" */\n  forEach(cb: (doc: Document) => void): void {\n    this.sortedSet.inorderTraversal((k, v) => {\n      cb(k);\n      return false;\n    });\n  }\n\n  /** Inserts or updates a document with the same key */\n  add(doc: Document): DocumentSet {\n    // First remove the element if we have it.\n    const set = this.delete(doc.key);\n    return set.copy(\n      set.keyedMap.insert(doc.key, doc),\n      set.sortedSet.insert(doc, null)\n    );\n  }\n\n  /** Deletes a document with a given key */\n  delete(key: DocumentKey): DocumentSet {\n    const doc = this.get(key);\n    if (!doc) {\n      return this;\n    }\n\n    return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\n  }\n\n  isEqual(other: DocumentSet | null | undefined): boolean {\n    if (!(other instanceof DocumentSet)) {\n      return false;\n    }\n    if (this.size !== other.size) {\n      return false;\n    }\n\n    const thisIt = this.sortedSet.getIterator();\n    const otherIt = other.sortedSet.getIterator();\n    while (thisIt.hasNext()) {\n      const thisDoc = thisIt.getNext().key;\n      const otherDoc = otherIt.getNext().key;\n      if (!thisDoc.isEqual(otherDoc)) {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  toString(): string {\n    const docStrings: string[] = [];\n    this.forEach(doc => {\n      docStrings.push(doc.toString());\n    });\n    if (docStrings.length === 0) {\n      return 'DocumentSet ()';\n    } else {\n      return 'DocumentSet (\\n  ' + docStrings.join('  \\n') + '\\n)';\n    }\n  }\n\n  private copy(\n    keyedMap: SortedMap<DocumentKey, Document>,\n    sortedSet: SortedMap<Document, null>\n  ): DocumentSet {\n    const newSet = new DocumentSet();\n    newSet.comparator = this.comparator;\n    newSet.keyedMap = keyedMap;\n    newSet.sortedSet = sortedSet;\n    return newSet;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKeySet } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { QueryOrPipeline, queryOrPipelineEqual } from './pipeline-util';\n\nexport const enum ChangeType {\n  Added,\n  Removed,\n  Modified,\n  Metadata\n}\n\nexport interface DocumentViewChange {\n  type: ChangeType;\n  doc: Document;\n}\n\nexport const enum SyncState {\n  Local,\n  Synced\n}\n\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */\nexport class DocumentChangeSet {\n  private changeMap = new SortedMap<DocumentKey, DocumentViewChange>(\n    DocumentKey.comparator\n  );\n\n  track(change: DocumentViewChange): void {\n    const key = change.doc.key;\n    const oldChange = this.changeMap.get(key);\n    if (!oldChange) {\n      this.changeMap = this.changeMap.insert(key, change);\n      return;\n    }\n\n    // Merge the new change with the existing change.\n    if (\n      change.type !== ChangeType.Added &&\n      oldChange.type === ChangeType.Metadata\n    ) {\n      this.changeMap = this.changeMap.insert(key, change);\n    } else if (\n      change.type === ChangeType.Metadata &&\n      oldChange.type !== ChangeType.Removed\n    ) {\n      this.changeMap = this.changeMap.insert(key, {\n        type: oldChange.type,\n        doc: change.doc\n      });\n    } else if (\n      change.type === ChangeType.Modified &&\n      oldChange.type === ChangeType.Modified\n    ) {\n      this.changeMap = this.changeMap.insert(key, {\n        type: ChangeType.Modified,\n        doc: change.doc\n      });\n    } else if (\n      change.type === ChangeType.Modified &&\n      oldChange.type === ChangeType.Added\n    ) {\n      this.changeMap = this.changeMap.insert(key, {\n        type: ChangeType.Added,\n        doc: change.doc\n      });\n    } else if (\n      change.type === ChangeType.Removed &&\n      oldChange.type === ChangeType.Added\n    ) {\n      this.changeMap = this.changeMap.remove(key);\n    } else if (\n      change.type === ChangeType.Removed &&\n      oldChange.type === ChangeType.Modified\n    ) {\n      this.changeMap = this.changeMap.insert(key, {\n        type: ChangeType.Removed,\n        doc: oldChange.doc\n      });\n    } else if (\n      change.type === ChangeType.Added &&\n      oldChange.type === ChangeType.Removed\n    ) {\n      this.changeMap = this.changeMap.insert(key, {\n        type: ChangeType.Modified,\n        doc: change.doc\n      });\n    } else {\n      // This includes these cases, which don't make sense:\n      // Added->Added\n      // Removed->Removed\n      // Modified->Added\n      // Removed->Modified\n      // Metadata->Added\n      // Removed->Metadata\n      fail(\n        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: QueryOrPipeline,\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: QueryOrPipeline,\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      !queryOrPipelineEqual(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 {\n  canonifyPipeline,\n  canonifyQueryOrPipeline,\n  isPipeline,\n  QueryOrPipeline,\n  queryOrPipelineEqual\n} from './pipeline-util';\nimport { Query, 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<T> {\n  next: EventHandler<T>;\n  error: EventHandler<FirestoreError>;\n}\n\n/**\n * EventManager is responsible for mapping queries to query event emitters.\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\n * backend.\n *\n * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be\n * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This\n * allows users to tree-shake the Watch logic.\n */\nexport interface EventManager {\n  onListen?: (\n    query: QueryOrPipeline,\n    enableRemoteListen: boolean\n  ) => Promise<ViewSnapshot>;\n  onUnlisten?: (\n    query: QueryOrPipeline,\n    disableRemoteListen: boolean\n  ) => Promise<void>;\n  onFirstRemoteStoreListen?: (query: QueryOrPipeline) => Promise<void>;\n  onLastRemoteStoreUnlisten?: (query: QueryOrPipeline) => Promise<void>;\n  terminate(): void;\n}\n\nexport function newEventManager(): EventManager {\n  return new EventManagerImpl();\n}\n\nexport class EventManagerImpl implements EventManager {\n  queries: ObjectMap<QueryOrPipeline, QueryListenersInfo> =\n    newQueriesObjectMap();\n\n  onlineState: OnlineState = OnlineState.Unknown;\n\n  snapshotsInSyncListeners: Set<Observer<void>> = new Set();\n\n  /** Callback invoked when a Query is first listen to. */\n  onListen?: (\n    query: QueryOrPipeline,\n    enableRemoteListen: boolean\n  ) => Promise<ViewSnapshot>;\n  /** Callback invoked once all listeners to a Query are removed. */\n  onUnlisten?: (\n    query: QueryOrPipeline,\n    disableRemoteListen: boolean\n  ) => Promise<void>;\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: QueryOrPipeline) => Promise<void>;\n  /**\n   * Callback invoked when a Query stops listening to the remote store, while\n   * still listening to the cache.\n   */\n  onLastRemoteStoreUnlisten?: (query: QueryOrPipeline) => Promise<void>;\n\n  terminate(): void {\n    errorAllTargets(\n      this,\n      new FirestoreError(Code.ABORTED, 'Firestore shutting down')\n    );\n  }\n}\n\nfunction newQueriesObjectMap(): ObjectMap<QueryOrPipeline, QueryListenersInfo> {\n  return new ObjectMap<QueryOrPipeline, QueryListenersInfo>(\n    q => canonifyQueryOrPipeline(q),\n    queryOrPipelineEqual\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<void> {\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 '${\n        isPipeline(listener.query)\n          ? canonifyPipeline(listener.query)\n          : stringifyQuery(listener.query)\n      }' 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<void> {\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<void>\n): void {\n  const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n  eventManagerImpl.snapshotsInSyncListeners.add(observer);\n  // Immediately fire an initial event, indicating all existing listeners\n  // are in-sync.\n  observer.next();\n}\n\nexport function removeSnapshotsInSyncListener(\n  eventManager: EventManager,\n  observer: Observer<void>\n): void {\n  const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n  eventManagerImpl.snapshotsInSyncListeners.delete(observer);\n}\n\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  /** Realtime Pipeline Only: Set server timestamp behavior. */\n  readonly serverTimestampBehavior?: 'estimate' | 'previous' | 'none';\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: QueryOrPipeline,\n    private queryObserver: Observer<ViewSnapshot>,\n    options?: ListenOptions\n  ) {\n    this.options = options || {};\n  }\n\n  /**\n   * Applies the new ViewSnapshot to this listener, raising a user-facing event\n   * if applicable (depending on what changed, whether the user has opted into\n   * metadata-only changes, etc.). Returns true if a user-facing event was\n   * indeed raised.\n   */\n  onViewSnapshot(snap: ViewSnapshot): boolean {\n    debugAssert(\n      snap.docChanges.length > 0 || snap.syncStateChanged,\n      'We got a new snapshot with no changes?'\n    );\n\n    if (!this.options.includeMetadataChanges) {\n      // Remove the metadata only changes.\n      const docChanges: DocumentViewChange[] = [];\n      for (const docChange of snap.docChanges) {\n        if (docChange.type !== ChangeType.Metadata) {\n          docChanges.push(docChange);\n        }\n      }\n      snap = new ViewSnapshot(\n        snap.query,\n        snap.docs,\n        snap.oldDocs,\n        docChanges,\n        snap.mutatedKeys,\n        snap.fromCache,\n        snap.syncStateChanged,\n        /* excludesMetadataChanges= */ true,\n        snap.hasCachedResults\n      );\n    }\n    let raisedEvent = false;\n    if (!this.raisedInitialEvent) {\n      if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\n        this.raiseInitialEvent(snap);\n        raisedEvent = true;\n      }\n    } else if (this.shouldRaiseEvent(snap)) {\n      this.queryObserver.next(snap);\n      raisedEvent = true;\n    }\n\n    this.snap = snap;\n    return raisedEvent;\n  }\n\n  onError(error: FirestoreError): void {\n    this.queryObserver.error(error);\n  }\n\n  /** Returns whether a snapshot was raised. */\n  applyOnlineStateChange(onlineState: OnlineState): boolean {\n    this.onlineState = onlineState;\n    let raisedEvent = false;\n    if (\n      this.snap &&\n      !this.raisedInitialEvent &&\n      this.shouldRaiseInitialEvent(this.snap, onlineState)\n    ) {\n      this.raiseInitialEvent(this.snap);\n      raisedEvent = true;\n    }\n    return raisedEvent;\n  }\n\n  private shouldRaiseInitialEvent(\n    snap: ViewSnapshot,\n    onlineState: OnlineState\n  ): boolean {\n    debugAssert(\n      !this.raisedInitialEvent,\n      'Determining whether to raise first event but already had first event'\n    );\n\n    // Always raise the first event when we're synced\n    if (!snap.fromCache) {\n      return true;\n    }\n\n    // 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<string>();\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<string, DocumentKeySet> {\n    const queryDocumentMap = new Map<string, DocumentKeySet>();\n    const bundleConverter = new BundleConverterImpl(this.serializer);\n    for (const bundleDoc of documents) {\n      if (bundleDoc.metadata.queries) {\n        const documentKey = bundleConverter.toDocumentKey(\n          bundleDoc.metadata.name!\n        );\n        for (const queryName of bundleDoc.metadata.queries) {\n          const documentKeys = (\n            queryDocumentMap.get(queryName) || documentKeySet()\n          ).add(documentKey);\n          queryDocumentMap.set(queryName, documentKeys);\n        }\n      }\n    }\n\n    return queryDocumentMap;\n  }\n\n  /**\n   * Update the progress to 'Success' and return the updated progress.\n   */\n  async completeAndStoreAsync(\n    localStore: LocalStore\n  ): Promise<BundleLoadResult> {\n    debugAssert(\n      this._documents[this._documents.length - 1]?.metadata.exists !== true ||\n        !!this._documents[this._documents.length - 1].document,\n      'Bundled documents end with a document metadata element instead of a document.'\n    );\n    debugAssert(!!this.bundleMetadata.id, 'Bundle ID must be set.');\n\n    const changedDocs = await localStoreApplyBundledDocuments(\n      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, MutableDocument } 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 { isPipeline, QueryOrPipeline } from './pipeline-util';\nimport {\n  getLastEffectiveLimit,\n  newPipelineComparator,\n  PipelineInputOutput,\n  queryOrPipelineMatches,\n  runPipeline\n} from './pipeline_run';\nimport { LimitType, newQueryComparator } 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: QueryOrPipeline,\n    /** Documents included in the remote target */\n    private _syncedDocuments: DocumentKeySet\n  ) {\n    this.docComparator = isPipeline(query)\n      ? newPipelineComparator(query)\n      : 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    const [lastDocInLimit, firstDocInLimit] = this.getLimitEdges(\n      this.query,\n      oldDocumentSet\n    );\n\n    docChanges.inorderTraversal((key, entry) => {\n      const oldDoc = oldDocumentSet.get(key);\n      const newDoc = queryOrPipelineMatches(\n        this.query,\n        entry as MutableDocument\n      )\n        ? entry\n        : 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    const limit = this.getLimit(this.query);\n    if (limit) {\n      if (isPipeline(this.query)) {\n        // TODO(pipeline): Not very efficient obviously, but should be fine for now.\n        // Longer term, limit queries should be evaluated from query engine as well.\n        const candidates: PipelineInputOutput[] = [];\n        newDocumentSet.forEach((doc: Document) =>\n          candidates.push(doc as MutableDocument)\n        );\n\n        const results = runPipeline(this.query, candidates);\n        let newResults = new DocumentSet(newPipelineComparator(this.query));\n        for (const doc of results) {\n          newResults = newResults.add(doc);\n        }\n\n        newDocumentSet.forEach((doc: Document) => {\n          if (!newResults.has(doc.key)) {\n            newMutatedKeys = newMutatedKeys.delete(doc.key);\n            changeSet.track({ type: ChangeType.Removed, doc });\n          }\n        });\n\n        newDocumentSet = newResults;\n      } else {\n        const limitType = this.getLimitType(this.query);\n        while (newDocumentSet.size > limit) {\n          const oldDoc =\n            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\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 getLimit(query: QueryOrPipeline): number | undefined {\n    return isPipeline(query)\n      ? getLastEffectiveLimit(query)?.limit\n      : query.limit || undefined;\n  }\n\n  private getLimitType(query: QueryOrPipeline): LimitType {\n    if (isPipeline(query)) {\n      const effectiveLimit = getLastEffectiveLimit(query);\n      return effectiveLimit && effectiveLimit.limit < 0\n        ? LimitType.Last\n        : LimitType.First;\n    }\n    return query.limitType;\n  }\n\n  private getLimitEdges(\n    query: QueryOrPipeline,\n    oldDocumentSet: DocumentSet\n  ): [Document | null, Document | null] {\n    if (isPipeline(query)) {\n      const limit = getLastEffectiveLimit(query)?.limit;\n      return [\n        oldDocumentSet.size === limit ? oldDocumentSet.last() : null,\n        null\n      ];\n    } else {\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        query.limitType === LimitType.First &&\n        oldDocumentSet.size === this.getLimit(this.query)\n          ? oldDocumentSet.last()\n          : null;\n      const firstDocInLimit =\n        query.limitType === LimitType.Last &&\n        oldDocumentSet.size === this.getLimit(this.query)\n          ? oldDocumentSet.first()\n          : null;\n      return [lastDocInLimit, firstDocInLimit];\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  localStoreGetDocuments,\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  DocumentMap,\n  mutableDocumentMap\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 { getPipelineCollectionId, getPipelineSourceType } from './pipeline';\nimport {\n  canonifyQueryOrPipeline,\n  isPipeline,\n  QueryOrPipeline,\n  queryOrPipelineEqual,\n  stringifyQueryOrPipeline,\n  TargetOrPipeline\n} from './pipeline-util';\nimport {\n  LimitType,\n  newQuery,\n  newQueryForPath,\n  queryCollectionGroup,\n  queryToTarget\n} from './query';\nimport { SnapshotVersion } from './snapshot_version';\nimport { SyncEngine } from './sync_engine';\nimport { targetIsPipelineTarget } 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: QueryOrPipeline,\n    /**\n     * The target number created by the client that is used in the watch\n     * stream to identify this query.\n     */\n    public targetId: TargetId,\n    /**\n     * The view is responsible for computing the final merged truth of what\n     * docs are in the query. It gets notified of local and remote changes,\n     * and applies the query filters and limits to determine the most correct\n     * possible results.\n     */\n    public view: View\n  ) {}\n}\n\n/** Tracks a limbo resolution. */\nclass LimboResolution {\n  constructor(public key: DocumentKey) {}\n\n  /**\n   * Set to true once we've received a document. This is used in\n   * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to\n   * decide whether it needs to manufacture a delete event for the target once\n   * the target is CURRENT.\n   */\n  receivedDocument: boolean = false;\n}\n\n/**\n * A function that updates a QueryView with a set of document changes (and a\n * remote event if applicable).\n */\ntype ApplyDocChangesHandler = (\n  queryView: QueryView,\n  changes: DocumentMap,\n  remoteEvent?: RemoteEvent\n) => Promise<ViewSnapshot | undefined>;\n\n/**\n * Callbacks implemented by EventManager to handle notifications from\n * SyncEngine.\n */\ninterface SyncEngineListener {\n  /** Handles new view snapshots. */\n  onWatchChange?(snapshots: ViewSnapshot[]): void;\n\n  /** Handles the failure of a query. */\n  onWatchError?(query: QueryOrPipeline, 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<QueryOrPipeline, QueryView>(\n    q => canonifyQueryOrPipeline(q),\n    queryOrPipelineEqual\n  );\n  queriesByTarget = new Map<TargetId, QueryOrPipeline[]>();\n  /**\n   * The keys of documents that are in limbo for which we haven't yet started a\n   * limbo resolution query. The strings in this set are the result of calling\n   * `key.path.canonicalString()` where `key` is a `DocumentKey` object.\n   *\n   * The `Set` type was chosen because it provides efficient lookup and removal\n   * of arbitrary elements and it also maintains insertion order, providing the\n   * desired queue-like FIFO semantics.\n   */\n  enqueuedLimboResolutions = new Set<string>();\n  /**\n   * Keeps track of the target ID for each document that is in limbo with an\n   * active target.\n   */\n  activeLimboTargetsByKey = new SortedMap<DocumentKey, TargetId>(\n    DocumentKey.comparator\n  );\n  /**\n   * Keeps track of the information about an active limbo resolution for each\n   * active target ID that was started for the purpose of limbo resolution.\n   */\n  activeLimboResolutionsByTarget = new Map<TargetId, LimboResolution>();\n  limboDocumentRefs = new ReferenceSet();\n  /** Stores user completion handlers, indexed by User and BatchId. */\n  mutationUserCallbacks = {} as {\n    [uidKey: string]: SortedMap<BatchId, Deferred<void>>;\n  };\n  /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n  pendingWritesCallbacks = new Map<BatchId, Array<Deferred<void>>>();\n  limboTargetIdGenerator = TargetIdGenerator.forSyncEngine();\n\n  onlineState = OnlineState.Unknown;\n\n  // The primary state is set to `true` or `false` immediately after Firestore\n  // startup. In the interim, a client should only be considered primary if\n  // `isPrimary` is true.\n  _isPrimaryClient: undefined | boolean = undefined;\n\n  constructor(\n    readonly localStore: LocalStore,\n    readonly remoteStore: RemoteStore,\n    readonly eventManager: EventManager,\n    // PORTING NOTE: Manages state synchronization in multi-tab environments.\n    readonly sharedClientState: SharedClientState,\n    public currentUser: User,\n    readonly maxConcurrentLimboResolutions: number\n  ) {}\n\n  get isPrimaryClient(): boolean {\n    return this._isPrimaryClient === true;\n  }\n}\n\nexport function newSyncEngine(\n  localStore: LocalStore,\n  remoteStore: RemoteStore,\n  eventManager: EventManager,\n  // PORTING NOTE: Manages state synchronization in multi-tab environments.\n  sharedClientState: SharedClientState,\n  currentUser: User,\n  maxConcurrentLimboResolutions: number,\n  isPrimary: boolean\n): SyncEngine {\n  const syncEngine = new SyncEngineImpl(\n    localStore,\n    remoteStore,\n    eventManager,\n    sharedClientState,\n    currentUser,\n    maxConcurrentLimboResolutions\n  );\n  if (isPrimary) {\n    syncEngine._isPrimaryClient = true;\n  }\n  return syncEngine;\n}\n\n/**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the initial snapshot.\n */\nexport async function syncEngineListen(\n  syncEngine: SyncEngine,\n  query: QueryOrPipeline,\n  shouldListenToRemote: boolean = true\n): Promise<ViewSnapshot> {\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: QueryOrPipeline\n): Promise<void> {\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: QueryOrPipeline,\n  shouldListenToRemote: boolean,\n  shouldInitializeView: boolean\n): Promise<ViewSnapshot | undefined> {\n  const targetData = await localStoreAllocateTarget(\n    syncEngineImpl.localStore,\n    isPipeline(query) ? query : 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: QueryOrPipeline,\n  targetId: TargetId,\n  current: boolean,\n  resumeToken: ByteString\n): Promise<ViewSnapshot> {\n  // PORTING NOTE: On Web only, we inject the code that registers new Limbo\n  // targets based on view changes. This allows us to only depend on Limbo\n  // changes when user code includes queries.\n  syncEngineImpl.applyDocChanges = (queryView, changes, remoteEvent) =>\n    applyDocChanges(syncEngineImpl, queryView, changes, remoteEvent);\n\n  const queryResult = await localStoreExecuteQuery(\n    syncEngineImpl.localStore,\n    query,\n    /* usePreviousResults= */ true\n  );\n  const view = new View(query, queryResult.remoteKeys);\n  const viewDocChanges = view.computeDocChanges(queryResult.documents);\n  const synthesizedTargetChange =\n    TargetChange.createSynthesizedTargetChangeForCurrentChange(\n      targetId,\n      current && syncEngineImpl.onlineState !== OnlineState.Offline,\n      resumeToken\n    );\n  const viewChange = view.applyChanges(\n    viewDocChanges,\n    /* limboResolutionEnabled= */ syncEngineImpl.isPrimaryClient,\n    synthesizedTargetChange\n  );\n  updateTrackedLimbos(syncEngineImpl, targetId, viewChange.limboChanges);\n\n  debugAssert(\n    !!viewChange.snapshot,\n    'applyChanges for new view should always return a snapshot'\n  );\n\n  const data = new QueryView(query, targetId, view);\n\n  syncEngineImpl.queryViewsByQuery.set(query, data);\n  if (syncEngineImpl.queriesByTarget.has(targetId)) {\n    syncEngineImpl.queriesByTarget.get(targetId)!.push(query);\n  } else {\n    syncEngineImpl.queriesByTarget.set(targetId, [query]);\n  }\n\n  return viewChange.snapshot;\n}\n\n/** Stops listening to the query. */\nexport async function syncEngineUnlisten(\n  syncEngine: SyncEngine,\n  query: QueryOrPipeline,\n  shouldUnlistenToRemote: boolean\n): Promise<void> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  const queryView = syncEngineImpl.queryViewsByQuery.get(query)!;\n  debugAssert(\n    !!queryView,\n    'Trying to unlisten on query not found:' + stringifyQueryOrPipeline(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 => !queryOrPipelineEqual(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: QueryOrPipeline\n): Promise<void> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  const queryView = syncEngineImpl.queryViewsByQuery.get(query)!;\n  debugAssert(\n    !!queryView,\n    'Trying to unlisten on query not found:' + stringifyQueryOrPipeline(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<void>\n): Promise<void> {\n  const syncEngineImpl = syncEngineEnsureWriteCallbacks(syncEngine);\n\n  try {\n    const result = await localStoreWriteLocally(\n      syncEngineImpl.localStore,\n      batch\n    );\n    syncEngineImpl.sharedClientState.addPendingMutation(result.batchId);\n    addMutationCallback(syncEngineImpl, result.batchId, userCallback);\n    await syncEngineEmitNewSnapsAndNotifyLocalStore(\n      syncEngineImpl,\n      result.changes\n    );\n    await fillWritePipeline(syncEngineImpl.remoteStore);\n  } catch (e) {\n    // If we can't persist the mutation, we reject the user callback and\n    // don't send the mutation. The user can then retry the write.\n    const error = wrapInUserErrorIfRecoverable(\n      e as Error,\n      `Failed to persist write`\n    );\n    userCallback.reject(error);\n  }\n}\n\n/**\n * Applies one remote event to the sync engine, notifying any views of the\n * changes, and releasing any pending mutation batches that would become\n * visible because of the snapshot version the remote event contains.\n */\nexport async function syncEngineApplyRemoteEvent(\n  syncEngine: SyncEngine,\n  remoteEvent: RemoteEvent\n): Promise<void> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n  try {\n    const changes = await localStoreApplyRemoteEventToLocalCache(\n      syncEngineImpl.localStore,\n      remoteEvent\n    );\n    // Update `receivedDocument` as appropriate for any limbo targets.\n    remoteEvent.targetChanges.forEach((targetChange, targetId) => {\n      const limboResolution =\n        syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n      if (limboResolution) {\n        // Since this is a limbo resolution lookup, it's for a single document\n        // and it could be added, modified, or removed, but not a combination.\n        hardAssert(\n          targetChange.addedDocuments.size +\n            targetChange.modifiedDocuments.size +\n            targetChange.removedDocuments.size <=\n            1,\n          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<void> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n  // PORTING NOTE: Multi-tab only.\n  syncEngineImpl.sharedClientState.updateQueryState(targetId, 'rejected', err);\n\n  const limboResolution =\n    syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n  const limboKey = limboResolution && limboResolution.key;\n  if (limboKey) {\n    // TODO(klimt): We really only should do the following on permission\n    // denied errors, but we don't have the cause code here.\n\n    // It's a limbo doc. Create a synthetic event saying it was deleted.\n    // This is kind of a hack. Ideally, we would have a method in the local\n    // store to purge a document. However, it would be tricky to keep all of\n    // the local store's invariants with another method.\n    let documentUpdates = new SortedMap<DocumentKey, MutableDocument>(\n      DocumentKey.comparator\n    );\n    // TODO(b/217189216): This limbo document should ideally have a read time,\n    // so that it is picked up by any read-time based scans. The backend,\n    // however, does not send a read time for target removals.\n    documentUpdates = documentUpdates.insert(\n      limboKey,\n      MutableDocument.newNoDocument(limboKey, SnapshotVersion.min())\n    );\n    const resolvedLimboDocuments = documentKeySet().add(limboKey);\n    const event = new RemoteEvent(\n      SnapshotVersion.min(),\n      /* targetChanges= */ new Map<TargetId, TargetChange>(),\n      /* targetMismatches= */ new SortedMap<TargetId, TargetPurpose>(\n        primitiveComparator\n      ),\n      documentUpdates,\n      mutableDocumentMap(),\n      resolvedLimboDocuments\n    );\n\n    await syncEngineApplyRemoteEvent(syncEngineImpl, event);\n\n    // Since this query failed, we won't want to manually unlisten to it.\n    // We only remove it from bookkeeping after we successfully applied the\n    // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to\n    // this query when the RemoteStore restarts the Watch stream, which should\n    // re-trigger the target failure.\n    syncEngineImpl.activeLimboTargetsByKey =\n      syncEngineImpl.activeLimboTargetsByKey.remove(limboKey);\n    syncEngineImpl.activeLimboResolutionsByTarget.delete(targetId);\n    pumpEnqueuedLimboResolutions(syncEngineImpl);\n  } else {\n    await localStoreReleaseTarget(\n      syncEngineImpl.localStore,\n      targetId,\n      /* keepPersistedTargetData */ false\n    )\n      .then(() => removeAndCleanupTarget(syncEngineImpl, targetId, err))\n      .catch(ignoreIfPrimaryLeaseLoss);\n  }\n}\n\nexport async function syncEngineApplySuccessfulWrite(\n  syncEngine: SyncEngine,\n  mutationBatchResult: MutationBatchResult\n): Promise<void> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  const batchId = mutationBatchResult.batch.batchId;\n\n  try {\n    const changes = await localStoreAcknowledgeBatch(\n      syncEngineImpl.localStore,\n      mutationBatchResult\n    );\n\n    // The local store may or may not be able to apply the write result and\n    // raise events immediately (depending on whether the watcher is caught\n    // up), so we raise user callbacks first so that they consistently happen\n    // before listen events.\n    processUserCallback(syncEngineImpl, batchId, /*error=*/ null);\n    triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n\n    syncEngineImpl.sharedClientState.updateMutationState(\n      batchId,\n      'acknowledged'\n    );\n    await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes);\n  } catch (error) {\n    await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n  }\n}\n\nexport async function syncEngineRejectFailedWrite(\n  syncEngine: SyncEngine,\n  batchId: BatchId,\n  error: FirestoreError\n): Promise<void> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n  try {\n    const changes = await localStoreRejectBatch(\n      syncEngineImpl.localStore,\n      batchId\n    );\n\n    // The local store may or may not be able to apply the write result and\n    // raise events immediately (depending on whether the watcher is caught up),\n    // so we raise user callbacks first so that they consistently happen before\n    // listen events.\n    processUserCallback(syncEngineImpl, batchId, error);\n    triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n\n    syncEngineImpl.sharedClientState.updateMutationState(\n      batchId,\n      'rejected',\n      error\n    );\n    await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes);\n  } catch (error) {\n    await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n  }\n}\n\n/**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */\nexport async function syncEngineRegisterPendingWritesCallback(\n  syncEngine: SyncEngine,\n  callback: Deferred<void>\n): Promise<void> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  if (!canUseNetwork(syncEngineImpl.remoteStore)) {\n    logDebug(\n      LOG_TAG,\n      'The network is disabled. The task returned by ' +\n        \"'awaitPendingWrites()' will not complete until the network is enabled.\"\n    );\n  }\n\n  try {\n    const highestBatchId = await localStoreGetHighestUnacknowledgedBatchId(\n      syncEngineImpl.localStore\n    );\n    if (highestBatchId === BATCHID_UNKNOWN) {\n      // Trigger the callback right away if there is no pending writes at the moment.\n      callback.resolve();\n      return;\n    }\n\n    const callbacks =\n      syncEngineImpl.pendingWritesCallbacks.get(highestBatchId) || [];\n    callbacks.push(callback);\n    syncEngineImpl.pendingWritesCallbacks.set(highestBatchId, callbacks);\n  } catch (e) {\n    const firestoreError = wrapInUserErrorIfRecoverable(\n      e as Error,\n      'Initialization of waitForPendingWrites() operation failed'\n    );\n    callback.reject(firestoreError);\n  }\n}\n\n/**\n * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,\n * if there are any.\n */\nfunction triggerPendingWritesCallbacks(\n  syncEngineImpl: SyncEngineImpl,\n  batchId: BatchId\n): void {\n  (syncEngineImpl.pendingWritesCallbacks.get(batchId) || []).forEach(\n    callback => {\n      callback.resolve();\n    }\n  );\n\n  syncEngineImpl.pendingWritesCallbacks.delete(batchId);\n}\n\n/** Reject all outstanding callbacks waiting for pending writes to complete. */\nfunction rejectOutstandingPendingWritesCallbacks(\n  syncEngineImpl: SyncEngineImpl,\n  errorMessage: string\n): void {\n  syncEngineImpl.pendingWritesCallbacks.forEach(callbacks => {\n    callbacks.forEach(callback => {\n      callback.reject(new FirestoreError(Code.CANCELLED, errorMessage));\n    });\n  });\n\n  syncEngineImpl.pendingWritesCallbacks.clear();\n}\n\nfunction addMutationCallback(\n  syncEngineImpl: SyncEngineImpl,\n  batchId: BatchId,\n  callback: Deferred<void>\n): void {\n  let newCallbacks =\n    syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()];\n  if (!newCallbacks) {\n    newCallbacks = new SortedMap<BatchId, Deferred<void>>(primitiveComparator);\n  }\n  newCallbacks = newCallbacks.insert(batchId, callback);\n  syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] =\n    newCallbacks;\n}\n\n/**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */\nfunction processUserCallback(\n  syncEngine: SyncEngine,\n  batchId: BatchId,\n  error: FirestoreError | null\n): void {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  let newCallbacks =\n    syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()];\n\n  // NOTE: Mutations restored from persistence won't have callbacks, so it's\n  // okay for there to be no callback for this ID.\n  if (newCallbacks) {\n    const callback = newCallbacks.get(batchId);\n    if (callback) {\n      debugAssert(\n        batchId === newCallbacks.minKey(),\n        'Mutation callbacks processed out-of-order?'\n      );\n      if (error) {\n        callback.reject(error);\n      } else {\n        callback.resolve();\n      }\n      newCallbacks = newCallbacks.remove(batchId);\n    }\n    syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] =\n      newCallbacks;\n  }\n}\n\nfunction removeAndCleanupTarget(\n  syncEngineImpl: SyncEngineImpl,\n  targetId: number,\n  error: FirestoreError | null = null\n): void {\n  syncEngineImpl.sharedClientState.removeLocalQueryTarget(targetId);\n\n  debugAssert(\n    syncEngineImpl.queriesByTarget.has(targetId) &&\n      syncEngineImpl.queriesByTarget.get(targetId)!.length !== 0,\n    `There are no queries mapped to target id ${targetId}`\n  );\n\n  for (const query of syncEngineImpl.queriesByTarget.get(targetId)!) {\n    syncEngineImpl.queryViewsByQuery.delete(query);\n    if (error) {\n      syncEngineImpl.syncEngineListener.onWatchError!(query, error);\n    }\n  }\n\n  syncEngineImpl.queriesByTarget.delete(targetId);\n\n  if (syncEngineImpl.isPrimaryClient) {\n    const limboKeys =\n      syncEngineImpl.limboDocumentRefs.removeReferencesForId(targetId);\n    limboKeys.forEach(limboKey => {\n      const isReferenced =\n        syncEngineImpl.limboDocumentRefs.containsKey(limboKey);\n      if (!isReferenced) {\n        // We removed the last reference for this key\n        removeLimboTarget(syncEngineImpl, limboKey);\n      }\n    });\n  }\n}\n\nfunction removeLimboTarget(\n  syncEngineImpl: SyncEngineImpl,\n  key: DocumentKey\n): void {\n  syncEngineImpl.enqueuedLimboResolutions.delete(key.path.canonicalString());\n\n  // It's possible that the target already got removed because the query failed. In that case,\n  // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.\n  const limboTargetId = syncEngineImpl.activeLimboTargetsByKey.get(key);\n  if (limboTargetId === null) {\n    // This target already got removed, because the query failed.\n    return;\n  }\n\n  remoteStoreUnlisten(syncEngineImpl.remoteStore, limboTargetId);\n  syncEngineImpl.activeLimboTargetsByKey =\n    syncEngineImpl.activeLimboTargetsByKey.remove(key);\n  syncEngineImpl.activeLimboResolutionsByTarget.delete(limboTargetId);\n  pumpEnqueuedLimboResolutions(syncEngineImpl);\n}\n\nfunction updateTrackedLimbos(\n  syncEngineImpl: SyncEngineImpl,\n  targetId: TargetId,\n  limboChanges: LimboDocumentChange[]\n): void {\n  for (const limboChange of limboChanges) {\n    if (limboChange instanceof AddedLimboDocument) {\n      syncEngineImpl.limboDocumentRefs.addReference(limboChange.key, targetId);\n      trackLimboChange(syncEngineImpl, limboChange);\n    } else if (limboChange instanceof RemovedLimboDocument) {\n      logDebug(LOG_TAG, 'Document no longer in limbo: ' + limboChange.key);\n      syncEngineImpl.limboDocumentRefs.removeReference(\n        limboChange.key,\n        targetId\n      );\n      const isReferenced = syncEngineImpl.limboDocumentRefs.containsKey(\n        limboChange.key\n      );\n      if (!isReferenced) {\n        // We removed the last reference for this key\n        removeLimboTarget(syncEngineImpl, limboChange.key);\n      }\n    } else {\n      fail(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<DocumentKey, TargetId> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  return syncEngineImpl.activeLimboTargetsByKey;\n}\n\n// Visible for testing\nexport function syncEngineGetEnqueuedLimboDocumentResolutions(\n  syncEngine: SyncEngine\n): Set<string> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  return syncEngineImpl.enqueuedLimboResolutions;\n}\n\nexport async function syncEngineEmitNewSnapsAndNotifyLocalStore(\n  syncEngine: SyncEngine,\n  changes: DocumentMap,\n  remoteEvent?: RemoteEvent\n): Promise<void> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  const newSnaps: ViewSnapshot[] = [];\n  const docChangesInAllViews: LocalViewChanges[] = [];\n  const queriesProcessed: Array<Promise<void>> = [];\n\n  if (syncEngineImpl.queryViewsByQuery.isEmpty()) {\n    // Return early since `onWatchChange()` might not have been assigned yet.\n    return;\n  }\n\n  syncEngineImpl.queryViewsByQuery.forEach((_, queryView) => {\n    debugAssert(\n      !!syncEngineImpl.applyDocChanges,\n      'ApplyDocChangesHandler not set'\n    );\n    queriesProcessed.push(\n      syncEngineImpl\n        .applyDocChanges(queryView, changes, remoteEvent)\n        .then(viewSnapshot => {\n          // If there are changes, or we are handling a global snapshot, notify\n          // secondary clients to update query state.\n          if (viewSnapshot || remoteEvent) {\n            if (syncEngineImpl.isPrimaryClient) {\n              // 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<ViewSnapshot | undefined> {\n  let viewDocChanges = queryView.view.computeDocChanges(changes);\n  if (viewDocChanges.needsRefill) {\n    // The query has a limit and some docs were removed, so we need\n    // to re-run the query against the local store to make sure we\n    // didn't lose any good docs that had been past the limit.\n    viewDocChanges = await localStoreExecuteQuery(\n      syncEngineImpl.localStore,\n      queryView.query,\n      /* usePreviousResults= */ false\n    ).then(({ documents }) => {\n      return queryView.view.computeDocChanges(documents, viewDocChanges);\n    });\n  }\n\n  const targetChange =\n    remoteEvent && remoteEvent.targetChanges.get(queryView.targetId);\n  const targetIsPendingReset =\n    remoteEvent && remoteEvent.targetMismatches.get(queryView.targetId) != null;\n  const viewChange = queryView.view.applyChanges(\n    viewDocChanges,\n    /* limboResolutionEnabled= */ syncEngineImpl.isPrimaryClient,\n    targetChange,\n    targetIsPendingReset\n  );\n  updateTrackedLimbos(\n    syncEngineImpl,\n    queryView.targetId,\n    viewChange.limboChanges\n  );\n  return viewChange.snapshot;\n}\n\nexport async function syncEngineHandleCredentialChange(\n  syncEngine: SyncEngine,\n  user: User\n): Promise<void> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  const userChanged = !syncEngineImpl.currentUser.isEqual(user);\n\n  if (userChanged) {\n    logDebug(LOG_TAG, 'User change. New user:', user.toKey());\n\n    const result = await localStoreHandleUserChange(\n      syncEngineImpl.localStore,\n      user\n    );\n    syncEngineImpl.currentUser = user;\n\n    // Fails tasks waiting for pending writes requested by previous user.\n    rejectOutstandingPendingWritesCallbacks(\n      syncEngineImpl,\n      \"'waitForPendingWrites' promise is rejected due to a user change.\"\n    );\n    // TODO(b/114226417): Consider calling this only in the primary tab.\n    syncEngineImpl.sharedClientState.handleUserChange(\n      user,\n      result.removedBatchIds,\n      result.addedBatchIds\n    );\n    await syncEngineEmitNewSnapsAndNotifyLocalStore(\n      syncEngineImpl,\n      result.affectedDocuments\n    );\n  }\n}\n\nexport function syncEngineGetRemoteKeysForTarget(\n  syncEngine: SyncEngine,\n  targetId: TargetId\n): DocumentKeySet {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  const limboResolution =\n    syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n  if (limboResolution && limboResolution.receivedDocument) {\n    return documentKeySet().add(limboResolution.key);\n  } else {\n    let keySet = documentKeySet();\n    const queries = syncEngineImpl.queriesByTarget.get(targetId);\n    if (!queries) {\n      return keySet;\n    }\n    for (const query of queries ?? []) {\n      const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n      debugAssert(\n        !!queryView,\n        `No query view found for ${stringifyQueryOrPipeline(query)}`\n      );\n      keySet = keySet.unionWith(queryView.view.syncedDocuments);\n    }\n    return keySet;\n  }\n}\n\n/**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */\nasync function synchronizeViewAndComputeSnapshot(\n  syncEngine: SyncEngine,\n  queryView: QueryView\n): Promise<ViewChange> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  const queryResult = await localStoreExecuteQuery(\n    syncEngineImpl.localStore,\n    queryView.query,\n    /* usePreviousResults= */ true\n  );\n  const viewSnapshot =\n    queryView.view.synchronizeWithPersistedState(queryResult);\n  if (syncEngineImpl.isPrimaryClient) {\n    updateTrackedLimbos(\n      syncEngineImpl,\n      queryView.targetId,\n      viewSnapshot.limboChanges\n    );\n  }\n  return viewSnapshot;\n}\n\n/**\n * Retrieves newly changed documents from remote document cache and raises\n * snapshots if needed.\n */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineSynchronizeWithChangedDocuments(\n  syncEngine: SyncEngine,\n  collectionGroup: string\n): Promise<void> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n  return localStoreGetNewDocumentChanges(\n    syncEngineImpl.localStore,\n    collectionGroup\n  ).then(changes =>\n    syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes)\n  );\n}\n\n/** Applies a mutation state to an existing batch.  */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyBatchState(\n  syncEngine: SyncEngine,\n  batchId: BatchId,\n  batchState: MutationBatchState,\n  error?: FirestoreError\n): Promise<void> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  const documents = await localStoreLookupMutationDocuments(\n    syncEngineImpl.localStore,\n    batchId\n  );\n\n  if (documents === null) {\n    // A throttled tab may not have seen the mutation before it was completed\n    // and removed from the mutation queue, in which case we won't have cached\n    // the affected documents. In this case we can safely ignore the update\n    // since that means we didn't apply the mutation locally at all (if we\n    // had, we would have cached the affected documents), and so we will just\n    // see any resulting document changes via normal remote document updates\n    // as applicable.\n    logDebug(LOG_TAG, 'Cannot apply mutation batch with id: ' + batchId);\n    return;\n  }\n\n  if (batchState === 'pending') {\n    // If we are the primary client, we need to send this write to the\n    // backend. Secondary clients will ignore these writes since their remote\n    // connection is disabled.\n    await fillWritePipeline(syncEngineImpl.remoteStore);\n  } else if (batchState === 'acknowledged' || batchState === 'rejected') {\n    // NOTE: Both these methods are no-ops for batches that originated from\n    // other clients.\n    processUserCallback(syncEngineImpl, batchId, error ? error : null);\n    triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n    localStoreRemoveCachedMutationBatchMetadata(\n      syncEngineImpl.localStore,\n      batchId\n    );\n  } else {\n    fail(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<void> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  ensureWatchCallbacks(syncEngineImpl);\n  syncEngineEnsureWriteCallbacks(syncEngineImpl);\n  if (isPrimary === true && syncEngineImpl._isPrimaryClient !== true) {\n    // Secondary tabs only maintain Views for their local listeners and the\n    // Views internal state may not be 100% populated (in particular\n    // secondary tabs don't track syncedDocuments, the set of documents the\n    // server considers to be in the target). So when a secondary becomes\n    // primary, we need to need to make sure that all views for all targets\n    // match the state on disk.\n    const activeTargets =\n      syncEngineImpl.sharedClientState.getAllActiveQueryTargets();\n    const activeQueries = await synchronizeQueryViewsAndRaiseSnapshots(\n      syncEngineImpl,\n      activeTargets.toArray(),\n      /*transitionToPrimary=*/ true\n    );\n    syncEngineImpl._isPrimaryClient = true;\n    await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, true);\n    for (const targetData of activeQueries) {\n      remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n    }\n  } else if (isPrimary === false && syncEngineImpl._isPrimaryClient !== false) {\n    const activeTargets: TargetId[] = [];\n\n    let p = Promise.resolve();\n    syncEngineImpl.queriesByTarget.forEach((_, targetId) => {\n      if (syncEngineImpl.sharedClientState.isLocalQueryTarget(targetId)) {\n        activeTargets.push(targetId);\n      } else {\n        p = p.then(() => {\n          removeAndCleanupTarget(syncEngineImpl, targetId);\n          return localStoreReleaseTarget(\n            syncEngineImpl.localStore,\n            targetId,\n            /*keepPersistedTargetData=*/ true\n          );\n        });\n      }\n      remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n    });\n    await p;\n\n    await synchronizeQueryViewsAndRaiseSnapshots(\n      syncEngineImpl,\n      activeTargets,\n      /*transitionToPrimary=*/ false\n    );\n    resetLimboDocuments(syncEngineImpl);\n    syncEngineImpl._isPrimaryClient = false;\n    await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, false);\n  }\n}\n\n// PORTING NOTE: Multi-Tab only.\nfunction resetLimboDocuments(syncEngine: SyncEngine): void {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  syncEngineImpl.activeLimboResolutionsByTarget.forEach((_, targetId) => {\n    remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n  });\n  syncEngineImpl.limboDocumentRefs.removeAllReferences();\n  syncEngineImpl.activeLimboResolutionsByTarget = new Map<\n    TargetId,\n    LimboResolution\n  >();\n  syncEngineImpl.activeLimboTargetsByKey = new SortedMap<DocumentKey, TargetId>(\n    DocumentKey.comparator\n  );\n}\n\n/**\n * Reconcile the query views of the provided query targets with the state from\n * persistence. Raises snapshots for any changes that affect the local\n * client and returns the updated state of all target's query data.\n *\n * @param syncEngine - The sync engine implementation\n * @param targets - the list of targets with views that need to be recomputed\n * @param transitionToPrimary - `true` iff the tab transitions from a secondary\n * tab to a primary tab\n */\n// PORTING NOTE: Multi-Tab only.\nasync function synchronizeQueryViewsAndRaiseSnapshots(\n  syncEngine: SyncEngine,\n  targets: TargetId[],\n  transitionToPrimary: boolean\n): Promise<TargetData[]> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  const activeQueries: TargetData[] = [];\n  const newViewSnapshots: ViewSnapshot[] = [];\n  for (const targetId of targets) {\n    let targetData: TargetData;\n    const queries = syncEngineImpl.queriesByTarget.get(targetId);\n\n    if (queries && queries.length !== 0) {\n      // For queries that have a local View, we fetch their current state\n      // from LocalStore (as the resume token and the snapshot version\n      // might have changed) and reconcile their views with the persisted\n      // state (the list of syncedDocuments may have gotten out of sync).\n      targetData = await localStoreAllocateTarget(\n        syncEngineImpl.localStore,\n        isPipeline(queries[0]) ? queries[0] : 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 ${stringifyQueryOrPipeline(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: TargetOrPipeline): QueryOrPipeline {\n  return targetIsPipelineTarget(target)\n    ? target\n    : newQuery(\n        target.path,\n        target.collectionGroup,\n        target.orderBy,\n        target.filters,\n        target.limit,\n        LimitType.First,\n        target.startAt,\n        target.endAt\n      );\n}\n\n/** Returns the IDs of the clients that are currently active. */\n// PORTING NOTE: Multi-Tab only.\nexport function syncEngineGetActiveClients(\n  syncEngine: SyncEngine\n): Promise<ClientId[]> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  return localStoreGetActiveClients(syncEngineImpl.localStore);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyTargetState(\n  syncEngine: SyncEngine,\n  targetId: TargetId,\n  state: QueryTargetState,\n  error?: FirestoreError\n): Promise<void> {\n  const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n  if (syncEngineImpl._isPrimaryClient) {\n    // If we receive a target state notification via WebStorage, we are\n    // either already secondary or another tab has taken the primary lease.\n    logDebug(LOG_TAG, 'Ignoring unexpected query state notification.');\n    return;\n  }\n\n  const query = syncEngineImpl.queriesByTarget.get(targetId);\n  if (query && query.length > 0) {\n    switch (state) {\n      case 'current':\n      case 'not-current': {\n        let changes: DocumentMap;\n        if (isPipeline(query[0])) {\n          switch (getPipelineSourceType(query[0])) {\n            case 'collection_group':\n            case 'collection':\n              changes = await localStoreGetNewDocumentChanges(\n                syncEngineImpl.localStore,\n                getPipelineCollectionId(query[0])!\n              );\n              break;\n            case 'documents':\n              changes = await localStoreGetDocuments(\n                syncEngineImpl.localStore,\n                query[0]!\n              );\n              break;\n            case 'database':\n            case 'unknown':\n            default:\n              logWarn('');\n              changes = documentMap();\n              break;\n          }\n        } else {\n          changes = await localStoreGetNewDocumentChanges(\n            syncEngineImpl.localStore,\n            queryCollectionGroup(query[0])\n          );\n        }\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<void> {\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<Set<string>> {\n  try {\n    const metadata = await reader.getMetadata();\n    const skip = await localStoreHasNewerBundle(\n      syncEngine.localStore,\n      metadata\n    );\n    if (skip) {\n      await reader.close();\n      task._completeWith(bundleSuccessProgress(metadata));\n      return Promise.resolve(new Set<string>());\n    }\n\n    task._updateProgress(bundleInitialProgress(metadata));\n\n    const loader = new BundleLoader(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<string>());\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport {\n  IndexBackfiller,\n  IndexBackfillerScheduler\n} from '../local/index_backfiller';\nimport {\n  indexedDbStoragePrefix,\n  IndexedDbPersistence\n} from '../local/indexeddb_persistence';\nimport { LocalStore } from '../local/local_store';\nimport { newLocalStore } from '../local/local_store_impl';\nimport { LruParams } from '../local/lru_garbage_collector';\nimport { LruScheduler } from '../local/lru_garbage_collector_impl';\nimport {\n  MemoryEagerDelegate,\n  MemoryLruDelegate,\n  MemoryPersistence\n} from '../local/memory_persistence';\nimport { Scheduler, Persistence } from '../local/persistence';\nimport { QueryEngine } from '../local/query_engine';\nimport {\n  ClientId,\n  MemorySharedClientState,\n  SharedClientState,\n  WebStorageSharedClientState\n} from '../local/shared_client_state';\nimport { newConnection, newConnectivityMonitor } from '../platform/connection';\nimport { getDocument, getWindow } from '../platform/dom';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport {\n  fillWritePipeline,\n  newRemoteStore,\n  RemoteStore,\n  remoteStoreApplyPrimaryState,\n  remoteStoreShutdown\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { DatabaseInfo } from './database_info';\nimport { EventManager, newEventManager } from './event_manager';\nimport { SyncEngine } from './sync_engine';\nimport {\n  newSyncEngine,\n  syncEngineApplyActiveTargetsChange,\n  syncEngineApplyBatchState,\n  syncEngineApplyOnlineStateChange,\n  syncEngineApplyPrimaryState,\n  syncEngineApplyTargetState,\n  syncEngineEnsureWriteCallbacks,\n  syncEngineGetActiveClients,\n  syncEngineHandleCredentialChange,\n  syncEngineSynchronizeWithChangedDocuments\n} from './sync_engine_impl';\nimport { OnlineStateSource } from './types';\n\ntype Kind = 'memory' | 'persistent';\n\nexport interface ComponentConfiguration {\n  asyncQueue: AsyncQueue;\n  databaseInfo: DatabaseInfo;\n  authCredentials: CredentialsProvider<User>;\n  appCheckCredentials: CredentialsProvider<string>;\n  clientId: ClientId;\n  initialUser: User;\n  maxConcurrentLimboResolutions: number;\n}\n\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<void>;\n\n  terminate(): Promise<void>;\n}\n\n/**\n * Provides all components needed for Firestore with in-memory persistence.\n * Uses EagerGC garbage collection.\n */\nexport class MemoryOfflineComponentProvider\n  implements OfflineComponentProvider\n{\n  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<void> {\n    this.serializer = newSerializer(cfg.databaseInfo.databaseId);\n    this.sharedClientState = this.createSharedClientState(cfg);\n    this.persistence = this.createPersistence(cfg);\n    await this.persistence.start();\n    this.localStore = this.createLocalStore(cfg);\n    this.gcScheduler = this.createGarbageCollectionScheduler(\n      cfg,\n      this.localStore\n    );\n    this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(\n      cfg,\n      this.localStore\n    );\n  }\n\n  createGarbageCollectionScheduler(\n    cfg: ComponentConfiguration,\n    localStore: LocalStore\n  ): Scheduler | null {\n    return null;\n  }\n\n  createIndexBackfillerScheduler(\n    cfg: ComponentConfiguration,\n    localStore: LocalStore\n  ): Scheduler | null {\n    return null;\n  }\n\n  createLocalStore(cfg: ComponentConfiguration): LocalStore {\n    return newLocalStore(\n      this.persistence,\n      new QueryEngine(),\n      cfg.initialUser,\n      this.serializer\n    );\n  }\n\n  createPersistence(cfg: ComponentConfiguration): Persistence {\n    return new MemoryPersistence(MemoryEagerDelegate.factory, this.serializer);\n  }\n\n  createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n    return new MemorySharedClientState();\n  }\n\n  async terminate(): Promise<void> {\n    this.gcScheduler?.stop();\n    this.indexBackfillerScheduler?.stop();\n    this.sharedClientState.shutdown();\n    await this.persistence.shutdown();\n  }\n}\n\nexport class LruGcMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider {\n  constructor(protected readonly cacheSizeBytes: number | undefined) {\n    super();\n  }\n\n  createGarbageCollectionScheduler(\n    cfg: ComponentConfiguration,\n    localStore: LocalStore\n  ): Scheduler | null {\n    hardAssert(\n      this.persistence.referenceDelegate instanceof MemoryLruDelegate,\n      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<void> {\n    await super.initialize(cfg);\n\n    await this.onlineComponentProvider.initialize(this, cfg);\n\n    // Enqueue writes from a previous session\n    await syncEngineEnsureWriteCallbacks(\n      this.onlineComponentProvider.syncEngine\n    );\n    await fillWritePipeline(this.onlineComponentProvider.remoteStore);\n\n    // NOTE: This will immediately call the listener, so we make sure to\n    // set it after localStore / remoteStore are started.\n    await this.persistence.setPrimaryStateListener(() => {\n      if (this.gcScheduler && !this.gcScheduler.started) {\n        this.gcScheduler.start();\n      }\n      if (\n        this.indexBackfillerScheduler &&\n        !this.indexBackfillerScheduler.started\n      ) {\n        this.indexBackfillerScheduler.start();\n      }\n      return Promise.resolve();\n    });\n  }\n\n  createLocalStore(cfg: ComponentConfiguration): LocalStore {\n    return newLocalStore(\n      this.persistence,\n      new QueryEngine(),\n      cfg.initialUser,\n      this.serializer\n    );\n  }\n\n  createGarbageCollectionScheduler(\n    cfg: ComponentConfiguration,\n    localStore: LocalStore\n  ): Scheduler | null {\n    const garbageCollector =\n      this.persistence.referenceDelegate.garbageCollector;\n    return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore);\n  }\n\n  createIndexBackfillerScheduler(\n    cfg: ComponentConfiguration,\n    localStore: LocalStore\n  ): Scheduler | null {\n    const indexBackfiller = new IndexBackfiller(localStore, this.persistence);\n    return new IndexBackfillerScheduler(cfg.asyncQueue, indexBackfiller);\n  }\n\n  createPersistence(cfg: ComponentConfiguration): IndexedDbPersistence {\n    const persistenceKey = indexedDbStoragePrefix(\n      cfg.databaseInfo.databaseId,\n      cfg.databaseInfo.persistenceKey\n    );\n    const lruParams =\n      this.cacheSizeBytes !== undefined\n        ? LruParams.withCacheSize(this.cacheSizeBytes)\n        : LruParams.DEFAULT;\n\n    return new IndexedDbPersistence(\n      this.synchronizeTabs,\n      persistenceKey,\n      cfg.clientId,\n      lruParams,\n      cfg.asyncQueue,\n      getWindow(),\n      getDocument(),\n      this.serializer,\n      this.sharedClientState,\n      !!this.forceOwnership\n    );\n  }\n\n  createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n    return new MemorySharedClientState();\n  }\n}\n\n/**\n * Provides all components needed for Firestore with multi-tab IndexedDB\n * persistence.\n *\n * In the legacy client, this provider is used to provide both multi-tab and\n * non-multi-tab persistence since we cannot tell at build time whether\n * `synchronizeTabs` will be enabled.\n */\nexport class MultiTabOfflineComponentProvider extends IndexedDbOfflineComponentProvider {\n  synchronizeTabs = true;\n\n  constructor(\n    protected readonly onlineComponentProvider: OnlineComponentProvider,\n    protected readonly cacheSizeBytes: number | undefined\n  ) {\n    super(onlineComponentProvider, cacheSizeBytes, /* forceOwnership= */ false);\n  }\n\n  async initialize(cfg: ComponentConfiguration): Promise<void> {\n    await super.initialize(cfg);\n\n    const syncEngine = this.onlineComponentProvider.syncEngine;\n\n    if (this.sharedClientState instanceof WebStorageSharedClientState) {\n      this.sharedClientState.syncEngine = {\n        applyBatchState: syncEngineApplyBatchState.bind(null, syncEngine),\n        applyTargetState: syncEngineApplyTargetState.bind(null, syncEngine),\n        applyActiveTargetsChange: syncEngineApplyActiveTargetsChange.bind(\n          null,\n          syncEngine\n        ),\n        getActiveClients: syncEngineGetActiveClients.bind(null, syncEngine),\n        synchronizeWithChangedDocuments:\n          syncEngineSynchronizeWithChangedDocuments.bind(null, syncEngine)\n      };\n      await this.sharedClientState.start();\n    }\n\n    // NOTE: This will immediately call the listener, so we make sure to\n    // set it after localStore / remoteStore are started.\n    await this.persistence.setPrimaryStateListener(async isPrimary => {\n      await syncEngineApplyPrimaryState(\n        this.onlineComponentProvider.syncEngine,\n        isPrimary\n      );\n      if (this.gcScheduler) {\n        if (isPrimary && !this.gcScheduler.started) {\n          this.gcScheduler.start();\n        } else if (!isPrimary) {\n          this.gcScheduler.stop();\n        }\n      }\n      if (this.indexBackfillerScheduler) {\n        if (isPrimary && !this.indexBackfillerScheduler.started) {\n          this.indexBackfillerScheduler.start();\n        } else if (!isPrimary) {\n          this.indexBackfillerScheduler.stop();\n        }\n      }\n    });\n  }\n\n  createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n    const window = getWindow();\n    if (!WebStorageSharedClientState.isAvailable(window)) {\n      throw new FirestoreError(\n        Code.UNIMPLEMENTED,\n        'IndexedDB persistence is only available on platforms that support LocalStorage.'\n      );\n    }\n    const persistenceKey = indexedDbStoragePrefix(\n      cfg.databaseInfo.databaseId,\n      cfg.databaseInfo.persistenceKey\n    );\n    return new WebStorageSharedClientState(\n      window,\n      cfg.asyncQueue,\n      persistenceKey,\n      cfg.clientId,\n      cfg.initialUser\n    );\n  }\n}\n\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<void> {\n    if (this.localStore) {\n      // OnlineComponentProvider may get initialized multiple times if\n      // multi-tab persistence is used.\n      return;\n    }\n\n    this.localStore = offlineComponentProvider.localStore;\n    this.sharedClientState = offlineComponentProvider.sharedClientState;\n    this.datastore = this.createDatastore(cfg);\n    this.remoteStore = this.createRemoteStore(cfg);\n    this.eventManager = this.createEventManager(cfg);\n    this.syncEngine = this.createSyncEngine(\n      cfg,\n      /* startAsPrimary=*/ !offlineComponentProvider.synchronizeTabs\n    );\n\n    this.sharedClientState.onlineStateHandler = onlineState =>\n      syncEngineApplyOnlineStateChange(\n        this.syncEngine,\n        onlineState,\n        OnlineStateSource.SharedClientState\n      );\n\n    this.remoteStore.remoteSyncer.handleCredentialChange =\n      syncEngineHandleCredentialChange.bind(null, this.syncEngine);\n\n    await remoteStoreApplyPrimaryState(\n      this.remoteStore,\n      this.syncEngine.isPrimaryClient\n    );\n  }\n\n  createEventManager(cfg: ComponentConfiguration): EventManager {\n    return newEventManager();\n  }\n\n  createDatastore(cfg: ComponentConfiguration): Datastore {\n    const serializer = newSerializer(cfg.databaseInfo.databaseId);\n    const connection = newConnection(cfg.databaseInfo);\n    return newDatastore(\n      cfg.authCredentials,\n      cfg.appCheckCredentials,\n      connection,\n      serializer\n    );\n  }\n\n  createRemoteStore(cfg: ComponentConfiguration): RemoteStore {\n    return newRemoteStore(\n      this.localStore,\n      this.datastore,\n      cfg.asyncQueue,\n      onlineState =>\n        syncEngineApplyOnlineStateChange(\n          this.syncEngine,\n          onlineState,\n          OnlineStateSource.RemoteStore\n        ),\n      newConnectivityMonitor()\n    );\n  }\n\n  createSyncEngine(\n    cfg: ComponentConfiguration,\n    startAsPrimary: boolean\n  ): SyncEngine {\n    return newSyncEngine(\n      this.localStore,\n      this.remoteStore,\n      this.eventManager,\n      this.sharedClientState,\n      cfg.initialUser,\n      cfg.maxConcurrentLimboResolutions,\n      startAsPrimary\n    );\n  }\n\n  async terminate(): Promise<void> {\n    await remoteStoreShutdown(this.remoteStore);\n    this.datastore?.terminate();\n    this.eventManager?.terminate();\n  }\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 '../lite-api/database';\nimport { BooleanExpression, Ordering } from '../lite-api/expressions';\nimport { Limit, Sort, Stage, Where } from '../lite-api/stage';\nimport {\n  UserDataReader,\n  UserDataSource,\n  UserData,\n  isUserData\n} from '../lite-api/user_data_reader';\nimport { AbstractUserDataWriter } from '../lite-api/user_data_writer';\nimport {\n  Stage as ProtoStage,\n  StructuredPipeline\n} from '../protos/firestore_proto_api';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\n/**\n * @beta\n * @internal\n *\n * The RealtimePipeline class provides a flexible and expressive framework for building complex data\n * transformation and query pipelines that can be used with Firestore's real-time and offline capabilities.\n *\n * A RealtimePipeline takes data sources, such as Firestore collections or collection groups, and applies\n * a series of stages that are chained together. Each stage takes the output from the previous stage\n * (or the data source) and produces an output for the next stage (or as the final output of the\n * pipeline).\n *\n * Expressions can be used within each stage to filter and transform data through the stage.\n *\n * NOTE: Both the initial and subsequent snapshots for RealtimePipeline take the consideration of the SDK's cache.\n * They might include results that have not been synchronized with the server yet, and wait for subsequent snapshots\n * to reflect the latest server state, this is the same as classic Firestore {@link Query}.\n * This behavior is different from the {@link Pipeline} class, which does not take the consideration of the SDK's cache.\n *\n * Usage Examples:\n *\n * ```typescript\n * const db: Firestore; // Assumes a valid firestore instance.\n *\n * // Example 1: Listen to books published after 1980\n * const unsubscribe = onRealtimePipelineSnapshot(db.realtimePipeline()\n *     .collection(\"books\")\n *     .where(field(\"published\").gt(1980)),\n *     (snapshot) => {\n *       // Handle the snapshot\n *     }\n * );\n * ```\n */\n// TODO(pipeline): Add more examples to showcase functions\nexport class RealtimePipeline {\n  /**\n   * @internal\n   * @private\n   * @param _db\n   * @param userDataReader\n   * @param _userDataWriter\n   * @param _documentReferenceFactory\n   * @param stages\n   */\n  constructor(\n    /**\n     * @internal\n     * @private\n     */\n    public _db: Firestore,\n    /**\n     * @internal\n     * @private\n     */\n    readonly userDataReader: UserDataReader,\n    /**\n     * @internal\n     * @private\n     */\n    public _userDataWriter: AbstractUserDataWriter,\n    readonly stages: Stage[]\n  ) {}\n\n  /**\n   * Reads user data for each expression in the expressionMap.\n   * @param name Name of the calling function. Used for error messages when invalid user data is encountered.\n   * @param expressionMap\n   * @return the expressionMap argument.\n   * @private\n   * @internal\n   */\n  protected readUserData<\n    T extends Map<string, UserData> | UserData[] | UserData\n  >(name: string, expressionMap: T): T {\n    const context = this.userDataReader.createContext(\n      UserDataSource.Argument,\n      name\n    );\n    if (isUserData(expressionMap)) {\n      expressionMap._readUserData(context);\n    } else if (Array.isArray(expressionMap)) {\n      expressionMap.forEach(readableData =>\n        readableData._readUserData(context)\n      );\n    } else {\n      expressionMap.forEach(expr => expr._readUserData(context));\n    }\n    return expressionMap;\n  }\n\n  where(condition: BooleanExpression): RealtimePipeline {\n    const copy = this.stages.map(s => s);\n    this.readUserData('where', condition);\n    copy.push(new Where(condition, {}));\n    return new RealtimePipeline(\n      this._db,\n      this.userDataReader,\n      this._userDataWriter,\n      copy\n    );\n  }\n\n  limit(limit: number): RealtimePipeline {\n    const copy = this.stages.map(s => s);\n    copy.push(new Limit(limit, {}));\n    return new RealtimePipeline(\n      this._db,\n      this.userDataReader,\n      this._userDataWriter,\n      copy\n    );\n  }\n\n  sort(...orderings: Ordering[]): RealtimePipeline;\n  sort(options: { orderings: Ordering[] }): RealtimePipeline;\n  sort(\n    optionsOrOrderings:\n      | Ordering\n      | {\n          orderings: Ordering[];\n        },\n    ...rest: Ordering[]\n  ): RealtimePipeline {\n    const copy = this.stages.map(s => s);\n    // Option object\n    if ('orderings' in optionsOrOrderings) {\n      copy.push(\n        new Sort(this.readUserData('sort', optionsOrOrderings.orderings), {})\n      );\n    } else {\n      // Ordering object\n      copy.push(\n        new Sort(this.readUserData('sort', [optionsOrOrderings, ...rest]), {})\n      );\n    }\n\n    return new RealtimePipeline(\n      this._db,\n      this.userDataReader,\n      this._userDataWriter,\n      copy\n    );\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toStructuredPipeline(\n    jsonProtoSerializer: JsonProtoSerializer\n  ): StructuredPipeline {\n    const stages: ProtoStage[] = this.stages.map(stage =>\n      stage._toProto(jsonProtoSerializer)\n    );\n    return { pipeline: { stages } };\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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<Uint8Array> {\n  debugAssert(\n    bytesPerRead > 0,\n    `toByteStreamReader expects positive bytesPerRead, but got ${bytesPerRead}`\n  );\n  let readFrom = 0;\n  // The TypeScript definition for ReadableStreamReader changed. We use\n  // `any` here to allow this code to compile with different versions.\n  // See https://github.com/microsoft/TypeScript/issues/42970\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  const reader: any = {\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    async read(): Promise<any> {\n      if (readFrom < source.byteLength) {\n        const result = {\n          value: source.slice(readFrom, readFrom + bytesPerRead),\n          done: false\n        } as const;\n        readFrom += bytesPerRead;\n        return result;\n      }\n\n      return { done: true };\n    },\n    async cancel(): Promise<void> {},\n    releaseLock() {},\n    closed: Promise.resolve()\n  };\n  return reader;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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<Uint8Array> {\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<T> that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nexport class AsyncObserver<T> implements Observer<T> {\n  /**\n   * When set to true, will not raise future events. Necessary to deal with\n   * async detachment of listener.\n   */\n  private muted = false;\n\n  constructor(private observer: Partial<Observer<T>>) {}\n\n  next(value: T): void {\n    if (this.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<E>(eventHandler: EventHandler<E>, 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<Uint8Array>\n  | ArrayBuffer\n  | Uint8Array;\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nexport interface BundleReader {\n  serializer: JsonProtoSerializer;\n\n  close(): Promise<void>;\n\n  /**\n   * Returns the metadata of the bundle.\n   */\n  getMetadata(): Promise<BundleMetadata>;\n\n  /**\n   * Returns the next BundleElement (together with its byte size in the bundle)\n   * that has not been read from underlying ReadableStream. Returns null if we\n   * have reached the end of the stream.\n   */\n  nextElement(): Promise<SizedBundleElement | null>;\n}\n\n/**\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<BundleMetadata> = new Deferred<BundleMetadata>();\n  /**\n   * Internal buffer to hold bundle content, accumulating incomplete element\n   * content.\n   */\n  private buffer: Uint8Array = new Uint8Array();\n  /** The decoder used to parse binary data into strings. */\n  private textDecoder: TextDecoder;\n\n  constructor(\n    /** The reader to read from underlying binary bundle data source. */\n    private reader: ReadableStreamDefaultReader<Uint8Array>,\n    readonly serializer: JsonProtoSerializer\n  ) {\n    this.textDecoder = newTextDecoder();\n    // Read the metadata (which is the first element).\n    this.nextElementImpl().then(\n      element => {\n        if (element && element.isBundleMetadata()) {\n          this.metadata.resolve(element.payload.metadata!);\n        } else {\n          this.metadata.reject(\n            new Error(`The first element of the bundle is not a metadata, it is\n             ${JSON.stringify(element?.payload)}`)\n          );\n        }\n      },\n      error => this.metadata.reject(error)\n    );\n  }\n\n  close(): Promise<void> {\n    return this.reader.cancel();\n  }\n\n  async getMetadata(): Promise<BundleMetadata> {\n    return this.metadata.promise;\n  }\n\n  async nextElement(): Promise<SizedBundleElement | null> {\n    // Makes sure metadata is read before proceeding.\n    await this.getMetadata();\n    return this.nextElementImpl();\n  }\n\n  /**\n   * Reads from the head of internal buffer, and pulling more data from\n   * underlying stream if a complete element cannot be found, until an\n   * element(including the prefixed length and the JSON string) is found.\n   *\n   * Once a complete element is read, it is dropped from internal buffer.\n   *\n   * Returns either the bundled element, or null if we have reached the end of\n   * the stream.\n   */\n  private async nextElementImpl(): Promise<SizedBundleElement | null> {\n    const lengthBuffer = await this.readLength();\n    if (lengthBuffer === null) {\n      return null;\n    }\n\n    const lengthString = this.textDecoder.decode(lengthBuffer);\n    const length = Number(lengthString);\n    if (isNaN(length)) {\n      this.raiseError(`length string (${lengthString}) is not valid number`);\n    }\n\n    const jsonString = await this.readJsonString(length);\n\n    return new SizedBundleElement(\n      JSON.parse(jsonString),\n      lengthBuffer.length + length\n    );\n  }\n\n  /** First index of '{' from the underlying buffer. */\n  private indexOfOpenBracket(): number {\n    return this.buffer.findIndex(v => v === '{'.charCodeAt(0));\n  }\n\n  /**\n   * Reads from the beginning of the internal buffer, until the first '{', and\n   * return the content.\n   *\n   * If reached end of the stream, returns a null.\n   */\n  private async readLength(): Promise<Uint8Array | null> {\n    while (this.indexOfOpenBracket() < 0) {\n      const done = await this.pullMoreDataToBuffer();\n      if (done) {\n        break;\n      }\n    }\n\n    // Broke out of the loop because underlying stream is closed, and there\n    // happens to be no more data to process.\n    if (this.buffer.length === 0) {\n      return null;\n    }\n\n    const position = this.indexOfOpenBracket();\n    // Broke out of the loop because underlying stream is closed, but still\n    // cannot find an open bracket.\n    if (position < 0) {\n      this.raiseError(\n        'Reached the end of bundle when a length string is expected.'\n      );\n    }\n\n    const result = this.buffer.slice(0, position);\n    // Update the internal buffer to drop the read length.\n    this.buffer = this.buffer.slice(position);\n    return result;\n  }\n\n  /**\n   * Reads from a specified position from the internal buffer, for a specified\n   * number of bytes, pulling more data from the underlying stream if needed.\n   *\n   * Returns a string decoded from the read bytes.\n   */\n  private async readJsonString(length: number): Promise<string> {\n    while (this.buffer.length < length) {\n      const done = await this.pullMoreDataToBuffer();\n      if (done) {\n        this.raiseError('Reached the end of bundle when more is expected.');\n      }\n    }\n\n    const result = this.textDecoder.decode(this.buffer.slice(0, length));\n    // Update the internal buffer to drop the read json string.\n    this.buffer = this.buffer.slice(length);\n    return result;\n  }\n\n  private raiseError(message: string): void {\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.reader.cancel();\n    throw new Error(`Invalid bundle format: ${message}`);\n  }\n\n  /**\n   * Pulls more data from underlying stream to internal buffer.\n   * Returns a boolean indicating whether the stream is finished.\n   */\n  private async pullMoreDataToBuffer(): Promise<boolean> {\n    const result = await this.reader.read();\n    if (!result.done) {\n      debugAssert(!!result.value, 'Read undefined when \"done\" is false.');\n      const newBuffer = new Uint8Array(\n        this.buffer.length + result.value!.length\n      );\n      newBuffer.set(this.buffer);\n      newBuffer.set(result.value!, this.buffer.length);\n      this.buffer = newBuffer;\n    }\n    return result.done;\n  }\n}\n\nexport function newBundleReader(\n  reader: ReadableStreamDefaultReader<Uint8Array>,\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</* path */ string, SnapshotVersion>();\n  private mutations: Mutation[] = [];\n  private committed = false;\n\n  /**\n   * A deferred usage error that occurred previously in this transaction that\n   * will cause the transaction to fail once it actually commits.\n   */\n  private lastTransactionError: FirestoreError | null = null;\n\n  /**\n   * Set of documents that have been written in the transaction.\n   *\n   * When there's more than one write to the same key in a transaction, any\n   * writes after the first are handled differently.\n   */\n  private writtenDocs: Set</* path= */ string> = new Set();\n\n  constructor(private datastore: Datastore) {}\n\n  async lookup(keys: DocumentKey[]): Promise<Document[]> {\n    this.ensureCommitNotCalled();\n\n    if (this.mutations.length > 0) {\n      this.lastTransactionError = new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Firestore transactions require all reads to be executed before all writes.'\n      );\n      throw this.lastTransactionError;\n    }\n    const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n    docs.forEach(doc => this.recordVersion(doc));\n    return docs;\n  }\n\n  set(key: DocumentKey, data: ParsedSetData): void {\n    this.write(data.toMutation(key, this.precondition(key)));\n    this.writtenDocs.add(key.toString());\n  }\n\n  update(key: DocumentKey, data: ParsedUpdateData): void {\n    try {\n      this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n    } catch (e) {\n      this.lastTransactionError = e as FirestoreError | null;\n    }\n    this.writtenDocs.add(key.toString());\n  }\n\n  delete(key: DocumentKey): void {\n    this.write(new DeleteMutation(key, this.precondition(key)));\n    this.writtenDocs.add(key.toString());\n  }\n\n  async commit(): Promise<void> {\n    this.ensureCommitNotCalled();\n\n    if (this.lastTransactionError) {\n      throw this.lastTransactionError;\n    }\n    const unwritten = this.readVersions;\n    // For each mutation, note that the doc was written.\n    this.mutations.forEach(mutation => {\n      unwritten.delete(mutation.key.toString());\n    });\n    // For each document that was read but not written to, we want to perform\n    // a `verify` operation.\n    unwritten.forEach((_, path) => {\n      const key = DocumentKey.fromPath(path);\n      this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n    });\n    await invokeCommitRpc(this.datastore, this.mutations);\n    this.committed = true;\n  }\n\n  private recordVersion(doc: Document): void {\n    let docVersion: SnapshotVersion;\n\n    if (doc.isFoundDocument()) {\n      docVersion = doc.version;\n    } else if (doc.isNoDocument()) {\n      // Represent a deleted doc using SnapshotVersion.min().\n      docVersion = SnapshotVersion.min();\n    } else {\n      throw fail(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<T> {\n  private attemptsRemaining: number;\n  private backoff: ExponentialBackoff;\n\n  constructor(\n    private readonly asyncQueue: AsyncQueue,\n    private readonly datastore: Datastore,\n    private readonly options: TransactionOptions,\n    private readonly updateFunction: (transaction: Transaction) => Promise<T>,\n    private readonly deferred: Deferred<T>\n  ) {\n    this.attemptsRemaining = options.maxAttempts;\n    this.backoff = new ExponentialBackoff(\n      this.asyncQueue,\n      TimerId.TransactionRetry\n    );\n  }\n\n  /** Runs the transaction and sets the result on deferred. */\n  run(): void {\n    this.attemptsRemaining -= 1;\n    this.runWithBackOff();\n  }\n\n  private runWithBackOff(): void {\n    this.backoff.backoffAndRun(async () => {\n      const transaction = new Transaction(this.datastore);\n      const userPromise = this.tryRunUpdateFunction(transaction);\n      if (userPromise) {\n        userPromise\n          .then(result => {\n            this.asyncQueue.enqueueAndForget(() => {\n              return transaction\n                .commit()\n                .then(() => {\n                  this.deferred.resolve(result);\n                })\n                .catch(commitError => {\n                  this.handleTransactionError(commitError);\n                });\n            });\n          })\n          .catch(userPromiseError => {\n            this.handleTransactionError(userPromiseError);\n          });\n      }\n    });\n  }\n\n  private tryRunUpdateFunction(transaction: Transaction): Promise<T> | null {\n    try {\n      const userPromise = this.updateFunction(transaction);\n      if (\n        isNullOrUndefined(userPromise) ||\n        !userPromise.catch ||\n        !userPromise.then\n      ) {\n        this.deferred.reject(\n          Error('Transaction callback must return a Promise')\n        );\n        return null;\n      }\n      return userPromise;\n    } catch (error) {\n      // Do not retry errors thrown by user provided updateFunction.\n      this.deferred.reject(error as Error);\n      return null;\n    }\n  }\n\n  private handleTransactionError(error: Error): void {\n    if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n      this.attemptsRemaining -= 1;\n      this.asyncQueue.enqueueAndForget(() => {\n        this.runWithBackOff();\n        return Promise.resolve();\n      });\n    } else {\n      this.deferred.reject(error);\n    }\n  }\n\n  private isRetryableTransactionError(error: Error | 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 { RealtimePipeline } from '../api/realtime_pipeline';\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 { PipelineStreamElement } from '../model/pipeline_stream_element';\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 {\n  Datastore,\n  invokeExecutePipeline,\n  invokeRunAggregationQueryRpc\n} 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 { QueryOrPipeline, toCorePipeline } from './pipeline-util';\nimport { newQueryForPath, Query } from './query';\nimport { StructuredPipeline } from './structured_pipeline';\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<User> = () =>\n    Promise.resolve();\n  private appCheckCredentialListener: (\n    appCheckToken: string,\n    user: User\n  ) => Promise<void> = () => 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<User>,\n    private appCheckCredentials: CredentialsProvider<string>,\n    /**\n     * Asynchronous queue responsible for all of our internal processing. When\n     * we get incoming work from the user (via public API) or the network\n     * (incoming GRPC messages), we should always schedule onto this queue.\n     * This ensures all of our work is properly serialized (e.g. we don't\n     * start processing a new operation while the previous one is waiting for\n     * an async I/O to complete).\n     */\n    public asyncQueue: AsyncQueue,\n    /**\n     * Exposed for testing\n     */\n    public _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>): void {\n    this.authCredentialListener = listener;\n  }\n\n  setAppCheckTokenChangeListener(\n    listener: (appCheckToken: string, user: User) => Promise<void>\n  ): void {\n    this.appCheckCredentialListener = listener;\n  }\n\n  terminate(): Promise<void> {\n    this.asyncQueue.enterRestrictedMode();\n    const deferred = new Deferred();\n    this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async () => {\n      try {\n        if (this._onlineComponents) {\n          await this._onlineComponents.terminate();\n        }\n        if (this._offlineComponents) {\n          await this._offlineComponents.terminate();\n        }\n\n        // The credentials provider must be terminated after shutting down the\n        // RemoteStore as it will prevent the RemoteStore from retrieving auth\n        // tokens.\n        this.authCredentials.shutdown();\n        this.appCheckCredentials.shutdown();\n        deferred.resolve();\n      } catch (e) {\n        const firestoreError = wrapInUserErrorIfRecoverable(\n          e as Error,\n          `Failed to shutdown persistence`\n        );\n        deferred.reject(firestoreError);\n      }\n    });\n    return deferred.promise;\n  }\n}\n\nexport async function setOfflineComponentProvider(\n  client: FirestoreClient,\n  offlineComponentProvider: OfflineComponentProvider\n): Promise<void> {\n  client.asyncQueue.verifyOperationInProgress();\n\n  logDebug(LOG_TAG, 'Initializing OfflineComponentProvider');\n  const configuration = client.configuration;\n  await offlineComponentProvider.initialize(configuration);\n\n  let currentUser = configuration.initialUser;\n  client.setCredentialChangeListener(async user => {\n    if (!currentUser.isEqual(user)) {\n      await localStoreHandleUserChange(\n        offlineComponentProvider.localStore,\n        user\n      );\n      currentUser = user;\n    }\n  });\n\n  // When a user calls clearPersistence() in one client, all other clients\n  // need to be terminated to allow the delete to succeed.\n  offlineComponentProvider.persistence.setDatabaseDeletedListener(() =>\n    client.terminate()\n  );\n\n  client._offlineComponents = offlineComponentProvider;\n}\n\nexport async function setOnlineComponentProvider(\n  client: FirestoreClient,\n  onlineComponentProvider: OnlineComponentProvider\n): Promise<void> {\n  client.asyncQueue.verifyOperationInProgress();\n\n  const 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<OfflineComponentProvider> {\n  if (!client._offlineComponents) {\n    if (client._uninitializedComponentsProvider) {\n      logDebug(LOG_TAG, 'Using user provided OfflineComponentProvider');\n      try {\n        await setOfflineComponentProvider(\n          client,\n          client._uninitializedComponentsProvider._offline\n        );\n      } catch (e) {\n        const error = e as FirestoreError | DOMException;\n        if (!canFallbackFromIndexedDbError(error)) {\n          throw error;\n        }\n        logWarn(\n          'Error using user provided cache. Falling back to ' +\n            'memory cache: ' +\n            error\n        );\n        await setOfflineComponentProvider(\n          client,\n          new MemoryOfflineComponentProvider()\n        );\n      }\n    } else {\n      logDebug(LOG_TAG, 'Using default OfflineComponentProvider');\n      await setOfflineComponentProvider(\n        client,\n        new LruGcMemoryOfflineComponentProvider(undefined)\n      );\n    }\n  }\n\n  return client._offlineComponents!;\n}\n\nexport async function ensureOnlineComponents(\n  client: FirestoreClient\n): Promise<OnlineComponentProvider> {\n  if (!client._onlineComponents) {\n    if (client._uninitializedComponentsProvider) {\n      logDebug(LOG_TAG, 'Using user provided OnlineComponentProvider');\n      await setOnlineComponentProvider(\n        client,\n        client._uninitializedComponentsProvider._online\n      );\n    } else {\n      logDebug(LOG_TAG, 'Using default OnlineComponentProvider');\n      await setOnlineComponentProvider(client, new OnlineComponentProvider());\n    }\n  }\n\n  return client._onlineComponents!;\n}\n\nfunction getPersistence(client: FirestoreClient): Promise<Persistence> {\n  return ensureOfflineComponents(client).then(c => c.persistence);\n}\n\nexport function getLocalStore(client: FirestoreClient): Promise<LocalStore> {\n  return ensureOfflineComponents(client).then(c => c.localStore);\n}\n\nfunction getRemoteStore(client: FirestoreClient): Promise<RemoteStore> {\n  return ensureOnlineComponents(client).then(c => c.remoteStore);\n}\n\nexport function getSyncEngine(client: FirestoreClient): Promise<SyncEngine> {\n  return ensureOnlineComponents(client).then(c => c.syncEngine);\n}\n\nfunction getDatastore(client: FirestoreClient): Promise<Datastore> {\n  return ensureOnlineComponents(client).then(c => c.datastore);\n}\n\nexport async function getEventManager(\n  client: FirestoreClient\n): Promise<EventManager> {\n  const onlineComponentProvider = await ensureOnlineComponents(client);\n  const eventManager = onlineComponentProvider.eventManager;\n  eventManager.onListen = syncEngineListen.bind(\n    null,\n    onlineComponentProvider.syncEngine\n  );\n  eventManager.onUnlisten = syncEngineUnlisten.bind(\n    null,\n    onlineComponentProvider.syncEngine\n  );\n  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<void> {\n  return client.asyncQueue.enqueue(async () => {\n    const persistence = await getPersistence(client);\n    const remoteStore = await getRemoteStore(client);\n    persistence.setNetworkEnabled(true);\n    return remoteStoreEnableNetwork(remoteStore);\n  });\n}\n\n/** Disables the network connection. Pending operations will not complete. */\nexport function firestoreClientDisableNetwork(\n  client: FirestoreClient\n): Promise<void> {\n  return client.asyncQueue.enqueue(async () => {\n    const persistence = await getPersistence(client);\n    const remoteStore = await getRemoteStore(client);\n    persistence.setNetworkEnabled(false);\n    return remoteStoreDisableNetwork(remoteStore);\n  });\n}\n\n/**\n * Returns a Promise that resolves when all writes that were pending at the time\n * this method was called received server acknowledgement. An acknowledgement\n * can be either acceptance or rejection.\n */\nexport function firestoreClientWaitForPendingWrites(\n  client: FirestoreClient\n): Promise<void> {\n  const deferred = new Deferred<void>();\n  client.asyncQueue.enqueueAndForget(async () => {\n    const syncEngine = await getSyncEngine(client);\n    return syncEngineRegisterPendingWritesCallback(syncEngine, deferred);\n  });\n  return deferred.promise;\n}\n\nexport function firestoreClientListen(\n  client: FirestoreClient,\n  query: QueryOrPipeline,\n  options: ListenOptions,\n  observer: Partial<Observer<ViewSnapshot>>\n): () => void {\n  const wrappedObserver = new AsyncObserver(observer);\n  const listener = new QueryListener(query, wrappedObserver, options);\n  client.asyncQueue.enqueueAndForget(async () => {\n    const eventManager = await getEventManager(client);\n    return eventManagerListen(eventManager, listener);\n  });\n  return () => {\n    wrappedObserver.mute();\n    client.asyncQueue.enqueueAndForget(async () => {\n      const eventManager = await getEventManager(client);\n      return eventManagerUnlisten(eventManager, listener);\n    });\n  };\n}\n\nexport function firestoreClientGetDocumentFromLocalCache(\n  client: FirestoreClient,\n  docKey: DocumentKey\n): Promise<Document | null> {\n  const deferred = new Deferred<Document | null>();\n  client.asyncQueue.enqueueAndForget(async () => {\n    const localStore = await getLocalStore(client);\n    return readDocumentFromCache(localStore, docKey, deferred);\n  });\n  return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentViaSnapshotListener(\n  client: FirestoreClient,\n  key: DocumentKey,\n  options: GetOptions = {}\n): Promise<ViewSnapshot> {\n  const deferred = new Deferred<ViewSnapshot>();\n  client.asyncQueue.enqueueAndForget(async () => {\n    const eventManager = await getEventManager(client);\n    return readDocumentViaSnapshotListener(\n      eventManager,\n      client.asyncQueue,\n      key,\n      options,\n      deferred\n    );\n  });\n  return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentsFromLocalCache(\n  client: FirestoreClient,\n  query: Query\n): Promise<ViewSnapshot> {\n  const deferred = new Deferred<ViewSnapshot>();\n  client.asyncQueue.enqueueAndForget(async () => {\n    const localStore = await getLocalStore(client);\n    return executeQueryFromCache(localStore, query, deferred);\n  });\n  return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentsViaSnapshotListener(\n  client: FirestoreClient,\n  query: Query | RealtimePipeline,\n  options: GetOptions = {}\n): Promise<ViewSnapshot> {\n  const deferred = new Deferred<ViewSnapshot>();\n  client.asyncQueue.enqueueAndForget(async () => {\n    const eventManager = await getEventManager(client);\n    return executeQueryViaSnapshotListener(\n      eventManager,\n      client.asyncQueue,\n      query,\n      options,\n      deferred\n    );\n  });\n  return deferred.promise;\n}\n\nexport function firestoreClientRunAggregateQuery(\n  client: FirestoreClient,\n  query: Query,\n  aggregates: Aggregate[]\n): Promise<ApiClientObjectMap<Value>> {\n  const deferred = new Deferred<ApiClientObjectMap<Value>>();\n\n  client.asyncQueue.enqueueAndForget(async () => {\n    // Implement and call executeAggregateQueryViaSnapshotListener, similar\n    // to the implementation in firestoreClientGetDocumentsViaSnapshotListener\n    // above\n    try {\n      // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab.\n      const datastore = await getDatastore(client);\n      deferred.resolve(\n        invokeRunAggregationQueryRpc(datastore, query, aggregates)\n      );\n    } catch (e) {\n      deferred.reject(e as Error);\n    }\n  });\n  return deferred.promise;\n}\n\nexport function firestoreClientExecutePipeline(\n  client: FirestoreClient,\n  pipeline: StructuredPipeline\n): Promise<PipelineStreamElement[]> {\n  const deferred = new Deferred<PipelineStreamElement[]>();\n\n  client.asyncQueue.enqueueAndForget(async () => {\n    try {\n      const datastore = await getDatastore(client);\n      deferred.resolve(invokeExecutePipeline(datastore, pipeline));\n    } catch (e) {\n      deferred.reject(e as Error);\n    }\n  });\n  return deferred.promise;\n}\n\nexport function firestoreClientWrite(\n  client: FirestoreClient,\n  mutations: Mutation[]\n): Promise<void> {\n  const deferred = new Deferred<void>();\n  client.asyncQueue.enqueueAndForget(async () => {\n    const syncEngine = await getSyncEngine(client);\n    return syncEngineWrite(syncEngine, mutations, deferred);\n  });\n  return deferred.promise;\n}\n\nexport function firestoreClientAddSnapshotsInSyncListener(\n  client: FirestoreClient,\n  observer: Partial<Observer<void>>\n): () => void {\n  const wrappedObserver = new AsyncObserver(observer);\n  client.asyncQueue.enqueueAndForget(async () => {\n    const eventManager = await getEventManager(client);\n    return addSnapshotsInSyncListener(eventManager, wrappedObserver);\n  });\n  return () => {\n    wrappedObserver.mute();\n    client.asyncQueue.enqueueAndForget(async () => {\n      const eventManager = await getEventManager(client);\n      return removeSnapshotsInSyncListener(eventManager, wrappedObserver);\n    });\n  };\n}\n\n/**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If a retryable error occurs (ex: some other\n * client has changed any of the data referenced), then the updateFunction\n * will be called again after a backoff. If the updateFunction still fails\n * after all retries, then the transaction will be rejected.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n */\nexport function firestoreClientTransaction<T>(\n  client: FirestoreClient,\n  updateFunction: (transaction: Transaction) => Promise<T>,\n  options: TransactionOptions\n): Promise<T> {\n  const deferred = new Deferred<T>();\n  client.asyncQueue.enqueueAndForget(async () => {\n    const datastore = await getDatastore(client);\n    new TransactionRunner<T>(\n      client.asyncQueue,\n      datastore,\n      options,\n      updateFunction,\n      deferred\n    ).run();\n  });\n  return deferred.promise;\n}\n\nasync function readDocumentFromCache(\n  localStore: LocalStore,\n  docKey: DocumentKey,\n  result: Deferred<Document | null>\n): Promise<void> {\n  try {\n    const document = await localStoreReadDocument(localStore, docKey);\n    if (document.isFoundDocument()) {\n      result.resolve(document);\n    } else if (document.isNoDocument()) {\n      result.resolve(null);\n    } else {\n      result.reject(\n        new FirestoreError(\n          Code.UNAVAILABLE,\n          'Failed to get document from cache. (However, this document may ' +\n            \"exist on the server. Run again without setting 'source' in \" +\n            'the GetOptions to attempt to retrieve the document from the ' +\n            'server.)'\n        )\n      );\n    }\n  } catch (e) {\n    const firestoreError = wrapInUserErrorIfRecoverable(\n      e as Error,\n      `Failed to get document '${docKey} from cache`\n    );\n    result.reject(firestoreError);\n  }\n}\n\n/**\n * Retrieves a latency-compensated document from the backend via a\n * SnapshotListener.\n */\nfunction readDocumentViaSnapshotListener(\n  eventManager: EventManager,\n  asyncQueue: AsyncQueue,\n  key: DocumentKey,\n  options: GetOptions,\n  result: Deferred<ViewSnapshot>\n): Promise<void> {\n  const wrappedObserver = new AsyncObserver({\n    next: (snap: ViewSnapshot) => {\n      // 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<ViewSnapshot>\n): Promise<void> {\n  try {\n    const queryResult = await localStoreExecuteQuery(\n      localStore,\n      query,\n      /* usePreviousResults= */ true\n    );\n    const view = new View(query, queryResult.remoteKeys);\n    const viewDocChanges = view.computeDocChanges(queryResult.documents);\n    const viewChange = view.applyChanges(\n      viewDocChanges,\n      /* limboResolutionEnabled= */ false\n    );\n    result.resolve(viewChange.snapshot!);\n  } catch (e) {\n    const firestoreError = wrapInUserErrorIfRecoverable(\n      e as Error,\n      `Failed to execute query '${query} against cache`\n    );\n    result.reject(firestoreError);\n  }\n}\n\n/**\n * Retrieves a latency-compensated query snapshot from the backend via a\n * SnapshotListener.\n */\nfunction executeQueryViaSnapshotListener(\n  eventManager: EventManager,\n  asyncQueue: AsyncQueue,\n  query: Query | RealtimePipeline,\n  options: GetOptions,\n  result: Deferred<ViewSnapshot>\n): Promise<void> {\n  const wrappedObserver = new AsyncObserver<ViewSnapshot>({\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 =\n    query instanceof RealtimePipeline\n      ? new QueryListener(toCorePipeline(query), wrappedObserver, {\n          includeMetadataChanges: true,\n          waitForSyncWhenOnline: true\n        })\n      : new QueryListener(query, wrappedObserver, {\n          includeMetadataChanges: true,\n          waitForSyncWhenOnline: true\n        });\n  return eventManagerListen(eventManager, listener);\n}\n\nexport function firestoreClientLoadBundle(\n  client: FirestoreClient,\n  databaseId: DatabaseId,\n  data: ReadableStream<Uint8Array> | ArrayBuffer | string,\n  resultTask: LoadBundleTask\n): void {\n  const reader = createBundleReader(data, newSerializer(databaseId));\n  client.asyncQueue.enqueueAndForget(async () => {\n    syncEngineLoadBundle(await getSyncEngine(client), reader, resultTask);\n  });\n}\n\nexport function firestoreClientGetNamedQuery(\n  client: FirestoreClient,\n  queryName: string\n): Promise<NamedQuery | undefined> {\n  return client.asyncQueue.enqueue(async () =>\n    localStoreGetNamedQuery(await getLocalStore(client), queryName)\n  );\n}\n\nfunction createBundleReader(\n  data: ReadableStream<Uint8Array> | ArrayBuffer | string,\n  serializer: JsonProtoSerializer\n): BundleReader {\n  let content: ReadableStream<Uint8Array> | ArrayBuffer;\n  if (typeof data === 'string') {\n    content = newTextEncoder().encode(data);\n  } else {\n    content = data;\n  }\n  return newBundleReader(toByteStreamReader(content), serializer);\n}\n\nexport function 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<void> {\n  return client.asyncQueue.enqueue(async () => {\n    return localStoreConfigureFieldIndexes(\n      await getLocalStore(client),\n      indexes\n    );\n  });\n}\n\nexport function firestoreClientSetPersistentCacheIndexAutoCreationEnabled(\n  client: FirestoreClient,\n  isEnabled: boolean\n): Promise<void> {\n  return client.asyncQueue.enqueue(async () => {\n    return localStoreSetIndexAutoCreationEnabled(\n      await getLocalStore(client),\n      isEnabled\n    );\n  });\n}\n\nexport function firestoreClientDeleteAllFieldIndexes(\n  client: FirestoreClient\n): Promise<void> {\n  return client.asyncQueue.enqueue(async () => {\n    return localStoreDeleteAllFieldIndexes(await getLocalStore(client));\n  });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { getDocument } from '../platform/dom';\nimport { ExponentialBackoff } from '../remote/backoff';\n\nimport { debugAssert, fail } from './assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from './async_queue';\nimport { FirestoreError } from './error';\nimport { logDebug, logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\nexport class AsyncQueueImpl implements AsyncQueue {\n  // The last promise in the queue.\n  private tail: Promise<unknown>;\n\n  // A list of retryable operations. Retryable operations are run in order and\n  // retried with backoff.\n  private retryableOps: Array<() => Promise<void>> = [];\n\n  // Is this AsyncQueue being shut down? Once it is set to true, it will not\n  // be changed again.\n  private _isShuttingDown: boolean = false;\n\n  // Operations scheduled to be queued in the future. Operations are\n  // automatically removed after they are run or canceled.\n  private delayedOperations: Array<DelayedOperation<unknown>> = [];\n\n  // visible for testing\n  failure: FirestoreError | null = null;\n\n  // Flag set while there's an outstanding AsyncQueue operation, used for\n  // assertion sanity-checks.\n  private operationInProgress = false;\n\n  // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n  private skipNonRestrictedTasks = false;\n\n  // List of TimerIds to fast-forward delays for.\n  private timerIdsToSkip: TimerId[] = [];\n\n  // Backoff timer used to schedule retries for retryable operations\n  private backoff = new ExponentialBackoff(this, TimerId.AsyncQueueRetry);\n\n  // Visibility handler that triggers an immediate retry of all retryable\n  // operations. Meant to speed up recovery when we regain file system access\n  // after page comes into foreground.\n  private visibilityHandler: () => void = () => {\n    const document = getDocument();\n    if (document) {\n      logDebug(\n        LOG_TAG,\n        'Visibility state changed to ' + document.visibilityState\n      );\n    }\n    this.backoff.skipBackoff();\n  };\n\n  constructor(tail: Promise<unknown> = 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<T extends unknown>(op: () => Promise<T>): void {\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.enqueue(op);\n  }\n\n  enqueueAndForgetEvenWhileRestricted<T extends unknown>(\n    op: () => Promise<T>\n  ): void {\n    this.verifyNotFailed();\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.enqueueInternal(op);\n  }\n\n  enterRestrictedMode(purgeExistingTasks?: boolean): void {\n    if (!this._isShuttingDown) {\n      this._isShuttingDown = true;\n      this.skipNonRestrictedTasks = purgeExistingTasks || false;\n      const document = getDocument();\n      if (document && typeof document.removeEventListener === 'function') {\n        document.removeEventListener(\n          'visibilitychange',\n          this.visibilityHandler\n        );\n      }\n    }\n  }\n\n  enqueue<T extends unknown>(op: () => Promise<T>): Promise<T> {\n    this.verifyNotFailed();\n    if (this._isShuttingDown) {\n      // Return a Promise which never resolves.\n      return new Promise<T>(() => {});\n    }\n\n    // Create a deferred Promise that we can return to the callee. This\n    // allows us to return a \"hanging Promise\" only to the callee and still\n    // advance the queue even when the operation is not run.\n    const task = new Deferred<T>();\n    return this.enqueueInternal<unknown>(() => {\n      if (this._isShuttingDown && this.skipNonRestrictedTasks) {\n        // We do not resolve 'task'\n        return Promise.resolve();\n      }\n\n      op().then(task.resolve, task.reject);\n      return task.promise;\n    }).then(() => task.promise);\n  }\n\n  enqueueRetryable(op: () => Promise<void>): void {\n    this.enqueueAndForget(() => {\n      this.retryableOps.push(op);\n      return this.retryNextOp();\n    });\n  }\n\n  /**\n   * Runs the next operation from the retryable queue. If the operation fails,\n   * reschedules with backoff.\n   */\n  private async retryNextOp(): Promise<void> {\n    if (this.retryableOps.length === 0) {\n      return;\n    }\n\n    try {\n      await this.retryableOps[0]();\n      this.retryableOps.shift();\n      this.backoff.reset();\n    } catch (e) {\n      if (isIndexedDbTransactionError(e as Error)) {\n        logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);\n      } else {\n        throw e; // Failure will be handled by AsyncQueue\n      }\n    }\n\n    if (this.retryableOps.length > 0) {\n      // If there are additional operations, we re-schedule `retryNextOp()`.\n      // This is necessary to run retryable operations that failed during\n      // their initial attempt since we don't know whether they are already\n      // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n      // needs to  be re-run, we will run `op1`, `op1`, `op2` using the\n      // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n      // call scheduled here.\n      // Since `backoffAndRun()` cancels an existing backoff and schedules a\n      // new backoff on every call, there is only ever a single additional\n      // operation in the queue.\n      this.backoff.backoffAndRun(() => this.retryNextOp());\n    }\n  }\n\n  private enqueueInternal<T extends unknown>(op: () => Promise<T>): Promise<T> {\n    const newTail = this.tail.then(() => {\n      this.operationInProgress = true;\n      return op()\n        .catch((error: FirestoreError) => {\n          this.failure = error;\n          this.operationInProgress = false;\n          const message = getMessageOrStack(error);\n          logError('INTERNAL UNHANDLED ERROR: ', message);\n\n          // Re-throw the error so that this.tail becomes a rejected Promise and\n          // all further attempts to chain (via .then) will just short-circuit\n          // and return the rejected Promise.\n          throw error;\n        })\n        .then(result => {\n          this.operationInProgress = false;\n          return result;\n        });\n    });\n    this.tail = newTail;\n    return newTail;\n  }\n\n  enqueueAfterDelay<T extends unknown>(\n    timerId: TimerId,\n    delayMs: number,\n    op: () => Promise<T>\n  ): DelayedOperation<T> {\n    this.verifyNotFailed();\n\n    debugAssert(\n      delayMs >= 0,\n      `Attempted to schedule an operation with a negative delay of ${delayMs}`\n    );\n\n    // Fast-forward delays for timerIds that have been overridden.\n    if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n      delayMs = 0;\n    }\n\n    const delayedOp = DelayedOperation.createAndSchedule<T>(\n      this,\n      timerId,\n      delayMs,\n      op,\n      removedOp =>\n        this.removeDelayedOperation(removedOp as DelayedOperation<unknown>)\n    );\n    this.delayedOperations.push(delayedOp as DelayedOperation<unknown>);\n    return delayedOp;\n  }\n\n  private verifyNotFailed(): void {\n    if (this.failure) {\n      fail(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<void> {\n    // Operations in the queue prior to draining may have enqueued additional\n    // operations. Keep draining the queue until the tail is no longer advanced,\n    // which indicates that no more new operations were enqueued and that all\n    // operations were executed.\n    let currentTail: Promise<unknown>;\n    do {\n      currentTail = this.tail;\n      await currentTail;\n    } while (currentTail !== this.tail);\n  }\n\n  /**\n   * For Tests: Determine if a delayed operation with a particular TimerId\n   * exists.\n   */\n  containsDelayedOperation(timerId: TimerId): boolean {\n    for (const op of this.delayedOperations) {\n      if (op.timerId === timerId) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /**\n   * For Tests: Runs some or all delayed operations early.\n   *\n   * @param lastTimerId - Delayed operations up to and including this TimerId\n   * will be drained. Pass TimerId.All to run all delayed operations.\n   * @returns a Promise that resolves once all operations have been run.\n   */\n  runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise<void> {\n    // Note that draining may generate more delayed ops, so we do that first.\n    return this.drain().then(() => {\n      // Run ops in the same order they'd run if they ran naturally.\n      /* 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<unknown>): void {\n    // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n    const index = this.delayedOperations.indexOf(op);\n    debugAssert(index >= 0, 'Delayed operation not found.');\n    /* 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<LoadBundleTaskProgress>`.\n */\nexport class LoadBundleTask implements PromiseLike<LoadBundleTaskProgress> {\n  private _progressObserver: PartialObserver<LoadBundleTaskProgress> = {};\n  private _taskCompletionResolver = new Deferred<LoadBundleTaskProgress>();\n\n  private _lastProgress: LoadBundleTaskProgress = {\n    taskState: 'Running',\n    totalBytes: 0,\n    totalDocuments: 0,\n    bytesLoaded: 0,\n    documentsLoaded: 0\n  };\n\n  /**\n   * Registers functions to listen to bundle loading progress events.\n   * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n   *   each time a Firestore document is loaded from the bundle.\n   * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n   *   error, and there should be no more updates after this.\n   * @param complete - Called when the loading task is complete.\n   */\n  onProgress(\n    next?: (progress: LoadBundleTaskProgress) => unknown,\n    error?: (err: Error) => unknown,\n    complete?: () => void\n  ): void {\n    this._progressObserver = {\n      next,\n      error,\n      complete\n    };\n  }\n\n  /**\n   * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.\n   *\n   * @param onRejected - Called when an error occurs during bundle loading.\n   */\n  catch<R>(\n    onRejected: (a: Error) => R | PromiseLike<R>\n  ): Promise<R | LoadBundleTaskProgress> {\n    return this._taskCompletionResolver.promise.catch(onRejected);\n  }\n\n  /**\n   * Implements the `Promise<LoadBundleTaskProgress>.then` interface.\n   *\n   * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n   *   The update will always have its `taskState` set to `\"Success\"`.\n   * @param onRejected - Called when an error occurs during bundle loading.\n   */\n  then<T, R>(\n    onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike<T>,\n    onRejected?: (a: Error) => R | PromiseLike<R>\n  ): Promise<T | R> {\n    return this._taskCompletionResolver.promise.then(onFulfilled, onRejected);\n  }\n\n  /**\n   * Notifies all observers that bundle loading has completed, with a provided\n   * `LoadBundleTaskProgress` object.\n   *\n   * @private\n   */\n  _completeWith(progress: LoadBundleTaskProgress): void {\n    debugAssert(\n      progress.taskState === 'Success',\n      'Task is not completed with Success.'\n    );\n    this._updateProgress(progress);\n    if (this._progressObserver.complete) {\n      this._progressObserver.complete();\n    }\n\n    this._taskCompletionResolver.resolve(progress);\n  }\n\n  /**\n   * Notifies all observers that bundle loading has failed, with a provided\n   * `Error` as the reason.\n   *\n   * @private\n   */\n  _failWith(error: FirestoreError): void {\n    this._lastProgress.taskState = 'Error';\n\n    if (this._progressObserver.next) {\n      this._progressObserver.next(this._lastProgress);\n    }\n\n    if (this._progressObserver.error) {\n      this._progressObserver.error(error);\n    }\n\n    this._taskCompletionResolver.reject(error);\n  }\n\n  /**\n   * Notifies a progress update of loading a bundle.\n   * @param progress - The new progress.\n   *\n   * @private\n   */\n  _updateProgress(progress: LoadBundleTaskProgress): void {\n    debugAssert(\n      this._lastProgress.taskState === 'Running',\n      'Cannot update progress on a completed or failed task'\n    );\n\n    this._lastProgress = progress;\n    if (this._progressObserver.next) {\n      this._progressObserver.next(progress);\n    }\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  _getProvider,\n  _removeServiceInstance,\n  FirebaseApp,\n  getApp\n} from '@firebase/app';\nimport {\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<User>,\n    appCheckCredentialsProvider: CredentialsProvider<string>,\n    databaseId: DatabaseId,\n    app?: FirebaseApp\n  ) {\n    super(\n      authCredentialsProvider,\n      appCheckCredentialsProvider,\n      databaseId,\n      app\n    );\n    this._persistenceKey = app?.name || '[DEFAULT]';\n  }\n\n  protected async _terminate(): Promise<void> {\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    firestore._app?.options.apiKey,\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<void> {\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<void> {\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<void> {\n  if (firestore._initialized && !firestore._terminated) {\n    throw new FirestoreError(\n      Code.FAILED_PRECONDITION,\n      'Persistence can only be cleared before a Firestore instance is ' +\n        'initialized or after it is terminated.'\n    );\n  }\n\n  const deferred = new Deferred<void>();\n  firestore._queue.enqueueAndForgetEvenWhileRestricted(async () => {\n    try {\n      await indexedDbClearPersistence(\n        indexedDbStoragePrefix(firestore._databaseId, firestore._persistenceKey)\n      );\n      deferred.resolve();\n    } catch (e) {\n      deferred.reject(e as Error | undefined);\n    }\n  });\n  return deferred.promise;\n}\n\n/**\n * Waits until all currently pending writes for the active user have been\n * acknowledged by the backend.\n *\n * The returned promise resolves immediately if there are no outstanding writes.\n * Otherwise, the promise waits for all previously issued writes (including\n * those written in a previous app session), but it does not wait for writes\n * that were added after the function is called. If you want to wait for\n * additional writes, call `waitForPendingWrites()` again.\n *\n * Any outstanding `waitForPendingWrites()` promises are rejected during user\n * changes.\n *\n * @returns A `Promise` which resolves when all currently pending writes have been\n * acknowledged by the backend.\n */\nexport function waitForPendingWrites(firestore: Firestore): Promise<void> {\n  firestore = cast(firestore, Firestore);\n  const client = ensureFirestoreConfigured(firestore);\n  return firestoreClientWaitForPendingWrites(client);\n}\n\n/**\n * Re-enables use of the network for this {@link Firestore} instance after a prior\n * call to {@link disableNetwork}.\n *\n * @returns A `Promise` that is resolved once the network has been enabled.\n */\nexport function enableNetwork(firestore: Firestore): Promise<void> {\n  firestore = cast(firestore, Firestore);\n  const client = ensureFirestoreConfigured(firestore);\n  return firestoreClientEnableNetwork(client);\n}\n\n/**\n * Disables network usage for this instance. It can be re-enabled via {@link\n * enableNetwork}. While the network is disabled, any snapshot listeners,\n * `getDoc()` or `getDocs()` calls will return results from cache, and any write\n * operations will be queued until the network is restored.\n *\n * @returns A `Promise` that is resolved once the network has been disabled.\n */\nexport function disableNetwork(firestore: Firestore): Promise<void> {\n  firestore = cast(firestore, Firestore);\n  const client = ensureFirestoreConfigured(firestore);\n  return firestoreClientDisableNetwork(client);\n}\n\n/**\n * Terminates the provided {@link Firestore} instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` function\n * may be used. Any other function will throw a `FirestoreError`.\n *\n * To restart after termination, create a new instance of FirebaseFirestore with\n * {@link (getFirestore:1)}.\n *\n * Termination does not cancel any pending writes, and any promises that are\n * awaiting a response from the server will not be resolved. If you have\n * persistence enabled, the next time you start this instance, it will resume\n * sending these writes to the server.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all\n * of its resources or in combination with `clearIndexedDbPersistence()` to\n * ensure that all local state is destroyed between test runs.\n *\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise<void> {\n  _removeServiceInstance(\n    firestore.app,\n    'firestore',\n    firestore._databaseId.database\n  );\n  return firestore._delete();\n}\n\n/**\n * Loads a Firestore bundle into the local cache.\n *\n * @param firestore - The {@link Firestore} instance to load bundles for.\n * @param bundleData - An object representing the bundle to be loaded. Valid\n * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.\n *\n * @returns A `LoadBundleTask` object, which notifies callers with progress\n * updates, and completion or error events. It can be used as a\n * `Promise<LoadBundleTaskProgress>`.\n */\nexport function loadBundle(\n  firestore: Firestore,\n  bundleData: ReadableStream<Uint8Array> | ArrayBuffer | string\n): LoadBundleTask {\n  firestore = cast(firestore, Firestore);\n  const client = ensureFirestoreConfigured(firestore);\n  const resultTask = new LoadBundleTask();\n  firestoreClientLoadBundle(\n    client,\n    firestore._databaseId,\n    bundleData,\n    resultTask\n  );\n  return resultTask;\n}\n\n/**\n * Reads a Firestore {@link Query} from local cache, identified by the given\n * name.\n *\n * The named queries are packaged  into bundles on the server side (along\n * with resulting documents), and loaded to local cache using `loadBundle`. Once\n * in local cache, use this method to extract a {@link Query} by name.\n *\n * @param firestore - The {@link Firestore} instance to read the query from.\n * @param name - The name of the query.\n * @returns A `Promise` that is resolved with the Query or `null`.\n */\nexport function namedQuery(\n  firestore: Firestore,\n  name: string\n): Promise<Query | null> {\n  firestore = cast(firestore, Firestore);\n  const client = ensureFirestoreConfigured(firestore);\n  return firestoreClientGetNamedQuery(client, name).then(namedQuery => {\n    if (!namedQuery) {\n      return null;\n    }\n\n    return new Query(firestore, null, namedQuery.query);\n  });\n}\n","/**\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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<Value> | undefined,\n    serverTimestampBehavior: ServerTimestampBehavior = 'none'\n  ): DocumentData {\n    const result: DocumentData = {};\n    forEach(fields, (key, value) => {\n      result[key] = this.convertValue(value, serverTimestampBehavior);\n    });\n    return result;\n  }\n\n  /**\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 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 { Bytes } from '../lite-api/bytes';\nimport { DocumentReference } from '../lite-api/reference';\nimport { AbstractUserDataWriter } from '../lite-api/user_data_writer';\nimport { ByteString } from '../util/byte_string';\n\nimport { Firestore } from './database';\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 * @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 { ParseContext } from '../api/parse_context';\nimport { UserData } from '../lite-api/user_data_reader';\nimport {\n  ApiClientObjectMap,\n  firestoreV1ApiClientInterfaces,\n  Pipeline as PipelineProto,\n  StructuredPipeline as StructuredPipelineProto\n} from '../protos/firestore_proto_api';\nimport { JsonProtoSerializer, ProtoSerializable } from '../remote/serializer';\n\nimport { OptionsUtil } from './options_util';\n\nexport class StructuredPipelineOptions implements UserData {\n  proto: ApiClientObjectMap<firestoreV1ApiClientInterfaces.Value> | undefined;\n\n  readonly optionsUtil = new OptionsUtil({\n    indexMode: {\n      serverName: 'index_mode'\n    }\n  });\n\n  constructor(\n    private _userOptions: Record<string, unknown> = {},\n    private _optionsOverride: Record<string, unknown> = {}\n  ) {}\n\n  _readUserData(context: ParseContext): void {\n    this.proto = this.optionsUtil.getOptionsProto(\n      context,\n      this._userOptions,\n      this._optionsOverride\n    );\n  }\n}\n\nexport class StructuredPipeline\n  implements ProtoSerializable<StructuredPipelineProto>\n{\n  constructor(\n    private pipeline: ProtoSerializable<PipelineProto>,\n    private options: StructuredPipelineOptions\n  ) {}\n\n  _toProto(serializer: JsonProtoSerializer): StructuredPipelineProto {\n    return {\n      pipeline: this.pipeline._toProto(serializer),\n      options: this.options.proto\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 { ensureFirestoreConfigured, Firestore } from '../api/database';\nimport { AggregateImpl } from '../core/aggregate';\nimport { queryToAggregateTarget, queryToTarget } from '../core/query';\nimport {\n  StructuredPipeline,\n  StructuredPipelineOptions\n} from '../core/structured_pipeline';\nimport { AggregateSpec } from '../lite-api/aggregate_types';\nimport { getDatastore } from '../lite-api/components';\nimport { Pipeline } from '../lite-api/pipeline';\nimport { Query } from '../lite-api/reference';\nimport {\n  newUserDataReader,\n  UserDataSource\n} from '../lite-api/user_data_reader';\nimport { ExecutePipelineRequest as ProtoExecutePipelineRequest } from '../protos/firestore_proto_api';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n  getEncodedDatabaseId,\n  toQueryTarget,\n  toRunAggregationQueryRequest\n} 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/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns the `ExecutePipelineRequest` representation of the given query.\n * Returns `null` if the Firestore client associated with the given query has\n * not been initialized or has been terminated.\n *\n * @param pipeline - The Pipeline to convert to proto representation.\n */\nexport function _internalPipelineToExecutePipelineRequestProto(\n  pipeline: Pipeline\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n  if (!pipeline._db) {\n    throw new FirestoreError(\n      Code.FAILED_PRECONDITION,\n      'This pipeline was created without a database and cannot be serialized for execution.'\n    );\n  }\n\n  const firestore = cast(pipeline._db, Firestore);\n\n  const userDataReader = newUserDataReader(firestore);\n  const context = userDataReader.createContext(\n    UserDataSource.Argument,\n    '_internalPipelineToExecutePipelineRequestProto'\n  );\n\n  pipeline._readUserData(context);\n\n  const datastore = getDatastore(firestore);\n  const serializer = datastore.serializer;\n  if (serializer === undefined) {\n    return null;\n  }\n\n  const structuredPipeline = new StructuredPipeline(\n    pipeline,\n    new StructuredPipelineOptions()\n  );\n  const executePipelineRequest: ProtoExecutePipelineRequest = {\n    database: getEncodedDatabaseId(serializer),\n    structuredPipeline: structuredPipeline._toProto(serializer)\n  };\n\n  return executePipelineRequest;\n}\n"],"names":["generateRandomBytes","MIN_SURROGATE","MAX_SURROGATE","FieldPath","LOG_TAG","DbRemoteDocumentStore","DbRemoteDocumentStoreLegacy","TYPE_KEY","serverTimestamp","isNumber","isString","valueEquals","isDocumentQuery","InternalFieldPath","documentId","protos","getDatastore","Firestore","minimum","maximum","documentIdFieldPath","valueEqualsWithOptions","FieldFilterInternal","CompositeFilterInternal","sentinelKey","LiteFirestore"],"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,I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