{"version":3,"file":"index.node.mjs","sources":["../src/register.ts","../src/lite-api/aggregate_types.ts","../src/lite-api/snapshot.ts","../src/lite-api/query.ts","../src/lite-api/reference_impl.ts","../src/lite-api/aggregate.ts","../src/api/aggregate.ts","../src/api/cache_config.ts","../test/unit/util/bundle_data.ts","../src/util/bundle_builder_impl.ts","../src/platform/node/snapshot_to_json.ts","../src/api/snapshot.ts","../src/core/transaction_options.ts","../src/lite-api/write_batch.ts","../src/lite-api/transaction.ts","../src/api/transaction.ts","../src/api/observer.ts","../src/api/reference_impl.ts","../src/api/write_batch.ts","../src/api/index_configuration.ts","../src/api/persistent_cache_index_manager.ts","../src/util/testing_hooks.ts","../src/index.node.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  _registerComponent,\n  registerVersion,\n  SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { name, version } from '../package.json';\nimport {\n  FirebaseAppCheckTokenProvider,\n  FirebaseAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { setSDKVersion } from '../src/core/version';\n\nimport { Firestore } from './api/database';\nimport { databaseIdFromApp } from './core/database_info';\n\nexport function registerFirestore(\n  variant?: string,\n  useFetchStreams = true\n): void {\n  setSDKVersion(SDK_VERSION);\n  _registerComponent(\n    new Component(\n      'firestore',\n      (container, { instanceIdentifier: databaseId, options: settings }) => {\n        const app = container.getProvider('app').getImmediate()!;\n        const firestoreInstance = new Firestore(\n          new FirebaseAuthCredentialsProvider(\n            container.getProvider('auth-internal')\n          ),\n          new FirebaseAppCheckTokenProvider(\n            app,\n            container.getProvider('app-check-internal')\n          ),\n          databaseIdFromApp(app, databaseId),\n          app\n        );\n        settings = { useFetchStreams, ...settings };\n        firestoreInstance._setSettings(settings);\n        return firestoreInstance;\n      },\n      'PUBLIC' as ComponentType.PUBLIC\n    ).setMultipleInstances(true)\n  );\n  registerVersion(name, version, variant);\n  // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\n  registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AggregateType } from '../core/aggregate';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n  ApiClientObjectMap,\n  firestoreV1ApiClientInterfaces,\n  Value\n} from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField<T> {\n  /** A type string to uniquely identify instances of this class. */\n  readonly type = 'AggregateField';\n\n  /** Indicates the aggregation operation of this AggregateField. */\n  readonly aggregateType: AggregateType;\n\n  /**\n   * Create a new AggregateField<T>\n   * @param aggregateType - Specifies the type of aggregation operation to perform.\n   * @param _internalFieldPath - Optionally specifies the field that is aggregated.\n   * @internal\n   */\n  constructor(\n    aggregateType: AggregateType = 'count',\n    readonly _internalFieldPath?: InternalFieldPath\n  ) {\n    this.aggregateType = aggregateType;\n  }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n  | ReturnType<typeof sum>\n  | ReturnType<typeof average>\n  | ReturnType<typeof count>;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n  [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData<T extends AggregateSpec> = {\n  [P in keyof T]: T[P] extends AggregateField<infer U> ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n  AggregateSpecType extends AggregateSpec,\n  AppModelType = DocumentData,\n  DbModelType extends DocumentData = DocumentData\n> {\n  /** A type string to uniquely identify instances of this class. */\n  readonly type = 'AggregateQuerySnapshot';\n\n  /**\n   * The underlying query over which the aggregations recorded in this\n   * `AggregateQuerySnapshot` were performed.\n   */\n  readonly query: Query<AppModelType, DbModelType>;\n\n  /** @hideconstructor */\n  constructor(\n    query: Query<AppModelType, DbModelType>,\n    private readonly _userDataWriter: AbstractUserDataWriter,\n    private readonly _data: ApiClientObjectMap<Value>\n  ) {\n    this.query = query;\n  }\n\n  /**\n   * Returns the results of the aggregations performed over the underlying\n   * query.\n   *\n   * The keys of the returned object will be the same as those of the\n   * `AggregateSpec` object specified to the aggregation method, and the values\n   * will be the corresponding aggregation result.\n   *\n   * @returns The results of the aggregations performed over the underlying\n   * query.\n   */\n  data(): AggregateSpecData<AggregateSpecType> {\n    return this._userDataWriter.convertObjectMap(\n      this._data\n    ) as AggregateSpecData<AggregateSpecType>;\n  }\n\n  /**\n   * @internal\n   * @private\n   *\n   * Retrieves all fields in the snapshot as a proto value.\n   *\n   * @returns An `Object` containing all fields in the snapshot.\n   */\n  _fieldsProto(): { [key: string]: firestoreV1ApiClientInterfaces.Value } {\n    // Wrap data in an ObjectValue to clone it.\n    const dataClone = new ObjectValue({\n      mapValue: { fields: this._data }\n    }).clone();\n\n    // Return the cloned value to prevent manipulation of the Snapshot's data\n    return dataClone.value.mapValue.fields!;\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { firestoreV1ApiClientInterfaces } from '../protos/firestore_proto_api';\nimport { arrayEquals } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n  DocumentData,\n  DocumentReference,\n  PartialWithFieldValue,\n  Query,\n  queryEqual,\n  SetOptions,\n  WithFieldValue\n} from './reference';\nimport {\n  fieldPathFromArgument,\n  UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n *     toFirestore(value: WithFieldValue<number>) {\n *         return { value };\n *     },\n *     fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n *         return snapshot.data(options).value as number;\n *     }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise<void> {\n *     const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n *     // converters are used with `setDoc`, `addDoc`, and `getDoc`\n *     await setDoc(documentRef, 42);\n *     const snapshot1 = await getDoc(documentRef);\n *     assertEqual(snapshot1.data(), 42);\n *\n *     // converters are not used when writing data with `updateDoc`\n *     await updateDoc(documentRef, { value: 999 });\n *     const snapshot2 = await getDoc(documentRef);\n *     assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n *     constructor(\n *         readonly title: string,\n *         readonly author: string,\n *         readonly lastUpdatedMillis: number\n *     ) {}\n *     toString(): string {\n *         return `${this.title} by ${this.author}`;\n *     }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n *     ttl: string;\n *     aut: { firstName: string; lastName: string };\n *     lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter<Post, PostDbModel> {\n *     toFirestore(post: WithFieldValue<Post>): WithFieldValue<PostDbModel> {\n *         return {\n *             ttl: post.title,\n *             aut: this._autFromAuthor(post.author),\n *             lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n *         };\n *     }\n *\n *     fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n *         const data = snapshot.data(options) as PostDbModel;\n *         const author = `${data.aut.firstName} ${data.aut.lastName}`;\n *         return new Post(data.ttl, author, data.lut.toMillis());\n *     }\n *\n *     _autFromAuthor(\n *         author: string | FieldValue\n *     ): { firstName: string; lastName: string } | FieldValue {\n *         if (typeof author !== 'string') {\n *             // `author` is a FieldValue, so just return it.\n *             return author;\n *         }\n *         const [firstName, lastName] = author.split(' ');\n *         return {firstName, lastName};\n *     }\n *\n *     _lutFromLastUpdatedMillis(\n *         lastUpdatedMillis: number | FieldValue\n *     ): Timestamp | FieldValue {\n *         if (typeof lastUpdatedMillis !== 'number') {\n *             // `lastUpdatedMillis` must be a FieldValue, so just return it.\n *             return lastUpdatedMillis;\n *         }\n *         return Timestamp.fromMillis(lastUpdatedMillis);\n *     }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise<void> {\n *     // Create a `DocumentReference` with a `FirestoreDataConverter`.\n *     const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n *     // The `data` argument specified to `setDoc()` is type checked by the\n *     // TypeScript compiler to be compatible with `Post`. Since the `data`\n *     // argument is typed as `WithFieldValue<Post>` rather than just `Post`,\n *     // this allows properties of the `data` argument to also be special\n *     // Firestore values that perform server-side mutations, such as\n *     // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n *     await setDoc(documentRef, {\n *         title: 'My Life',\n *         author: 'Foo Bar',\n *         lastUpdatedMillis: serverTimestamp()\n *     });\n *\n *     // The TypeScript compiler will fail to compile if the `data` argument to\n *     // `setDoc()` is _not_ compatible with `WithFieldValue<Post>`. This\n *     // type checking prevents the caller from specifying objects with incorrect\n *     // properties or property values.\n *     // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n *     // to parameter of type WithFieldValue<Post>\"\n *     await setDoc(documentRef, { ttl: 'The Title' });\n *\n *     // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n *     // object's `data()` method returns a `Post`, rather than a generic object,\n *     // which would have been returned if the `DocumentReference` did _not_ have a\n *     // `FirestoreDataConverter` attached to it.\n *     const snapshot1: DocumentSnapshot<Post> = await getDoc(documentRef);\n *     const post1: Post = snapshot1.data()!;\n *     if (post1) {\n *         assertEqual(post1.title, 'My Life');\n *         assertEqual(post1.author, 'Foo Bar');\n *     }\n *\n *     // The `data` argument specified to `updateDoc()` is type checked by the\n *     // TypeScript compiler to be compatible with `PostDbModel`. Note that\n *     // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n *     // the `data` argument to `updateDoc()` must be compatible with\n *     // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n *     // as `WithFieldValue<PostDbModel>` rather than just `PostDbModel`, this\n *     // allows properties of the `data` argument to also be those special\n *     // Firestore values, like `arrayRemove()`, `deleteField()`, and\n *     // `serverTimestamp()`.\n *     await updateDoc(documentRef, {\n *         'aut.firstName': 'NewFirstName',\n *         lut: serverTimestamp()\n *     });\n *\n *     // The TypeScript compiler will fail to compile if the `data` argument to\n *     // `updateDoc()` is _not_ compatible with `WithFieldValue<PostDbModel>`.\n *     // This type checking prevents the caller from specifying objects with\n *     // incorrect properties or property values.\n *     // @ts-expect-error \"Argument of type { title: string; } is not assignable\n *     // to parameter of type WithFieldValue<PostDbModel>\"\n *     await updateDoc(documentRef, { title: 'New Title' });\n *     const snapshot2: DocumentSnapshot<Post> = await getDoc(documentRef);\n *     const post2: Post = snapshot2.data()!;\n *     if (post2) {\n *         assertEqual(post2.title, 'My Life');\n *         assertEqual(post2.author, 'NewFirstName Bar');\n *     }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n  AppModelType,\n  DbModelType extends DocumentData = DocumentData\n> {\n  /**\n   * Called by the Firestore SDK to convert a custom model object of type\n   * `AppModelType` into a plain JavaScript object (suitable for writing\n   * directly to the Firestore database) of type `DbModelType`. Used with\n   * {@link @firebase/firestore/lite#(setDoc:1)},\n   * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n   * {@link @firebase/firestore/lite#(Transaction.set:1)}.\n   *\n   * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as\n   * {@link (deleteField:1)} to be used as property values.\n   */\n  toFirestore(\n    modelObject: WithFieldValue<AppModelType>\n  ): WithFieldValue<DbModelType>;\n\n  /**\n   * Called by the Firestore SDK to convert a custom model object of type\n   * `AppModelType` into a plain JavaScript object (suitable for writing\n   * directly to the Firestore database) of type `DbModelType`. Used with\n   * {@link @firebase/firestore/lite#(setDoc:1)},\n   * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n   * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true`\n   * or `mergeFields`.\n   *\n   * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow\n   * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n   * It also supports nested `Partial` by allowing nested fields to be\n   * omitted.\n   */\n  toFirestore(\n    modelObject: PartialWithFieldValue<AppModelType>,\n    options: SetOptions\n  ): PartialWithFieldValue<DbModelType>;\n\n  /**\n   * Called by the Firestore SDK to convert Firestore data into an object of\n   * type `AppModelType`. You can access your data by calling:\n   * `snapshot.data()`.\n   *\n   *\n   * Generally, the data returned from `snapshot.data()` can be cast to\n   * `DbModelType`; however, this is not guaranteed because Firestore does not\n   * enforce a schema on the database. For example, writes from a previous\n   * version of the application or writes from another client that did not use a\n   * type converter could have written data with different properties and/or\n   * property types. The implementation will need to choose whether to\n   * gracefully recover from non-conforming data or throw an error.\n   *\n   * @param snapshot - A `QueryDocumentSnapshot` containing your data and\n   * metadata.\n   */\n  fromFirestore(\n    snapshot: QueryDocumentSnapshot<DocumentData, DocumentData>\n  ): AppModelType;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get(<field>)` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n  AppModelType = DocumentData,\n  DbModelType extends DocumentData = DocumentData\n> {\n  // Note: This class is stripped down version of the DocumentSnapshot in\n  // the legacy SDK. The changes are:\n  // - No support for SnapshotMetadata.\n  // - No support for SnapshotOptions.\n\n  /** @hideconstructor protected */\n  constructor(\n    public _firestore: Firestore,\n    public _userDataWriter: AbstractUserDataWriter,\n    public _key: DocumentKey,\n    public _document: Document | null,\n    public _converter: UntypedFirestoreDataConverter<\n      AppModelType,\n      DbModelType\n    > | null\n  ) {}\n\n  /** Property of the `DocumentSnapshot` that provides the document's ID. */\n  get id(): string {\n    return this._key.path.lastSegment();\n  }\n\n  /**\n   * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n   */\n  get ref(): DocumentReference<AppModelType, DbModelType> {\n    return new DocumentReference<AppModelType, DbModelType>(\n      this._firestore,\n      this._converter,\n      this._key\n    );\n  }\n\n  /**\n   * Signals whether or not the document at the snapshot's location exists.\n   *\n   * @returns true if the document exists.\n   */\n  exists(): this is QueryDocumentSnapshot<AppModelType, DbModelType> {\n    return this._document !== null;\n  }\n\n  /**\n   * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n   * the document doesn't exist.\n   *\n   * @returns An `Object` containing all fields in the document or `undefined`\n   * if the document doesn't exist.\n   */\n  data(): AppModelType | undefined {\n    if (!this._document) {\n      return undefined;\n    } else if (this._converter) {\n      // We only want to use the converter and create a new DocumentSnapshot\n      // if a converter has been provided.\n      const snapshot = new QueryDocumentSnapshot(\n        this._firestore,\n        this._userDataWriter,\n        this._key,\n        this._document,\n        /* converter= */ null\n      );\n      return this._converter.fromFirestore(snapshot);\n    } else {\n      return this._userDataWriter.convertValue(\n        this._document.data.value\n      ) as AppModelType;\n    }\n  }\n\n  /**\n   * @internal\n   * @private\n   *\n   * Retrieves all fields in the document as a proto Value. Returns `undefined` if\n   * the document doesn't exist.\n   *\n   * @returns An `Object` containing all fields in the document or `undefined`\n   * if the document doesn't exist.\n   */\n  _fieldsProto():\n    | { [key: string]: firestoreV1ApiClientInterfaces.Value }\n    | undefined {\n    // Return a cloned value to prevent manipulation of the Snapshot's data\n    return this._document?.data.clone().value.mapValue.fields ?? undefined;\n  }\n\n  /**\n   * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n   * document or field doesn't exist.\n   *\n   * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n   * field.\n   * @returns The data at the specified field location or undefined if no such\n   * field exists in the document.\n   */\n  // We are using `any` here to avoid an explicit cast by our users.\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  get(fieldPath: string | FieldPath): any {\n    if (this._document) {\n      const value = this._document.data.field(\n        fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n      );\n      if (value !== null) {\n        return this._userDataWriter.convertValue(value);\n      }\n    }\n    return undefined;\n  }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get(<field>)` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n  AppModelType = DocumentData,\n  DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot<AppModelType, DbModelType> {\n  /**\n   * Retrieves all fields in the document as an `Object`.\n   *\n   * @override\n   * @returns An `Object` containing all fields in the document.\n   */\n  data(): AppModelType {\n    return super.data() as AppModelType;\n  }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n  AppModelType = DocumentData,\n  DbModelType extends DocumentData = DocumentData\n> {\n  /**\n   * The query on which you called {@link getDocs} in order to get this\n   * `QuerySnapshot`.\n   */\n  readonly query: Query<AppModelType, DbModelType>;\n\n  /** @hideconstructor */\n  constructor(\n    _query: Query<AppModelType, DbModelType>,\n    readonly _docs: Array<QueryDocumentSnapshot<AppModelType, DbModelType>>\n  ) {\n    this.query = _query;\n  }\n\n  /** An array of all the documents in the `QuerySnapshot`. */\n  get docs(): Array<QueryDocumentSnapshot<AppModelType, DbModelType>> {\n    return [...this._docs];\n  }\n\n  /** The number of documents in the `QuerySnapshot`. */\n  get size(): number {\n    return this.docs.length;\n  }\n\n  /** True if there are no documents in the `QuerySnapshot`. */\n  get empty(): boolean {\n    return this.docs.length === 0;\n  }\n\n  /**\n   * Enumerates all of the documents in the `QuerySnapshot`.\n   *\n   * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n   * each document in the snapshot.\n   * @param thisArg - The `this` binding for the callback.\n   */\n  forEach(\n    callback: (\n      result: QueryDocumentSnapshot<AppModelType, DbModelType>\n    ) => void,\n    thisArg?: unknown\n  ): void {\n    this._docs.forEach(callback, thisArg);\n  }\n}\n\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual<AppModelType, DbModelType extends DocumentData>(\n  left:\n    | DocumentSnapshot<AppModelType, DbModelType>\n    | QuerySnapshot<AppModelType, DbModelType>,\n  right:\n    | DocumentSnapshot<AppModelType, DbModelType>\n    | QuerySnapshot<AppModelType, DbModelType>\n): boolean {\n  left = getModularInstance(left);\n  right = getModularInstance(right);\n\n  if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n    return (\n      left._firestore === right._firestore &&\n      left._key.isEqual(right._key) &&\n      (left._document === null\n        ? right._document === null\n        : left._document.isEqual(right._document)) &&\n      left._converter === right._converter\n    );\n  } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n    return (\n      queryEqual(left.query, right.query) &&\n      arrayEquals(left.docs, right.docs, snapshotEqual)\n    );\n  }\n\n  return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n  CompositeFilter,\n  CompositeOperator,\n  FieldFilter,\n  Filter,\n  Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n  isCollectionGroupQuery,\n  LimitType,\n  Query as InternalQuery,\n  queryNormalizedOrderBy,\n  queryWithAddedFilter,\n  queryWithAddedOrderBy,\n  queryWithEndAt,\n  queryWithLimit,\n  queryWithStartAt\n} from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath, ResourcePath } from '../model/path';\nimport { isServerTimestamp } from '../model/server_timestamps';\nimport { refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n  validatePositiveNumber,\n  valueDescription\n} from '../util/input_validation';\n\nimport { FieldPath } from './field_path';\nimport { DocumentData, DocumentReference, Query } from './reference';\nimport { DocumentSnapshot } from './snapshot';\nimport {\n  fieldPathFromArgument,\n  newUserDataReader,\n  parseQueryValue,\n  UserDataReader\n} from './user_data_reader';\n\nexport function validateHasExplicitOrderByForLimitToLast(\n  query: InternalQuery\n): void {\n  if (\n    query.limitType === LimitType.Last &&\n    query.explicitOrderBy.length === 0\n  ) {\n    throw new FirestoreError(\n      Code.UNIMPLEMENTED,\n      'limitToLast() queries require specifying at least one orderBy() clause'\n    );\n  }\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n  | 'where'\n  | 'orderBy'\n  | 'limit'\n  | 'limitToLast'\n  | 'startAt'\n  | 'startAfter'\n  | 'endAt'\n  | 'endBefore';\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */\nexport abstract class AppliableConstraint {\n  /**\n   * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n   * {@link AppliableConstraint} applied.\n   */\n  abstract _apply<AppModelType, DbModelType extends DocumentData>(\n    query: Query<AppModelType, DbModelType>\n  ): Query<AppModelType, DbModelType>;\n}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint extends AppliableConstraint {\n  /** The type of this query constraint */\n  abstract readonly type: QueryConstraintType;\n\n  /**\n   * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n   * {@link AppliableConstraint} applied.\n   */\n  abstract _apply<AppModelType, DbModelType extends DocumentData>(\n    query: Query<AppModelType, DbModelType>\n  ): Query<AppModelType, DbModelType>;\n}\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to\n * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or\n * {@link or}.\n * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to\n * apply (e.g. {@link orderBy}, {@link limit}).\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query<AppModelType, DbModelType extends DocumentData>(\n  query: Query<AppModelType, DbModelType>,\n  compositeFilter: QueryCompositeFilterConstraint,\n  ...queryConstraints: QueryNonFilterConstraint[]\n): Query<AppModelType, DbModelType>;\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param queryConstraints - The list of {@link QueryConstraint}s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query<AppModelType, DbModelType extends DocumentData>(\n  query: Query<AppModelType, DbModelType>,\n  ...queryConstraints: QueryConstraint[]\n): Query<AppModelType, DbModelType>;\n\nexport function query<AppModelType, DbModelType extends DocumentData>(\n  query: Query<AppModelType, DbModelType>,\n  queryConstraint: QueryCompositeFilterConstraint | QueryConstraint | undefined,\n  ...additionalQueryConstraints: Array<\n    QueryConstraint | QueryNonFilterConstraint\n  >\n): Query<AppModelType, DbModelType> {\n  let queryConstraints: AppliableConstraint[] = [];\n\n  if (queryConstraint instanceof AppliableConstraint) {\n    queryConstraints.push(queryConstraint);\n  }\n\n  queryConstraints = queryConstraints.concat(additionalQueryConstraints);\n\n  validateQueryConstraintArray(queryConstraints);\n\n  for (const constraint of queryConstraints) {\n    query = constraint._apply(query);\n  }\n  return query;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */\nexport class QueryFieldFilterConstraint extends QueryConstraint {\n  /** The type of this query constraint */\n  readonly type = 'where';\n\n  /**\n   * @internal\n   */\n  protected constructor(\n    private readonly _field: InternalFieldPath,\n    private _op: Operator,\n    private _value: unknown\n  ) {\n    super();\n  }\n\n  static _create(\n    _field: InternalFieldPath,\n    _op: Operator,\n    _value: unknown\n  ): QueryFieldFilterConstraint {\n    return new QueryFieldFilterConstraint(_field, _op, _value);\n  }\n\n  _apply<AppModelType, DbModelType extends DocumentData>(\n    query: Query<AppModelType, DbModelType>\n  ): Query<AppModelType, DbModelType> {\n    const filter = this._parse(query);\n    validateNewFieldFilter(query._query, filter);\n    return new Query(\n      query.firestore,\n      query.converter,\n      queryWithAddedFilter(query._query, filter)\n    );\n  }\n\n  _parse<AppModelType, DbModelType extends DocumentData>(\n    query: Query<AppModelType, DbModelType>\n  ): FieldFilter {\n    const reader = newUserDataReader(query.firestore);\n    const filter = newQueryFilter(\n      query._query,\n      'where',\n      reader,\n      query.firestore._databaseId,\n      this._field,\n      this._op,\n      this._value\n    );\n    return filter;\n  }\n}\n\n/**\n * Filter conditions in a {@link where} clause are specified using the\n * strings '&lt;', '&lt;=', '==', '!=', '&gt;=', '&gt;', 'array-contains', 'in',\n * 'array-contains-any', and 'not-in'.\n */\nexport type WhereFilterOp =\n  | '<'\n  | '<='\n  | '=='\n  | '!='\n  | '>='\n  | '>'\n  | 'array-contains'\n  | 'in'\n  | 'array-contains-any'\n  | 'not-in';\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"&lt;\", \"&lt;=\", \"==\", \"&lt;\",\n *   \"&lt;=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */\nexport function where(\n  fieldPath: string | FieldPath,\n  opStr: WhereFilterOp,\n  value: unknown\n): QueryFieldFilterConstraint {\n  const op = opStr as Operator;\n  const field = fieldPathFromArgument('where', fieldPath);\n  return QueryFieldFilterConstraint._create(field, op, value);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */\nexport class QueryCompositeFilterConstraint extends AppliableConstraint {\n  /**\n   * @internal\n   */\n  protected constructor(\n    /** The type of this query constraint */\n    readonly type: 'or' | 'and',\n    private readonly _queryConstraints: QueryFilterConstraint[]\n  ) {\n    super();\n  }\n\n  static _create(\n    type: 'or' | 'and',\n    _queryConstraints: QueryFilterConstraint[]\n  ): QueryCompositeFilterConstraint {\n    return new QueryCompositeFilterConstraint(type, _queryConstraints);\n  }\n\n  _parse<AppModelType, DbModelType extends DocumentData>(\n    query: Query<AppModelType, DbModelType>\n  ): Filter {\n    const parsedFilters = this._queryConstraints\n      .map(queryConstraint => {\n        return queryConstraint._parse(query);\n      })\n      .filter(parsedFilter => parsedFilter.getFilters().length > 0);\n\n    if (parsedFilters.length === 1) {\n      return parsedFilters[0];\n    }\n\n    return CompositeFilter.create(parsedFilters, this._getOperator());\n  }\n\n  _apply<AppModelType, DbModelType extends DocumentData>(\n    query: Query<AppModelType, DbModelType>\n  ): Query<AppModelType, DbModelType> {\n    const parsedFilter = this._parse(query);\n    if (parsedFilter.getFilters().length === 0) {\n      // Return the existing query if not adding any more filters (e.g. an empty\n      // composite filter).\n      return query;\n    }\n    validateNewFilter(query._query, parsedFilter);\n\n    return new Query(\n      query.firestore,\n      query.converter,\n      queryWithAddedFilter(query._query, parsedFilter)\n    );\n  }\n\n  _getQueryConstraints(): readonly AppliableConstraint[] {\n    return this._queryConstraints;\n  }\n\n  _getOperator(): CompositeOperator {\n    return this.type === 'and' ? CompositeOperator.AND : CompositeOperator.OR;\n  }\n}\n\n/**\n * `QueryNonFilterConstraint` is a helper union type that represents\n * QueryConstraints which are used to narrow or order the set of documents,\n * but that do not explicitly filter on a document field.\n * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},\n * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)},\n * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)}\n * to create a new query instance that also contains the `QueryConstraint`.\n */\nexport type QueryNonFilterConstraint =\n  | QueryOrderByConstraint\n  | QueryLimitConstraint\n  | QueryStartAtConstraint\n  | QueryEndAtConstraint;\n\n/**\n * `QueryFilterConstraint` is a helper union type that represents\n * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.\n */\nexport type QueryFilterConstraint =\n  | QueryFieldFilterConstraint\n  | QueryCompositeFilterConstraint;\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function or(\n  ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n  // Only support QueryFilterConstraints\n  queryConstraints.forEach(queryConstraint =>\n    validateQueryFilterConstraint('or', queryConstraint)\n  );\n\n  return QueryCompositeFilterConstraint._create(\n    CompositeOperator.OR,\n    queryConstraints as QueryFilterConstraint[]\n  );\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function and(\n  ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n  // Only support QueryFilterConstraints\n  queryConstraints.forEach(queryConstraint =>\n    validateQueryFilterConstraint('and', queryConstraint)\n  );\n\n  return QueryCompositeFilterConstraint._create(\n    CompositeOperator.AND,\n    queryConstraints as QueryFilterConstraint[]\n  );\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */\nexport class QueryOrderByConstraint extends QueryConstraint {\n  /** The type of this query constraint */\n  readonly type = 'orderBy';\n\n  /**\n   * @internal\n   */\n  protected constructor(\n    private readonly _field: InternalFieldPath,\n    private _direction: Direction\n  ) {\n    super();\n  }\n\n  static _create(\n    _field: InternalFieldPath,\n    _direction: Direction\n  ): QueryOrderByConstraint {\n    return new QueryOrderByConstraint(_field, _direction);\n  }\n\n  _apply<AppModelType, DbModelType extends DocumentData>(\n    query: Query<AppModelType, DbModelType>\n  ): Query<AppModelType, DbModelType> {\n    const orderBy = newQueryOrderBy(query._query, this._field, this._direction);\n    return new Query(\n      query.firestore,\n      query.converter,\n      queryWithAddedOrderBy(query._query, orderBy)\n    );\n  }\n}\n\n/**\n * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'\n * (descending or ascending).\n */\nexport type OrderByDirection = 'desc' | 'asc';\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */\nexport function orderBy(\n  fieldPath: string | FieldPath,\n  directionStr: OrderByDirection = 'asc'\n): QueryOrderByConstraint {\n  const direction = directionStr as Direction;\n  const path = fieldPathFromArgument('orderBy', fieldPath);\n  return QueryOrderByConstraint._create(path, direction);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */\nexport class QueryLimitConstraint extends QueryConstraint {\n  /**\n   * @internal\n   */\n  protected constructor(\n    /** The type of this query constraint */\n    readonly type: 'limit' | 'limitToLast',\n    private readonly _limit: number,\n    private readonly _limitType: LimitType\n  ) {\n    super();\n  }\n\n  static _create(\n    type: 'limit' | 'limitToLast',\n    _limit: number,\n    _limitType: LimitType\n  ): QueryLimitConstraint {\n    return new QueryLimitConstraint(type, _limit, _limitType);\n  }\n\n  _apply<AppModelType, DbModelType extends DocumentData>(\n    query: Query<AppModelType, DbModelType>\n  ): Query<AppModelType, DbModelType> {\n    return new Query(\n      query.firestore,\n      query.converter,\n      queryWithLimit(query._query, this._limit, this._limitType)\n    );\n  }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limit(limit: number): QueryLimitConstraint {\n  validatePositiveNumber('limit', limit);\n  return QueryLimitConstraint._create('limit', limit, LimitType.First);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limitToLast(limit: number): QueryLimitConstraint {\n  validatePositiveNumber('limitToLast', limit);\n  return QueryLimitConstraint._create('limitToLast', limit, LimitType.Last);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */\nexport class QueryStartAtConstraint extends QueryConstraint {\n  /**\n   * @internal\n   */\n  protected constructor(\n    /** The type of this query constraint */\n    readonly type: 'startAt' | 'startAfter',\n    private readonly _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n    private readonly _inclusive: boolean\n  ) {\n    super();\n  }\n\n  static _create(\n    type: 'startAt' | 'startAfter',\n    _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n    _inclusive: boolean\n  ): QueryStartAtConstraint {\n    return new QueryStartAtConstraint(type, _docOrFields, _inclusive);\n  }\n\n  _apply<AppModelType, DbModelType extends DocumentData>(\n    query: Query<AppModelType, DbModelType>\n  ): Query<AppModelType, DbModelType> {\n    const bound = newQueryBoundFromDocOrFields(\n      query,\n      this.type,\n      this._docOrFields,\n      this._inclusive\n    );\n    return new Query<AppModelType, DbModelType>(\n      query.firestore,\n      query.converter,\n      queryWithStartAt(query._query, bound)\n    );\n  }\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided document (inclusive). The starting position is relative\n * to the order of the query. The document must contain all of the fields\n * provided in the `orderBy` of this query.\n *\n * @param snapshot - The snapshot of the document to start at.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt<AppModelType, DbModelType extends DocumentData>(\n  snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query at, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAt<AppModelType, DbModelType extends DocumentData>(\n  ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryStartAtConstraint {\n  return QueryStartAtConstraint._create(\n    'startAt',\n    docOrFields,\n    /*inclusive=*/ true\n  );\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided document (exclusive). The starting position is\n * relative to the order of the query. The document must contain all of the\n * fields provided in the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to start after.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter<AppModelType, DbModelType extends DocumentData>(\n  snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided fields relative to the order of the query. The order\n * of the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query after, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAfter<AppModelType, DbModelType extends DocumentData>(\n  ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryStartAtConstraint {\n  return QueryStartAtConstraint._create(\n    'startAfter',\n    docOrFields,\n    /*inclusive=*/ false\n  );\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */\nexport class QueryEndAtConstraint extends QueryConstraint {\n  /**\n   * @internal\n   */\n  protected constructor(\n    /** The type of this query constraint */\n    readonly type: 'endBefore' | 'endAt',\n    private readonly _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n    private readonly _inclusive: boolean\n  ) {\n    super();\n  }\n\n  static _create(\n    type: 'endBefore' | 'endAt',\n    _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n    _inclusive: boolean\n  ): QueryEndAtConstraint {\n    return new QueryEndAtConstraint(type, _docOrFields, _inclusive);\n  }\n\n  _apply<AppModelType, DbModelType extends DocumentData>(\n    query: Query<AppModelType, DbModelType>\n  ): Query<AppModelType, DbModelType> {\n    const bound = newQueryBoundFromDocOrFields(\n      query,\n      this.type,\n      this._docOrFields,\n      this._inclusive\n    );\n    return new Query(\n      query.firestore,\n      query.converter,\n      queryWithEndAt(query._query, bound)\n    );\n  }\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided document (exclusive). The end position is relative to the\n * order of the query. The document must contain all of the fields provided in\n * the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end before.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore<AppModelType, DbModelType extends DocumentData>(\n  snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query before, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endBefore<AppModelType, DbModelType extends DocumentData>(\n  ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryEndAtConstraint {\n  return QueryEndAtConstraint._create(\n    'endBefore',\n    docOrFields,\n    /*inclusive=*/ false\n  );\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided document (inclusive). The end position is relative to the order\n * of the query. The document must contain all of the fields provided in the\n * orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end at.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt<AppModelType, DbModelType extends DocumentData>(\n  snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided fields relative to the order of the query. The order of the field\n * values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query at, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endAt<AppModelType, DbModelType extends DocumentData>(\n  ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryEndAtConstraint {\n  return QueryEndAtConstraint._create(\n    'endAt',\n    docOrFields,\n    /*inclusive=*/ true\n  );\n}\n\n/** Helper function to create a bound from a document or fields */\nfunction newQueryBoundFromDocOrFields<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  query: Query<AppModelType, DbModelType>,\n  methodName: string,\n  docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>,\n  inclusive: boolean\n): Bound {\n  docOrFields[0] = getModularInstance(docOrFields[0]);\n\n  if (docOrFields[0] instanceof DocumentSnapshot) {\n    return newQueryBoundFromDocument(\n      query._query,\n      query.firestore._databaseId,\n      methodName,\n      docOrFields[0]._document,\n      inclusive\n    );\n  } else {\n    const reader = newUserDataReader(query.firestore);\n    return newQueryBoundFromFields(\n      query._query,\n      query.firestore._databaseId,\n      reader,\n      methodName,\n      docOrFields,\n      inclusive\n    );\n  }\n}\n\nexport function newQueryFilter(\n  query: InternalQuery,\n  methodName: string,\n  dataReader: UserDataReader,\n  databaseId: DatabaseId,\n  fieldPath: InternalFieldPath,\n  op: Operator,\n  value: unknown\n): FieldFilter {\n  let fieldValue: ProtoValue;\n  if (fieldPath.isKeyField()) {\n    if (op === Operator.ARRAY_CONTAINS || op === Operator.ARRAY_CONTAINS_ANY) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        `Invalid Query. You can't perform '${op}' queries on documentId().`\n      );\n    } else if (op === Operator.IN || op === Operator.NOT_IN) {\n      validateDisjunctiveFilterElements(value, op);\n      const referenceList: ProtoValue[] = [];\n      for (const arrayValue of value as ProtoValue[]) {\n        referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));\n      }\n      fieldValue = { arrayValue: { values: referenceList } };\n    } else {\n      fieldValue = parseDocumentIdValue(databaseId, query, value);\n    }\n  } else {\n    if (\n      op === Operator.IN ||\n      op === Operator.NOT_IN ||\n      op === Operator.ARRAY_CONTAINS_ANY\n    ) {\n      validateDisjunctiveFilterElements(value, op);\n    }\n    fieldValue = parseQueryValue(\n      dataReader,\n      methodName,\n      value,\n      /* allowArrays= */ op === Operator.IN || op === Operator.NOT_IN\n    );\n  }\n  const filter = FieldFilter.create(fieldPath, op, fieldValue);\n  return filter;\n}\n\nexport function newQueryOrderBy(\n  query: InternalQuery,\n  fieldPath: InternalFieldPath,\n  direction: Direction\n): OrderBy {\n  if (query.startAt !== null) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'Invalid query. You must not call startAt() or startAfter() before ' +\n        'calling orderBy().'\n    );\n  }\n  if (query.endAt !== null) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'Invalid query. You must not call endAt() or endBefore() before ' +\n        'calling orderBy().'\n    );\n  }\n  const orderBy = new OrderBy(fieldPath, direction);\n  return orderBy;\n}\n\n/**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */\nexport function newQueryBoundFromDocument(\n  query: InternalQuery,\n  databaseId: DatabaseId,\n  methodName: string,\n  doc: Document | null,\n  inclusive: boolean\n): Bound {\n  if (!doc) {\n    throw new FirestoreError(\n      Code.NOT_FOUND,\n      `Can't use a DocumentSnapshot that doesn't exist for ` +\n        `${methodName}().`\n    );\n  }\n\n  const components: ProtoValue[] = [];\n\n  // Because people expect to continue/end a query at the exact document\n  // provided, we need to use the implicit sort order rather than the explicit\n  // sort order, because it's guaranteed to contain the document key. That way\n  // the position becomes unambiguous and the query continues/ends exactly at\n  // the provided document. Without the key (by using the explicit sort\n  // orders), multiple documents could match the position, yielding duplicate\n  // results.\n  for (const orderBy of queryNormalizedOrderBy(query)) {\n    if (orderBy.field.isKeyField()) {\n      components.push(refValue(databaseId, doc.key));\n    } else {\n      const value = doc.data.field(orderBy.field);\n      if (isServerTimestamp(value)) {\n        throw new FirestoreError(\n          Code.INVALID_ARGUMENT,\n          'Invalid query. You are trying to start or end a query using a ' +\n            'document for which the field \"' +\n            orderBy.field +\n            '\" is an uncommitted server timestamp. (Since the value of ' +\n            'this field is unknown, you cannot start/end a query with it.)'\n        );\n      } else if (value !== null) {\n        components.push(value);\n      } else {\n        const field = orderBy.field.canonicalString();\n        throw new FirestoreError(\n          Code.INVALID_ARGUMENT,\n          `Invalid query. You are trying to start or end a query using a ` +\n            `document for which the field '${field}' (used as the ` +\n            `orderBy) does not exist.`\n        );\n      }\n    }\n  }\n  return new Bound(components, inclusive);\n}\n\n/**\n * Converts a list of field values to a `Bound` for the given query.\n */\nexport function newQueryBoundFromFields(\n  query: InternalQuery,\n  databaseId: DatabaseId,\n  dataReader: UserDataReader,\n  methodName: string,\n  values: unknown[],\n  inclusive: boolean\n): Bound {\n  // Use explicit order by's because it has to match the query the user made\n  const orderBy = query.explicitOrderBy;\n  if (values.length > orderBy.length) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      `Too many arguments provided to ${methodName}(). ` +\n        `The number of arguments must be less than or equal to the ` +\n        `number of orderBy() clauses`\n    );\n  }\n\n  const components: ProtoValue[] = [];\n  for (let i = 0; i < values.length; i++) {\n    const rawValue = values[i];\n    const orderByComponent = orderBy[i];\n    if (orderByComponent.field.isKeyField()) {\n      if (typeof rawValue !== 'string') {\n        throw new FirestoreError(\n          Code.INVALID_ARGUMENT,\n          `Invalid query. Expected a string for document ID in ` +\n            `${methodName}(), but got a ${typeof rawValue}`\n        );\n      }\n      if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {\n        throw new FirestoreError(\n          Code.INVALID_ARGUMENT,\n          `Invalid query. When querying a collection and ordering by documentId(), ` +\n            `the value passed to ${methodName}() must be a plain document ID, but ` +\n            `'${rawValue}' contains a slash.`\n        );\n      }\n      const path = query.path.child(ResourcePath.fromString(rawValue));\n      if (!DocumentKey.isDocumentKey(path)) {\n        throw new FirestoreError(\n          Code.INVALID_ARGUMENT,\n          `Invalid query. When querying a collection group and ordering by ` +\n            `documentId(), the value passed to ${methodName}() must result in a ` +\n            `valid document path, but '${path}' is not because it contains an odd number ` +\n            `of segments.`\n        );\n      }\n      const key = new DocumentKey(path);\n      components.push(refValue(databaseId, key));\n    } else {\n      const wrapped = parseQueryValue(dataReader, methodName, rawValue);\n      components.push(wrapped);\n    }\n  }\n\n  return new Bound(components, inclusive);\n}\n\n/**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */\nfunction parseDocumentIdValue(\n  databaseId: DatabaseId,\n  query: InternalQuery,\n  documentIdValue: unknown\n): ProtoValue {\n  documentIdValue = getModularInstance(documentIdValue);\n\n  if (typeof documentIdValue === 'string') {\n    if (documentIdValue === '') {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Invalid query. When querying with documentId(), you ' +\n          'must provide a valid document ID, but it was an empty string.'\n      );\n    }\n    if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        `Invalid query. When querying a collection by ` +\n          `documentId(), you must provide a plain document ID, but ` +\n          `'${documentIdValue}' contains a '/' character.`\n      );\n    }\n    const path = query.path.child(ResourcePath.fromString(documentIdValue));\n    if (!DocumentKey.isDocumentKey(path)) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        `Invalid query. When querying a collection group by ` +\n          `documentId(), the value provided must result in a valid document path, ` +\n          `but '${path}' is not because it has an odd number of segments (${path.length}).`\n      );\n    }\n    return refValue(databaseId, new DocumentKey(path));\n  } else if (documentIdValue instanceof DocumentReference) {\n    return refValue(databaseId, documentIdValue._key);\n  } else {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      `Invalid query. When querying with documentId(), you must provide a valid ` +\n        `string or a DocumentReference, but it was: ` +\n        `${valueDescription(documentIdValue)}.`\n    );\n  }\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */\nfunction validateDisjunctiveFilterElements(\n  value: unknown,\n  operator: Operator\n): void {\n  if (!Array.isArray(value) || value.length === 0) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'Invalid Query. A non-empty array is required for ' +\n        `'${operator.toString()}' filters.`\n    );\n  }\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */\nfunction conflictingOps(op: Operator): Operator[] {\n  switch (op) {\n    case Operator.NOT_EQUAL:\n      return [Operator.NOT_EQUAL, Operator.NOT_IN];\n    case Operator.ARRAY_CONTAINS_ANY:\n    case Operator.IN:\n      return [Operator.NOT_IN];\n    case Operator.NOT_IN:\n      return [\n        Operator.ARRAY_CONTAINS_ANY,\n        Operator.IN,\n        Operator.NOT_IN,\n        Operator.NOT_EQUAL\n      ];\n    default:\n      return [];\n  }\n}\n\nfunction validateNewFieldFilter(\n  query: InternalQuery,\n  fieldFilter: FieldFilter\n): void {\n  const conflictingOp = findOpInsideFilters(\n    query.filters,\n    conflictingOps(fieldFilter.op)\n  );\n  if (conflictingOp !== null) {\n    // Special case when it's a duplicate op to give a slightly clearer error message.\n    if (conflictingOp === fieldFilter.op) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Invalid query. You cannot use more than one ' +\n          `'${fieldFilter.op.toString()}' filter.`\n      );\n    } else {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +\n          `with '${conflictingOp.toString()}' filters.`\n      );\n    }\n  }\n}\n\nfunction validateNewFilter(query: InternalQuery, filter: Filter): void {\n  let testQuery = query;\n  const subFilters = filter.getFlattenedFilters();\n  for (const subFilter of subFilters) {\n    validateNewFieldFilter(testQuery, subFilter);\n    testQuery = queryWithAddedFilter(testQuery, subFilter);\n  }\n}\n\n// Checks if any of the provided filter operators are included in the given list of filters and\n// returns the first one that is, or null if none are.\nfunction findOpInsideFilters(\n  filters: Filter[],\n  operators: Operator[]\n): Operator | null {\n  for (const filter of filters) {\n    for (const fieldFilter of filter.getFlattenedFilters()) {\n      if (operators.indexOf(fieldFilter.op) >= 0) {\n        return fieldFilter.op;\n      }\n    }\n  }\n  return null;\n}\n\nexport function validateQueryFilterConstraint(\n  functionName: string,\n  queryConstraint: AppliableConstraint\n): void {\n  if (\n    !(queryConstraint instanceof QueryFieldFilterConstraint) &&\n    !(queryConstraint instanceof QueryCompositeFilterConstraint)\n  ) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`\n    );\n  }\n}\n\nfunction validateQueryConstraintArray(\n  queryConstraint: AppliableConstraint[]\n): void {\n  const compositeFilterCount = queryConstraint.filter(\n    filter => filter instanceof QueryCompositeFilterConstraint\n  ).length;\n  const fieldFilterCount = queryConstraint.filter(\n    filter => filter instanceof QueryFieldFilterConstraint\n  ).length;\n\n  if (\n    compositeFilterCount > 1 ||\n    (compositeFilterCount > 0 && fieldFilterCount > 0)\n  ) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'InvalidQuery. When using composite filters, you cannot use ' +\n        'more than one filter at the top level. Consider nesting the multiple ' +\n        'filters within an `and(...)` statement. For example: ' +\n        'change `query(query, where(...), or(...))` to ' +\n        '`query(query, and(where(...), or(...)))`.'\n    );\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  DocumentData as PublicDocumentData,\n  SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n  invokeBatchGetDocumentsRpc,\n  invokeCommitRpc,\n  invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n  CollectionReference,\n  doc,\n  DocumentData,\n  DocumentReference,\n  PartialWithFieldValue,\n  Query,\n  SetOptions,\n  UpdateData,\n  WithFieldValue\n} from './reference';\nimport {\n  DocumentSnapshot,\n  QueryDocumentSnapshot,\n  QuerySnapshot\n} from './snapshot';\nimport {\n  newUserDataReader,\n  ParsedUpdateData,\n  parseSetData,\n  parseUpdateData,\n  parseUpdateVarargs,\n  UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter<T>(\n  converter: UntypedFirestoreDataConverter<T> | null,\n  value: WithFieldValue<T> | PartialWithFieldValue<T>,\n  options?: PublicSetOptions\n): PublicDocumentData {\n  let convertedValue;\n  if (converter) {\n    if (options && (options.merge || options.mergeFields)) {\n      // Cast to `any` in order to satisfy the union type constraint on\n      // toFirestore().\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      convertedValue = (converter as any).toFirestore(value, options);\n    } else {\n      convertedValue = converter.toFirestore(value as WithFieldValue<T>);\n    }\n  } else {\n    convertedValue = value as PublicDocumentData;\n  }\n  return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n  constructor(protected firestore: Firestore) {\n    super();\n  }\n\n  protected convertBytes(bytes: ByteString): Bytes {\n    return new Bytes(bytes);\n  }\n\n  protected convertReference(name: string): DocumentReference {\n    const key = this.convertDocumentKey(name, this.firestore._databaseId);\n    return new DocumentReference(this.firestore, /* converter= */ null, key);\n  }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n  reference = cast<DocumentReference<AppModelType, DbModelType>>(\n    reference,\n    DocumentReference\n  );\n  const datastore = getDatastore(reference.firestore);\n  const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n  return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n    result => {\n      hardAssert(\n        result.length === 1,\n        0x3d02,\n        'Expected a single document result'\n      );\n      const document = result[0];\n      return new DocumentSnapshot<AppModelType, DbModelType>(\n        reference.firestore,\n        userDataWriter,\n        reference._key,\n        document.isFoundDocument() ? document : null,\n        reference.converter\n      );\n    }\n  );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs<AppModelType, DbModelType extends DocumentData>(\n  query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n  query = cast<Query<AppModelType, DbModelType>>(query, Query);\n  validateHasExplicitOrderByForLimitToLast(query._query);\n\n  const datastore = getDatastore(query.firestore);\n  const userDataWriter = new LiteUserDataWriter(query.firestore);\n  return invokeRunQueryRpc(datastore, query._query).then(result => {\n    const docs = result.map(\n      doc =>\n        new QueryDocumentSnapshot<AppModelType, DbModelType>(\n          query.firestore,\n          userDataWriter,\n          doc.key,\n          doc,\n          query.converter\n        )\n    );\n\n    if (query._query.limitType === LimitType.Last) {\n      // Limit to last queries reverse the orderBy constraint that was\n      // specified by the user. As such, we need to reverse the order of the\n      // results to return the documents in the expected order.\n      docs.reverse();\n    }\n\n    return new QuerySnapshot<AppModelType, DbModelType>(query, docs);\n  });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  data: WithFieldValue<AppModelType>\n): Promise<void>;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  data: PartialWithFieldValue<AppModelType>,\n  options: SetOptions\n): Promise<void>;\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  data: PartialWithFieldValue<AppModelType>,\n  options?: SetOptions\n): Promise<void> {\n  reference = cast<DocumentReference<AppModelType, DbModelType>>(\n    reference,\n    DocumentReference\n  );\n  const convertedValue = applyFirestoreDataConverter(\n    reference.converter,\n    data,\n    options\n  );\n  const dataReader = newUserDataReader(reference.firestore);\n  const parsed = parseSetData(\n    dataReader,\n    'setDoc',\n    reference._key,\n    convertedValue,\n    reference.converter !== null,\n    options\n  );\n\n  const datastore = getDatastore(reference.firestore);\n  return invokeCommitRpc(datastore, [\n    parsed.toMutation(reference._key, Precondition.none())\n  ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  data: UpdateData<DbModelType>\n): Promise<void>;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  field: string | FieldPath,\n  value: unknown,\n  ...moreFieldsAndValues: unknown[]\n): Promise<void>;\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n  value?: unknown,\n  ...moreFieldsAndValues: unknown[]\n): Promise<void> {\n  reference = cast<DocumentReference<AppModelType, DbModelType>>(\n    reference,\n    DocumentReference\n  );\n  const dataReader = newUserDataReader(reference.firestore);\n\n  // For Compat types, we have to \"extract\" the underlying types before\n  // performing validation.\n  fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n  let parsed: ParsedUpdateData;\n  if (\n    typeof fieldOrUpdateData === 'string' ||\n    fieldOrUpdateData instanceof FieldPath\n  ) {\n    parsed = parseUpdateVarargs(\n      dataReader,\n      'updateDoc',\n      reference._key,\n      fieldOrUpdateData,\n      value,\n      moreFieldsAndValues\n    );\n  } else {\n    parsed = parseUpdateData(\n      dataReader,\n      'updateDoc',\n      reference._key,\n      fieldOrUpdateData\n    );\n  }\n\n  const datastore = getDatastore(reference.firestore);\n  return invokeCommitRpc(datastore, [\n    parsed.toMutation(reference._key, Precondition.exists(true))\n  ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>\n): Promise<void> {\n  reference = cast<DocumentReference<AppModelType, DbModelType>>(\n    reference,\n    DocumentReference\n  );\n  const datastore = getDatastore(reference.firestore);\n  return invokeCommitRpc(datastore, [\n    new DeleteMutation(reference._key, Precondition.none())\n  ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: CollectionReference<AppModelType, DbModelType>,\n  data: WithFieldValue<AppModelType>\n): Promise<DocumentReference<AppModelType, DbModelType>> {\n  reference = cast<CollectionReference<AppModelType, DbModelType>>(\n    reference,\n    CollectionReference\n  );\n  const docRef = doc(reference);\n\n  const convertedValue = applyFirestoreDataConverter(\n    reference.converter,\n    data as PartialWithFieldValue<AppModelType>\n  );\n\n  const dataReader = newUserDataReader(reference.firestore);\n  const parsed = parseSetData(\n    dataReader,\n    'addDoc',\n    docRef._key,\n    convertedValue,\n    docRef.converter !== null,\n    {}\n  );\n\n  const datastore = getDatastore(reference.firestore);\n  return invokeCommitRpc(datastore, [\n    parsed.toMutation(docRef._key, Precondition.exists(false))\n  ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n  AggregateField,\n  AggregateQuerySnapshot,\n  AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query - The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount<AppModelType, DbModelType extends DocumentData>(\n  query: Query<AppModelType, DbModelType>\n): Promise<\n  AggregateQuerySnapshot<\n    { count: AggregateField<number> },\n    AppModelType,\n    DbModelType\n  >\n> {\n  const countQuerySpec: { count: AggregateField<number> } = {\n    count: count()\n  };\n\n  return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query - The query whose result set is aggregated over.\n * @param aggregateSpec - An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n *   countOfDocs: count(),\n *   totalHours: sum('hours'),\n *   averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n  AggregateSpecType extends AggregateSpec,\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  query: Query<AppModelType, DbModelType>,\n  aggregateSpec: AggregateSpecType\n): Promise<\n  AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>\n> {\n  const firestore = cast(query.firestore, Firestore);\n  const datastore = getDatastore(firestore);\n\n  const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n    return new AggregateImpl(\n      alias,\n      aggregate.aggregateType,\n      aggregate._internalFieldPath\n    );\n  });\n\n  // Run the aggregation and convert the results\n  return invokeRunAggregationQueryRpc(\n    datastore,\n    query._query,\n    internalAggregates\n  ).then(aggregateResult =>\n    convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n  );\n}\n\nfunction convertToAggregateQuerySnapshot<\n  AggregateSpecType extends AggregateSpec,\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  firestore: Firestore,\n  query: Query<AppModelType, DbModelType>,\n  aggregateResult: ApiClientObjectMap<Value>\n): AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType> {\n  const userDataWriter = new LiteUserDataWriter(firestore);\n  const querySnapshot = new AggregateQuerySnapshot<\n    AggregateSpecType,\n    AppModelType,\n    DbModelType\n  >(query, userDataWriter, aggregateResult);\n  return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field - Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField<number> {\n  return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field - Specifies the field to average across the result set.\n */\nexport function average(\n  field: string | FieldPath\n): AggregateField<number | null> {\n  return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField<number> {\n  return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left - Compare this AggregateField to the `right`.\n * @param right - Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n  left: AggregateField<unknown>,\n  right: AggregateField<unknown>\n): boolean {\n  return (\n    left instanceof AggregateField &&\n    right instanceof AggregateField &&\n    left.aggregateType === right.aggregateType &&\n    left._internalFieldPath?.canonicalString() ===\n      right._internalFieldPath?.canonicalString()\n  );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n  AggregateSpecType extends AggregateSpec,\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  left: AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>,\n  right: AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>\n): boolean {\n  return (\n    queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\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 { AggregateImpl } from '../core/aggregate';\nimport { firestoreClientRunAggregateQuery } from '../core/firestore_client';\nimport { count } from '../lite-api/aggregate';\nimport {\n  AggregateField,\n  AggregateQuerySnapshot,\n  AggregateSpec\n} from '../lite-api/aggregate_types';\nimport { DocumentData, Query } from '../lite-api/reference';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './user_data_writer';\n\nexport {\n  aggregateQuerySnapshotEqual,\n  count,\n  sum,\n  average,\n  aggregateFieldEqual\n} from '../lite-api/aggregate';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query - The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCountFromServer<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  query: Query<AppModelType, DbModelType>\n): Promise<\n  AggregateQuerySnapshot<\n    { count: AggregateField<number> },\n    AppModelType,\n    DbModelType\n  >\n> {\n  const countQuerySpec: { count: AggregateField<number> } = {\n    count: count()\n  };\n\n  return getAggregateFromServer(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query - The query whose result set is aggregated over.\n * @param aggregateSpec - An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregateFromServer(query, {\n *   countOfDocs: count(),\n *   totalHours: sum('hours'),\n *   averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregateFromServer<\n  AggregateSpecType extends AggregateSpec,\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  query: Query<AppModelType, DbModelType>,\n  aggregateSpec: AggregateSpecType\n): Promise<\n  AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>\n> {\n  const firestore = cast(query.firestore, Firestore);\n  const client = ensureFirestoreConfigured(firestore);\n\n  const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n    return new AggregateImpl(\n      alias,\n      aggregate.aggregateType,\n      aggregate._internalFieldPath\n    );\n  });\n\n  // Run the aggregation and convert the results\n  return firestoreClientRunAggregateQuery(\n    client,\n    query._query,\n    internalAggregates\n  ).then(aggregateResult =>\n    convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n  );\n}\n\n/**\n * Converts the core aggregation result to an `AggregateQuerySnapshot`\n * that can be returned to the consumer.\n * @param query\n * @param aggregateResult - Core aggregation result\n * @internal\n */\nfunction convertToAggregateQuerySnapshot<\n  AggregateSpecType extends AggregateSpec,\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  firestore: Firestore,\n  query: Query<AppModelType, DbModelType>,\n  aggregateResult: ApiClientObjectMap<Value>\n): AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType> {\n  const userDataWriter = new ExpUserDataWriter(firestore);\n  const querySnapshot = new AggregateQuerySnapshot<\n    AggregateSpecType,\n    AppModelType,\n    DbModelType\n  >(query, userDataWriter, aggregateResult);\n  return querySnapshot;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  IndexedDbOfflineComponentProvider,\n  LruGcMemoryOfflineComponentProvider,\n  MemoryOfflineComponentProvider,\n  MultiTabOfflineComponentProvider,\n  OfflineComponentProviderFactory,\n  OnlineComponentProviderFactory,\n  OnlineComponentProvider\n} from '../core/component_provider';\n\n/* eslint @typescript-eslint/consistent-type-definitions: [\"error\", \"type\"] */\n/**\n * Provides an in-memory cache to the SDK. This is the default cache unless explicitly\n * configured otherwise.\n *\n * To use, create an instance using the factory function {@link memoryLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type MemoryLocalCache = {\n  kind: 'memory';\n  /**\n   * @internal\n   */\n  _onlineComponentProvider: OnlineComponentProviderFactory;\n  /**\n   * @internal\n   */\n  _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass MemoryLocalCacheImpl implements MemoryLocalCache {\n  kind: 'memory' = 'memory';\n  /**\n   * @internal\n   */\n  _onlineComponentProvider: OnlineComponentProviderFactory;\n  /**\n   * @internal\n   */\n  _offlineComponentProvider: OfflineComponentProviderFactory;\n\n  constructor(settings?: MemoryCacheSettings) {\n    this._onlineComponentProvider = OnlineComponentProvider.provider;\n    if (settings?.garbageCollector) {\n      this._offlineComponentProvider =\n        settings.garbageCollector._offlineComponentProvider;\n    } else {\n      this._offlineComponentProvider = {\n        build: () => new LruGcMemoryOfflineComponentProvider(undefined)\n      };\n    }\n  }\n\n  toJSON(): {} {\n    return { kind: this.kind };\n  }\n}\n\n/**\n * Provides a persistent cache backed by IndexedDb to the SDK.\n *\n * To use, create an instance using the factory function {@link persistentLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type PersistentLocalCache = {\n  kind: 'persistent';\n  /**\n   * @internal\n   */\n  _onlineComponentProvider: OnlineComponentProviderFactory;\n  /**\n   * @internal\n   */\n  _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass PersistentLocalCacheImpl implements PersistentLocalCache {\n  kind: 'persistent' = 'persistent';\n  /**\n   * @internal\n   */\n  _onlineComponentProvider: OnlineComponentProviderFactory;\n  /**\n   * @internal\n   */\n  _offlineComponentProvider: OfflineComponentProviderFactory;\n\n  constructor(settings: PersistentCacheSettings | undefined) {\n    let tabManager: PersistentTabManager;\n    if (settings?.tabManager) {\n      settings.tabManager._initialize(settings);\n      tabManager = settings.tabManager;\n    } else {\n      tabManager = persistentSingleTabManager(undefined);\n      tabManager._initialize(settings);\n    }\n    this._onlineComponentProvider = tabManager._onlineComponentProvider!;\n    this._offlineComponentProvider = tabManager._offlineComponentProvider!;\n  }\n\n  toJSON(): {} {\n    return { kind: this.kind };\n  }\n}\n\n/**\n * Union type from all supported SDK cache layer.\n */\nexport type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache;\n\n/**\n * Union type from all support garbage collectors for memory local cache.\n */\nexport type MemoryGarbageCollector =\n  | MemoryEagerGarbageCollector\n  | MemoryLruGarbageCollector;\n\n/**\n * A garbage collector deletes documents whenever they are not part of any\n * active queries, and have no local mutations attached to them.\n *\n * This collector tries to ensure lowest memory footprints from the SDK,\n * at the risk of documents not being cached for offline queries or for\n * direct queries to the cache.\n *\n * Use factory function {@link memoryEagerGarbageCollector()} to create an\n * instance of this collector.\n */\nexport type MemoryEagerGarbageCollector = {\n  kind: 'memoryEager';\n  /**\n   * @internal\n   */\n  _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\n/**\n * A garbage collector deletes Least-Recently-Used documents in multiple\n * batches.\n *\n * This collector is configured with a target size, and will only perform\n * collection when the cached documents exceed the target size. It avoids\n * querying backend repeated for the same query or document, at the risk\n * of having a larger memory footprint.\n *\n * Use factory function {@link memoryLruGarbageCollector()} to create a\n * instance of this collector.\n */\nexport type MemoryLruGarbageCollector = {\n  kind: 'memoryLru';\n  /**\n   * @internal\n   */\n  _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass MemoryEagerGarbageCollectorImpl implements MemoryEagerGarbageCollector {\n  kind: 'memoryEager' = 'memoryEager';\n  /**\n   * @internal\n   */\n  _offlineComponentProvider: OfflineComponentProviderFactory;\n\n  constructor() {\n    this._offlineComponentProvider = MemoryOfflineComponentProvider.provider;\n  }\n\n  toJSON(): {} {\n    return { kind: this.kind };\n  }\n}\n\nclass MemoryLruGarbageCollectorImpl implements MemoryLruGarbageCollector {\n  kind: 'memoryLru' = 'memoryLru';\n  /**\n   * @internal\n   */\n  _offlineComponentProvider: OfflineComponentProviderFactory;\n\n  constructor(cacheSize?: number) {\n    this._offlineComponentProvider = {\n      build: () => new LruGcMemoryOfflineComponentProvider(cacheSize)\n    };\n  }\n\n  toJSON(): {} {\n    return { kind: this.kind };\n  }\n}\n\n/**\n * Creates an instance of `MemoryEagerGarbageCollector`. This is also the\n * default garbage collector unless it is explicitly specified otherwise.\n */\nexport function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector {\n  return new MemoryEagerGarbageCollectorImpl();\n}\n\n/**\n * Creates an instance of `MemoryLruGarbageCollector`.\n *\n * A target size can be specified as part of the setting parameter. The\n * collector will start deleting documents once the cache size exceeds\n * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).\n */\nexport function memoryLruGarbageCollector(settings?: {\n  cacheSizeBytes?: number;\n}): MemoryLruGarbageCollector {\n  return new MemoryLruGarbageCollectorImpl(settings?.cacheSizeBytes);\n}\n\n/**\n * An settings object to configure an `MemoryLocalCache` instance.\n */\nexport type MemoryCacheSettings = {\n  /**\n   * The garbage collector to use, for the memory cache layer.\n   * A `MemoryEagerGarbageCollector` is used when this is undefined.\n   */\n  garbageCollector?: MemoryGarbageCollector;\n};\n\n/**\n * Creates an instance of `MemoryLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n */\nexport function memoryLocalCache(\n  settings?: MemoryCacheSettings\n): MemoryLocalCache {\n  return new MemoryLocalCacheImpl(settings);\n}\n\n/**\n * An settings object to configure an `PersistentLocalCache` instance.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport type PersistentCacheSettings = {\n  /**\n   * An approximate cache size threshold for the on-disk data. If the cache\n   * grows beyond this size, Firestore will start removing data that hasn't been\n   * recently used. The SDK does not guarantee that the cache will stay below\n   * that size, only that if the cache exceeds the given size, cleanup will be\n   * attempted.\n   *\n   * The default value is 40 MB. The threshold must be set to at least 1 MB, and\n   * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection.\n   */\n  cacheSizeBytes?: number;\n\n  /**\n   * Specifies how multiple tabs/windows will be managed by the SDK.\n   */\n  tabManager?: PersistentTabManager;\n};\n\n/**\n * Creates an instance of `PersistentLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport function persistentLocalCache(\n  settings?: PersistentCacheSettings\n): PersistentLocalCache {\n  return new PersistentLocalCacheImpl(settings);\n}\n\n/**\n * A tab manager supporting only one tab, no synchronization will be\n * performed across tabs.\n */\nexport type PersistentSingleTabManager = {\n  kind: 'persistentSingleTab';\n  /**\n   * @internal\n   */\n  _initialize: (\n    settings: Omit<PersistentCacheSettings, 'tabManager'> | undefined\n  ) => void;\n  /**\n   * @internal\n   */\n  _onlineComponentProvider?: OnlineComponentProviderFactory;\n  /**\n   * @internal\n   */\n  _offlineComponentProvider?: OfflineComponentProviderFactory;\n};\n\nclass SingleTabManagerImpl implements PersistentSingleTabManager {\n  kind: 'persistentSingleTab' = 'persistentSingleTab';\n\n  /**\n   * @internal\n   */\n  _onlineComponentProvider?: OnlineComponentProviderFactory;\n  /**\n   * @internal\n   */\n  _offlineComponentProvider?: OfflineComponentProviderFactory;\n\n  constructor(private forceOwnership?: boolean) {}\n\n  toJSON(): {} {\n    return { kind: this.kind };\n  }\n\n  /**\n   * @internal\n   */\n  _initialize(\n    settings: Omit<PersistentCacheSettings, 'tabManager'> | undefined\n  ): void {\n    this._onlineComponentProvider = OnlineComponentProvider.provider;\n    this._offlineComponentProvider = {\n      build: (onlineComponents: OnlineComponentProvider) =>\n        new IndexedDbOfflineComponentProvider(\n          onlineComponents,\n          settings?.cacheSizeBytes,\n          this.forceOwnership\n        )\n    };\n  }\n}\n\n/**\n * A tab manager supporting multiple tabs. SDK will synchronize queries and\n * mutations done across all tabs using the SDK.\n */\nexport type PersistentMultipleTabManager = {\n  kind: 'PersistentMultipleTab';\n  /**\n   * @internal\n   */\n  _initialize: (settings: Omit<PersistentCacheSettings, 'tabManager'>) => void;\n  /**\n   * @internal\n   */\n  _onlineComponentProvider?: OnlineComponentProviderFactory;\n  /**\n   * @internal\n   */\n\n  _offlineComponentProvider?: OfflineComponentProviderFactory;\n};\n\nclass MultiTabManagerImpl implements PersistentMultipleTabManager {\n  kind: 'PersistentMultipleTab' = 'PersistentMultipleTab';\n\n  /**\n   * @internal\n   */\n  _onlineComponentProvider?: OnlineComponentProviderFactory;\n  /**\n   * @internal\n   */\n  _offlineComponentProvider?: OfflineComponentProviderFactory;\n\n  toJSON(): {} {\n    return { kind: this.kind };\n  }\n\n  /**\n   * @internal\n   */\n  _initialize(\n    settings: Omit<PersistentCacheSettings, 'tabManager'> | undefined\n  ): void {\n    this._onlineComponentProvider = OnlineComponentProvider.provider;\n    this._offlineComponentProvider = {\n      build: (onlineComponents: OnlineComponentProvider) =>\n        new MultiTabOfflineComponentProvider(\n          onlineComponents,\n          settings?.cacheSizeBytes\n        )\n    };\n  }\n}\n\n/**\n * A union of all available tab managers.\n */\nexport type PersistentTabManager =\n  | PersistentSingleTabManager\n  | PersistentMultipleTabManager;\n\n/**\n * Type to configure an `PersistentSingleTabManager` instance.\n */\nexport type PersistentSingleTabManagerSettings = {\n  /**\n   * Whether to force-enable persistent (IndexedDB) cache for the client. This\n   * cannot be used with multi-tab synchronization and is primarily intended for\n   * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause\n   * other tabs using IndexedDB cache to fail.\n   */\n  forceOwnership?: boolean;\n};\n/**\n * Creates an instance of `PersistentSingleTabManager`.\n *\n * @param settings - Configures the created tab manager.\n */\nexport function persistentSingleTabManager(\n  settings: PersistentSingleTabManagerSettings | undefined\n): PersistentSingleTabManager {\n  return new SingleTabManagerImpl(settings?.forceOwnership);\n}\n\n/**\n * Creates an instance of `PersistentMultipleTabManager`.\n */\nexport function persistentMultipleTabManager(): PersistentMultipleTabManager {\n  return new MultiTabManagerImpl();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { DatabaseId } from '../../../src/core/database_info';\nimport {\n  LimitType,\n  Query,\n  queryToTarget,\n  queryWithLimit\n} from '../../../src/core/query';\nimport { DocumentKey } from '../../../src/model/document_key';\nimport { newSerializer } from '../../../src/platform/serializer';\nimport { newTextEncoder } from '../../../src/platform/text_serializer';\nimport {\n  BundleElement,\n  LimitType as BundleLimitType\n} from '../../../src/protos/firestore_bundle_proto';\nimport * as api from '../../../src/protos/firestore_proto_api';\nimport { Value } from '../../../src/protos/firestore_proto_api';\nimport {\n  JsonProtoSerializer,\n  toName,\n  toQueryTarget\n} from '../../../src/remote/serializer';\n\nexport const encoder = newTextEncoder();\n\nfunction lengthPrefixedString(o: {}): string {\n  const str = JSON.stringify(o);\n  const l = encoder.encode(str).byteLength;\n  return `${l}${str}`;\n}\n\nexport class TestBundleBuilder {\n  readonly elements: BundleElement[] = [];\n  private serializer: JsonProtoSerializer;\n  constructor(private databaseId: DatabaseId) {\n    this.serializer = newSerializer(databaseId);\n  }\n\n  addDocumentMetadata(\n    docKey: DocumentKey,\n    readTime: api.Timestamp,\n    exists: boolean\n  ): TestBundleBuilder {\n    this.elements.push({\n      documentMetadata: {\n        name: toName(this.serializer, docKey),\n        readTime,\n        exists\n      }\n    });\n    return this;\n  }\n  addDocument(\n    docKey: DocumentKey,\n    createTime: api.Timestamp,\n    updateTime: api.Timestamp,\n    fields: api.ApiClientObjectMap<Value>\n  ): TestBundleBuilder {\n    this.elements.push({\n      document: {\n        name: toName(this.serializer, docKey),\n        createTime,\n        updateTime,\n        fields\n      }\n    });\n    return this;\n  }\n\n  addNamedQuery(\n    name: string,\n    readTime: api.Timestamp,\n    query: Query\n  ): TestBundleBuilder {\n    let bundledLimitType: BundleLimitType | undefined = !!query.limit\n      ? 'FIRST'\n      : undefined;\n    if (query.limitType === LimitType.Last) {\n      query = queryWithLimit(query, query.limit!, LimitType.First);\n      bundledLimitType = 'LAST';\n    }\n    const queryTarget = toQueryTarget(\n      this.serializer,\n      queryToTarget(query)\n    ).queryTarget;\n    this.elements.push({\n      namedQuery: {\n        name,\n        readTime,\n        bundledQuery: {\n          parent: queryTarget.parent,\n          structuredQuery: queryTarget.structuredQuery,\n          limitType: bundledLimitType\n        }\n      }\n    });\n    return this;\n  }\n\n  getMetadataElement(\n    id: string,\n    createTime: api.Timestamp,\n    version = 1\n  ): BundleElement {\n    let totalDocuments = 0;\n    let totalBytes = 0;\n    for (const element of this.elements) {\n      if (element.documentMetadata && !element.documentMetadata.exists) {\n        totalDocuments += 1;\n      }\n      if (element.document) {\n        totalDocuments += 1;\n      }\n      totalBytes += encoder.encode(lengthPrefixedString(element)).byteLength;\n    }\n\n    return {\n      metadata: {\n        id,\n        createTime,\n        version,\n        totalDocuments,\n        totalBytes\n      }\n    };\n  }\n\n  build(id: string, createTime: api.Timestamp, version = 1): string {\n    let result = '';\n    for (const element of this.elements) {\n      result += lengthPrefixedString(element);\n    }\n    return (\n      lengthPrefixedString(this.getMetadataElement(id, createTime, version)) +\n      result\n    );\n  }\n}\n\n// TODO(wuandy): Ideally, these should use `TestBundleBuilder` above.\nexport const meta: BundleElement = {\n  metadata: {\n    id: 'test-bundle',\n    createTime: { seconds: 1577836805, nanos: 6 },\n    version: 1,\n    totalDocuments: 1,\n    totalBytes: 416\n  }\n};\nexport const metaString = lengthPrefixedString(meta);\n\nexport const doc1Meta: BundleElement = {\n  documentMetadata: {\n    name: 'projects/test-project/databases/(default)/documents/collectionId/doc1',\n    readTime: { seconds: 5, nanos: 6 },\n    exists: true\n  }\n};\nexport const doc1MetaString = lengthPrefixedString(doc1Meta);\nexport const doc1: BundleElement = {\n  document: {\n    name: 'projects/test-project/databases/(default)/documents/collectionId/doc1',\n    createTime: { seconds: 1, nanos: 2000000 },\n    updateTime: { seconds: 3, nanos: 4000 },\n    fields: { foo: { stringValue: 'value' }, bar: { integerValue: -42 } }\n  }\n};\nexport const doc1String = lengthPrefixedString(doc1);\n\nexport const doc2Meta: BundleElement = {\n  documentMetadata: {\n    name: 'projects/test-project/databases/(default)/documents/collectionId/doc2',\n    readTime: { seconds: 5, nanos: 6 },\n    exists: true\n  }\n};\nexport const doc2MetaString = lengthPrefixedString(doc2Meta);\nexport const doc2: BundleElement = {\n  document: {\n    name: 'projects/test-project/databases/(default)/documents/collectionId/doc2',\n    createTime: { seconds: 1, nanos: 2000000 },\n    updateTime: { seconds: 3, nanos: 4000 },\n    fields: {\n      foo: { stringValue: 'value1' },\n      bar: { integerValue: 42 },\n      emptyArray: { arrayValue: {} },\n      emptyMap: { mapValue: {} }\n    }\n  }\n};\nexport const doc2String = lengthPrefixedString(doc2);\n\nexport const noDocMeta: BundleElement = {\n  documentMetadata: {\n    name: 'projects/test-project/databases/(default)/documents/collectionId/nodoc',\n    readTime: { seconds: 5, nanos: 6 },\n    exists: false\n  }\n};\nexport const noDocMetaString = lengthPrefixedString(noDocMeta);\n\nexport const limitQuery: BundleElement = {\n  namedQuery: {\n    name: 'limitQuery',\n    bundledQuery: {\n      parent: 'projects/fireeats-97d5e/databases/(default)/documents',\n      structuredQuery: {\n        from: [{ collectionId: 'node_3.7.5_7Li7XoCjutvNxwD0tpo9' }],\n        orderBy: [{ field: { fieldPath: 'sort' }, direction: 'DESCENDING' }],\n        limit: { 'value': 1 }\n      },\n      limitType: 'FIRST'\n    },\n    readTime: { 'seconds': 1590011379, 'nanos': 191164000 }\n  }\n};\nexport const limitQueryString = lengthPrefixedString(limitQuery);\nexport const limitToLastQuery: BundleElement = {\n  namedQuery: {\n    name: 'limitToLastQuery',\n    bundledQuery: {\n      parent: 'projects/fireeats-97d5e/databases/(default)/documents',\n      structuredQuery: {\n        from: [{ collectionId: 'node_3.7.5_7Li7XoCjutvNxwD0tpo9' }],\n        orderBy: [{ field: { fieldPath: 'sort' }, direction: 'ASCENDING' }],\n        limit: { 'value': 1 }\n      },\n      limitType: 'LAST'\n    },\n    readTime: { 'seconds': 1590011379, 'nanos': 543063000 }\n  }\n};\nexport const limitToLastQueryString = lengthPrefixedString(limitToLastQuery);\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  JsonProtoSerializer,\n  fromTimestamp,\n  toName,\n  toQueryTarget,\n  toTimestamp\n} from '../../src/remote/serializer';\nimport { encoder } from '../../test/unit/util/bundle_data';\nimport { Firestore } from '../api/database';\nimport { DatabaseId } from '../core/database_info';\nimport { Query, queryToTarget } from '../core/query';\nimport { DocumentData } from '../lite-api/reference';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n  parseObject,\n  UserDataReader,\n  UserDataSource\n} from '../lite-api/user_data_reader';\nimport { DocumentKey } from '../model/document_key';\nimport {\n  BundledDocumentMetadata as ProtoBundledDocumentMetadata,\n  BundleElement as ProtoBundleElement,\n  BundleMetadata as ProtoBundleMetadata,\n  NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport {\n  Document as ProtoDocument,\n  Document\n} from '../protos/firestore_proto_api';\n\nconst BUNDLE_VERSION = 1;\n\n/**\n * Builds a Firestore data bundle with results from the given document and query snapshots.\n */\nexport class BundleBuilder {\n  // Resulting documents for the bundle, keyed by full document path.\n  private documents: Map<string, BundledDocument> = new Map();\n  // Named queries saved in the bundle, keyed by query name.\n  private namedQueries: Map<string, ProtoNamedQuery> = new Map();\n\n  // The latest read time among all bundled documents and queries.\n  private latestReadTime = new Timestamp(0, 0);\n\n  // Database identifier which is part of the serialized bundle.\n  private databaseId: DatabaseId;\n\n  // Tools to convert public data types into their serialized form.\n  private readonly serializer: JsonProtoSerializer;\n  private readonly userDataReader: UserDataReader;\n\n  constructor(private firestore: Firestore, readonly bundleId: string) {\n    this.databaseId = firestore._databaseId;\n\n    // useProto3Json is true because the objects will be serialized to JSON string\n    // before being written to the bundle buffer.\n    this.serializer = new JsonProtoSerializer(\n      this.databaseId,\n      /*useProto3Json=*/ true\n    );\n\n    this.userDataReader = new UserDataReader(\n      this.databaseId,\n      true,\n      this.serializer\n    );\n  }\n\n  /**\n   * Adds data from a DocumentSnapshot to the bundle.\n   * @internal\n   * @param docBundleData - A DocumentSnapshotBundleData containing information from the\n   * DocumentSnapshot. Note we cannot accept a DocumentSnapshot directly due to a circular\n   * dependency error.\n   * @param queryName - The name of the QuerySnapshot if this document is part of a Query.\n   */\n  addBundleDocument(\n    docBundleData: DocumentSnapshotBundleData,\n    queryName?: string\n  ): void {\n    const originalDocument = this.documents.get(docBundleData.documentPath);\n    const originalQueries = originalDocument?.metadata.queries;\n    const docReadTime: Timestamp | undefined = docBundleData.readTime;\n    const origDocReadTime: Timestamp | null = !!originalDocument?.metadata\n      .readTime\n      ? fromTimestamp(originalDocument.metadata.readTime)\n      : null;\n\n    const neitherHasReadTime: boolean = !docReadTime && origDocReadTime == null;\n    const docIsNewer: boolean =\n      docReadTime !== undefined &&\n      (origDocReadTime == null || origDocReadTime < docReadTime);\n    if (neitherHasReadTime || docIsNewer) {\n      // Store document.\n      this.documents.set(docBundleData.documentPath, {\n        document: this.toBundleDocument(docBundleData),\n        metadata: {\n          name: toName(this.serializer, docBundleData.documentKey),\n          readTime: !!docReadTime\n            ? toTimestamp(this.serializer, docReadTime) // Convert Timestamp to proto format.\n            : undefined,\n          exists: docBundleData.documentExists\n        }\n      });\n    }\n    if (docReadTime && docReadTime > this.latestReadTime) {\n      this.latestReadTime = docReadTime;\n    }\n    // Update `queries` to include both original and `queryName`.\n    if (queryName) {\n      const newDocument = this.documents.get(docBundleData.documentPath)!;\n      newDocument.metadata.queries = originalQueries || [];\n      newDocument.metadata.queries!.push(queryName);\n    }\n  }\n\n  /**\n   * Adds data from a QuerySnapshot to the bundle.\n   * @internal\n   * @param docBundleData - A QuerySnapshotBundleData containing information from the\n   * QuerySnapshot. Note we cannot accept a QuerySnapshot directly due to a circular\n   * dependency error.\n   */\n  addBundleQuery(queryBundleData: QuerySnapshotBundleData): void {\n    if (this.namedQueries.has(queryBundleData.name)) {\n      throw new Error(`Query name conflict: ${name} has already been added.`);\n    }\n    let latestReadTime = new Timestamp(0, 0);\n    for (const docBundleData of queryBundleData.docBundleDataArray) {\n      this.addBundleDocument(docBundleData, queryBundleData.name);\n      if (docBundleData.readTime && docBundleData.readTime > latestReadTime) {\n        latestReadTime = docBundleData.readTime;\n      }\n    }\n    const queryTarget = toQueryTarget(\n      this.serializer,\n      queryToTarget(queryBundleData.query)\n    );\n    const bundledQuery = {\n      parent: queryBundleData.parent,\n      structuredQuery: queryTarget.queryTarget.structuredQuery\n    };\n    this.namedQueries.set(queryBundleData.name, {\n      name: queryBundleData.name,\n      bundledQuery,\n      readTime: toTimestamp(this.serializer, latestReadTime)\n    });\n  }\n\n  /**\n   * Convert data from a DocumentSnapshot into the serialized form within a bundle.\n   * @private\n   * @internal\n   * @param docBundleData - a DocumentSnapshotBundleData containing the data required to\n   * serialize a document.\n   */\n  private toBundleDocument(\n    docBundleData: DocumentSnapshotBundleData\n  ): ProtoDocument {\n    // a parse context is typically used for validating and parsing user data, but in this\n    // case we are using it internally to convert DocumentData to Proto3 JSON\n    const context = this.userDataReader.createContext(\n      UserDataSource.ArrayArgument,\n      'internal toBundledDocument'\n    );\n    const proto3Fields = parseObject(docBundleData.documentData, context);\n\n    return {\n      name: toName(this.serializer, docBundleData.documentKey),\n      fields: proto3Fields.mapValue.fields,\n      updateTime: toTimestamp(this.serializer, docBundleData.versionTime),\n      createTime: toTimestamp(this.serializer, docBundleData.createdTime)\n    };\n  }\n\n  /**\n   * Converts a IBundleElement to a Buffer whose content is the length prefixed JSON representation\n   * of the element.\n   * @private\n   * @internal\n   * @param bundleElement - A ProtoBundleElement that is expected to be Proto3 JSON compatible.\n   */\n  private lengthPrefixedString(bundleElement: ProtoBundleElement): string {\n    const str = JSON.stringify(bundleElement);\n    // TODO: it's not ideal to have to re-encode all of these strings multiple times\n    //       It may be more performant to return a UInt8Array that is concatenated to other\n    //       UInt8Arrays instead of returning and concatenating strings and then\n    //       converting the full string to UInt8Array.\n    const l = encoder.encode(str).byteLength;\n    return `${l}${str}`;\n  }\n\n  /**\n   * Construct a serialized string containing document and query information that has previously\n   * been added to the BundleBuilder through the addBundleDocument and addBundleQuery methods.\n   * @internal\n   */\n  build(): string {\n    let bundleString = '';\n\n    for (const namedQuery of this.namedQueries.values()) {\n      bundleString += this.lengthPrefixedString({ namedQuery });\n    }\n\n    for (const bundledDocument of this.documents.values()) {\n      const documentMetadata: ProtoBundledDocumentMetadata =\n        bundledDocument.metadata;\n\n      bundleString += this.lengthPrefixedString({ documentMetadata });\n      // Write to the bundle if document exists.\n      const document = bundledDocument.document;\n      if (document) {\n        bundleString += this.lengthPrefixedString({ document });\n      }\n    }\n\n    const metadata: ProtoBundleMetadata = {\n      id: this.bundleId,\n      createTime: toTimestamp(this.serializer, this.latestReadTime),\n      version: BUNDLE_VERSION,\n      totalDocuments: this.documents.size,\n      // TODO: it's not ideal to have to re-encode all of these strings multiple times\n      totalBytes: encoder.encode(bundleString).length\n    };\n    // Prepends the metadata element to the bundleBuffer: `bundleBuffer` is the second argument to `Buffer.concat`.\n    bundleString = this.lengthPrefixedString({ metadata }) + bundleString;\n\n    return bundleString;\n  }\n}\n\n/**\n * Interface for an object that contains data required to bundle a DocumentSnapshot.\n * @internal\n */\nexport interface DocumentSnapshotBundleData {\n  documentData: DocumentData;\n  documentKey: DocumentKey;\n  documentPath: string;\n  documentExists: boolean;\n  createdTime: Timestamp;\n  readTime?: Timestamp;\n  versionTime: Timestamp;\n}\n\n/**\n * Interface for an object that contains data required to bundle a QuerySnapshot.\n * @internal\n */\nexport interface QuerySnapshotBundleData {\n  name: string;\n  query: Query;\n  parent: string;\n  docBundleDataArray: DocumentSnapshotBundleData[];\n}\n\n/**\n * Convenient class to hold both the metadata and the actual content of a document to be bundled.\n * @private\n * @internal\n */\nclass BundledDocument {\n  constructor(\n    readonly metadata: ProtoBundledDocumentMetadata,\n    readonly document?: Document\n  ) {}\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Return the Platform-specific build JSON bundle implementations. */\nimport { Firestore } from '../../api/database';\nimport { Query } from '../../core/query';\nimport { DocumentData } from '../../lite-api/reference';\nimport { Document } from '../../model/document';\nimport {\n  BundleBuilder,\n  DocumentSnapshotBundleData,\n  QuerySnapshotBundleData\n} from '../../util/bundle_builder_impl';\nimport { AutoId } from '../../util/misc';\n\nexport function buildDocumentSnapshotJsonBundle(\n  db: Firestore,\n  document: Document,\n  docData: DocumentData,\n  path: string\n): string {\n  const builder: BundleBuilder = new BundleBuilder(db, AutoId.newId());\n  builder.addBundleDocument(\n    documentToDocumentSnapshotBundleData(path, docData, document)\n  );\n  return builder.build();\n}\n\nexport function buildQuerySnapshotJsonBundle(\n  db: Firestore,\n  query: Query,\n  bundleName: string,\n  parent: string,\n  paths: string[],\n  docs: Document[],\n  documentData: DocumentData[]\n): string {\n  const docBundleDataArray: DocumentSnapshotBundleData[] = [];\n  for (let i = 0; i < docs.length; i++) {\n    docBundleDataArray.push(\n      documentToDocumentSnapshotBundleData(paths[i], documentData[i], docs[i])\n    );\n  }\n  const bundleData: QuerySnapshotBundleData = {\n    name: bundleName,\n    query,\n    parent,\n    docBundleDataArray\n  };\n  const builder: BundleBuilder = new BundleBuilder(db, bundleName);\n  builder.addBundleQuery(bundleData);\n  return builder.build();\n}\n\n// Formats Document data for bundling a DocumentSnapshot.\nfunction documentToDocumentSnapshotBundleData(\n  path: string,\n  documentData: DocumentData,\n  document: Document\n): DocumentSnapshotBundleData {\n  return {\n    documentData,\n    documentKey: document.mutableCopy().key,\n    documentPath: path,\n    documentExists: true,\n    createdTime: document.createTime.toTimestamp(),\n    readTime: document.readTime.toTimestamp(),\n    versionTime: document.version.toTimestamp()\n  };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleLoader } from '../core/bundle_impl';\nimport { createBundleReaderSync } from '../core/firestore_client';\nimport { newQueryComparator } from '../core/query';\nimport { ChangeType, ViewSnapshot } from '../core/view_snapshot';\nimport { FieldPath } from '../lite-api/field_path';\nimport {\n  DocumentData,\n  PartialWithFieldValue,\n  Query,\n  queryEqual,\n  SetOptions,\n  WithFieldValue\n} from '../lite-api/reference';\nimport { LiteUserDataWriter } from '../lite-api/reference_impl';\nimport {\n  DocumentSnapshot as LiteDocumentSnapshot,\n  FirestoreDataConverter as LiteFirestoreDataConverter\n} from '../lite-api/snapshot';\nimport {\n  fieldPathFromArgument,\n  UntypedFirestoreDataConverter\n} from '../lite-api/user_data_reader';\nimport { AbstractUserDataWriter } from '../lite-api/user_data_writer';\nimport { fromBundledQuery } from '../local/local_serializer';\nimport { documentKeySet } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { ResourcePath } from '../model/path';\nimport { newSerializer } from '../platform/serializer';\nimport {\n  buildQuerySnapshotJsonBundle,\n  buildDocumentSnapshotJsonBundle\n} from '../platform/snapshot_to_json';\nimport { fromDocument } from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { SnapshotListenOptions } from './reference_impl';\n\nconst NOT_SUPPORTED = 'NOT SUPPORTED';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n *     toFirestore(value: WithFieldValue<number>) {\n *         return { value };\n *     },\n *     fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n *         return snapshot.data(options).value as number;\n *     }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise<void> {\n *     const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n *     // converters are used with `setDoc`, `addDoc`, and `getDoc`\n *     await setDoc(documentRef, 42);\n *     const snapshot1 = await getDoc(documentRef);\n *     assertEqual(snapshot1.data(), 42);\n *\n *     // converters are not used when writing data with `updateDoc`\n *     await updateDoc(documentRef, { value: 999 });\n *     const snapshot2 = await getDoc(documentRef);\n *     assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n *     constructor(\n *         readonly title: string,\n *         readonly author: string,\n *         readonly lastUpdatedMillis: number\n *     ) {}\n *     toString(): string {\n *         return `${this.title} by ${this.author}`;\n *     }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n *     ttl: string;\n *     aut: { firstName: string; lastName: string };\n *     lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter<Post, PostDbModel> {\n *     toFirestore(post: WithFieldValue<Post>): WithFieldValue<PostDbModel> {\n *         return {\n *             ttl: post.title,\n *             aut: this._autFromAuthor(post.author),\n *             lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n *         };\n *     }\n *\n *     fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n *         const data = snapshot.data(options) as PostDbModel;\n *         const author = `${data.aut.firstName} ${data.aut.lastName}`;\n *         return new Post(data.ttl, author, data.lut.toMillis());\n *     }\n *\n *     _autFromAuthor(\n *         author: string | FieldValue\n *     ): { firstName: string; lastName: string } | FieldValue {\n *         if (typeof author !== 'string') {\n *             // `author` is a FieldValue, so just return it.\n *             return author;\n *         }\n *         const [firstName, lastName] = author.split(' ');\n *         return {firstName, lastName};\n *     }\n *\n *     _lutFromLastUpdatedMillis(\n *         lastUpdatedMillis: number | FieldValue\n *     ): Timestamp | FieldValue {\n *         if (typeof lastUpdatedMillis !== 'number') {\n *             // `lastUpdatedMillis` must be a FieldValue, so just return it.\n *             return lastUpdatedMillis;\n *         }\n *         return Timestamp.fromMillis(lastUpdatedMillis);\n *     }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise<void> {\n *     // Create a `DocumentReference` with a `FirestoreDataConverter`.\n *     const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n *     // The `data` argument specified to `setDoc()` is type checked by the\n *     // TypeScript compiler to be compatible with `Post`. Since the `data`\n *     // argument is typed as `WithFieldValue<Post>` rather than just `Post`,\n *     // this allows properties of the `data` argument to also be special\n *     // Firestore values that perform server-side mutations, such as\n *     // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n *     await setDoc(documentRef, {\n *         title: 'My Life',\n *         author: 'Foo Bar',\n *         lastUpdatedMillis: serverTimestamp()\n *     });\n *\n *     // The TypeScript compiler will fail to compile if the `data` argument to\n *     // `setDoc()` is _not_ compatible with `WithFieldValue<Post>`. This\n *     // type checking prevents the caller from specifying objects with incorrect\n *     // properties or property values.\n *     // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n *     // to parameter of type WithFieldValue<Post>\"\n *     await setDoc(documentRef, { ttl: 'The Title' });\n *\n *     // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n *     // object's `data()` method returns a `Post`, rather than a generic object,\n *     // which would have been returned if the `DocumentReference` did _not_ have a\n *     // `FirestoreDataConverter` attached to it.\n *     const snapshot1: DocumentSnapshot<Post> = await getDoc(documentRef);\n *     const post1: Post = snapshot1.data()!;\n *     if (post1) {\n *         assertEqual(post1.title, 'My Life');\n *         assertEqual(post1.author, 'Foo Bar');\n *     }\n *\n *     // The `data` argument specified to `updateDoc()` is type checked by the\n *     // TypeScript compiler to be compatible with `PostDbModel`. Note that\n *     // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n *     // the `data` argument to `updateDoc()` must be compatible with\n *     // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n *     // as `WithFieldValue<PostDbModel>` rather than just `PostDbModel`, this\n *     // allows properties of the `data` argument to also be those special\n *     // Firestore values, like `arrayRemove()`, `deleteField()`, and\n *     // `serverTimestamp()`.\n *     await updateDoc(documentRef, {\n *         'aut.firstName': 'NewFirstName',\n *         lut: serverTimestamp()\n *     });\n *\n *     // The TypeScript compiler will fail to compile if the `data` argument to\n *     // `updateDoc()` is _not_ compatible with `WithFieldValue<PostDbModel>`.\n *     // This type checking prevents the caller from specifying objects with\n *     // incorrect properties or property values.\n *     // @ts-expect-error \"Argument of type { title: string; } is not assignable\n *     // to parameter of type WithFieldValue<PostDbModel>\"\n *     await updateDoc(documentRef, { title: 'New Title' });\n *     const snapshot2: DocumentSnapshot<Post> = await getDoc(documentRef);\n *     const post2: Post = snapshot2.data()!;\n *     if (post2) {\n *         assertEqual(post2.title, 'My Life');\n *         assertEqual(post2.author, 'NewFirstName Bar');\n *     }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n  AppModelType,\n  DbModelType extends DocumentData = DocumentData\n> extends LiteFirestoreDataConverter<AppModelType, DbModelType> {\n  /**\n   * Called by the Firestore SDK to convert a custom model object of type\n   * `AppModelType` into a plain JavaScript object (suitable for writing\n   * directly to the Firestore database) of type `DbModelType`. To use `set()`\n   * with `merge` and `mergeFields`, `toFirestore()` must be defined with\n   * `PartialWithFieldValue<AppModelType>`.\n   *\n   * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as\n   * {@link (deleteField:1)} to be used as property values.\n   */\n  toFirestore(\n    modelObject: WithFieldValue<AppModelType>\n  ): WithFieldValue<DbModelType>;\n\n  /**\n   * Called by the Firestore SDK to convert a custom model object of type\n   * `AppModelType` into a plain JavaScript object (suitable for writing\n   * directly to the Firestore database) of type `DbModelType`. Used with\n   * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and\n   * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`.\n   *\n   * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow\n   * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n   * It also supports nested `Partial` by allowing nested fields to be\n   * omitted.\n   */\n  toFirestore(\n    modelObject: PartialWithFieldValue<AppModelType>,\n    options: SetOptions\n  ): PartialWithFieldValue<DbModelType>;\n\n  /**\n   * Called by the Firestore SDK to convert Firestore data into an object of\n   * type `AppModelType`. You can access your data by calling:\n   * `snapshot.data(options)`.\n   *\n   * Generally, the data returned from `snapshot.data()` can be cast to\n   * `DbModelType`; however, this is not guaranteed because Firestore does not\n   * enforce a schema on the database. For example, writes from a previous\n   * version of the application or writes from another client that did not use a\n   * type converter could have written data with different properties and/or\n   * property types. The implementation will need to choose whether to\n   * gracefully recover from non-conforming data or throw an error.\n   *\n   * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}.\n   *\n   * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata.\n   * @param options - The `SnapshotOptions` from the initial call to `data()`.\n   */\n  fromFirestore(\n    snapshot: QueryDocumentSnapshot<DocumentData, DocumentData>,\n    options?: SnapshotOptions\n  ): AppModelType;\n}\n\n/**\n * Options that configure how data is retrieved from a `DocumentSnapshot` (for\n * example the desired behavior for server timestamps that have not yet been set\n * to their final value).\n */\nexport interface SnapshotOptions {\n  /**\n   * If set, controls the return value for server timestamps that have not yet\n   * been set to their final value.\n   *\n   * By specifying 'estimate', pending server timestamps return an estimate\n   * based on the local clock. This estimate will differ from the final value\n   * and cause these values to change once the server result becomes available.\n   *\n   * By specifying 'previous', pending timestamps will be ignored and return\n   * their previous value instead.\n   *\n   * If omitted or set to 'none', `null` will be returned by default until the\n   * server value becomes available.\n   */\n  readonly serverTimestamps?: 'estimate' | 'previous' | 'none';\n}\n\n/**\n * Metadata about a snapshot, describing the state of the snapshot.\n */\nexport class SnapshotMetadata {\n  /**\n   * True if the snapshot contains the result of local writes (for example\n   * `set()` or `update()` calls) that have not yet been committed to the\n   * backend. If your listener has opted into metadata updates (via\n   * `SnapshotListenOptions`) you will receive another snapshot with\n   * `hasPendingWrites` equal to false once the writes have been committed to\n   * the backend.\n   */\n  readonly hasPendingWrites: boolean;\n\n  /**\n   * True if the snapshot was created from cached data rather than guaranteed\n   * up-to-date server data. If your listener has opted into metadata updates\n   * (via `SnapshotListenOptions`) you will receive another snapshot with\n   * `fromCache` set to false once the client has received up-to-date data from\n   * the backend.\n   */\n  readonly fromCache: boolean;\n\n  /** @hideconstructor */\n  constructor(hasPendingWrites: boolean, fromCache: boolean) {\n    this.hasPendingWrites = hasPendingWrites;\n    this.fromCache = fromCache;\n  }\n\n  /**\n   * Returns true if this `SnapshotMetadata` is equal to the provided one.\n   *\n   * @param other - The `SnapshotMetadata` to compare against.\n   * @returns true if this `SnapshotMetadata` is equal to the provided one.\n   */\n  isEqual(other: SnapshotMetadata): boolean {\n    return (\n      this.hasPendingWrites === other.hasPendingWrites &&\n      this.fromCache === other.fromCache\n    );\n  }\n}\n\n/**\n * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'.\n */\nexport type DocumentChangeType = 'added' | 'removed' | 'modified';\n\n/**\n * A `DocumentChange` represents a change to the documents matching a query.\n * It contains the document affected and the type of change that occurred.\n */\nexport interface DocumentChange<\n  AppModelType = DocumentData,\n  DbModelType extends DocumentData = DocumentData\n> {\n  /** The type of change ('added', 'modified', or 'removed'). */\n  readonly type: DocumentChangeType;\n\n  /** The document affected by this change. */\n  readonly doc: QueryDocumentSnapshot<AppModelType, DbModelType>;\n\n  /**\n   * The index of the changed document in the result set immediately prior to\n   * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects\n   * have been applied). Is `-1` for 'added' events.\n   */\n  readonly oldIndex: number;\n\n  /**\n   * The index of the changed document in the result set immediately after\n   * this `DocumentChange` (i.e. supposing that all prior `DocumentChange`\n   * objects and the current `DocumentChange` object have been applied).\n   * Is -1 for 'removed' events.\n   */\n  readonly newIndex: number;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get(<field>)` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n  AppModelType = DocumentData,\n  DbModelType extends DocumentData = DocumentData\n> extends LiteDocumentSnapshot<AppModelType, DbModelType> {\n  private readonly _firestoreImpl: Firestore;\n\n  /**\n   *  Metadata about the `DocumentSnapshot`, including information about its\n   *  source and local modifications.\n   */\n  readonly metadata: SnapshotMetadata;\n\n  /** @hideconstructor protected */\n  constructor(\n    readonly _firestore: Firestore,\n    userDataWriter: AbstractUserDataWriter,\n    key: DocumentKey,\n    document: Document | null,\n    metadata: SnapshotMetadata,\n    converter: UntypedFirestoreDataConverter<AppModelType, DbModelType> | null\n  ) {\n    super(_firestore, userDataWriter, key, document, converter);\n    this._firestoreImpl = _firestore;\n    this.metadata = metadata;\n  }\n\n  /**\n   * Returns whether or not the data exists. True if the document exists.\n   */\n  exists(): this is QueryDocumentSnapshot<AppModelType, DbModelType> {\n    return super.exists();\n  }\n\n  /**\n   * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n   * the document doesn't exist.\n   *\n   * By default, `serverTimestamp()` values that have not yet been\n   * set to their final value will be returned as `null`. You can override\n   * this by passing an options object.\n   *\n   * @param options - An options object to configure how data is retrieved from\n   * the snapshot (for example the desired behavior for server timestamps that\n   * have not yet been set to their final value).\n   * @returns An `Object` containing all fields in the document or `undefined` if\n   * the document doesn't exist.\n   */\n  data(options: SnapshotOptions = {}): AppModelType | undefined {\n    if (!this._document) {\n      return undefined;\n    } else if (this._converter) {\n      // We only want to use the converter and create a new DocumentSnapshot\n      // if a converter has been provided.\n      const snapshot = new QueryDocumentSnapshot(\n        this._firestore,\n        this._userDataWriter,\n        this._key,\n        this._document,\n        this.metadata,\n        /* converter= */ null\n      );\n      return this._converter.fromFirestore(snapshot, options);\n    } else {\n      return this._userDataWriter.convertValue(\n        this._document.data.value,\n        options.serverTimestamps\n      ) as AppModelType;\n    }\n  }\n\n  /**\n   * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n   * document or field doesn't exist.\n   *\n   * By default, a `serverTimestamp()` that has not yet been set to\n   * its final value will be returned as `null`. You can override this by\n   * passing an options object.\n   *\n   * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n   * field.\n   * @param options - An options object to configure how the field is retrieved\n   * from the snapshot (for example the desired behavior for server timestamps\n   * that have not yet been set to their final value).\n   * @returns The data at the specified field location or undefined if no such\n   * field exists in the document.\n   */\n  // We are using `any` here to avoid an explicit cast by our users.\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  get(fieldPath: string | FieldPath, options: SnapshotOptions = {}): any {\n    if (this._document) {\n      const value = this._document.data.field(\n        fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n      );\n      if (value !== null) {\n        return this._userDataWriter.convertValue(\n          value,\n          options.serverTimestamps\n        );\n      }\n    }\n    return undefined;\n  }\n\n  static _jsonSchemaVersion: string = 'firestore/documentSnapshot/1.0';\n  static _jsonSchema = {\n    type: property('string', DocumentSnapshot._jsonSchemaVersion),\n    bundleSource: property('string', 'DocumentSnapshot'),\n    bundleName: property('string'),\n    bundle: property('string')\n  };\n\n  /**\n   * Returns a JSON-serializable representation of this `DocumentSnapshot` instance.\n   *\n   * @returns a JSON representation of this object.  Throws a {@link FirestoreError} if this\n   * `DocumentSnapshot` has pending writes.\n   */\n  toJSON(): object {\n    if (this.metadata.hasPendingWrites) {\n      throw new FirestoreError(\n        Code.FAILED_PRECONDITION,\n        'DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. ' +\n          'Await waitForPendingWrites() before invoking toJSON().'\n      );\n    }\n    const document = this._document;\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    const result: any = {};\n    result['type'] = DocumentSnapshot._jsonSchemaVersion;\n    result['bundle'] = '';\n    result['bundleSource'] = 'DocumentSnapshot';\n    result['bundleName'] = this._key.toString();\n\n    if (\n      !document ||\n      !document.isValidDocument() ||\n      !document.isFoundDocument()\n    ) {\n      return result;\n    }\n    const documentData = this._userDataWriter.convertObjectMap(\n      document.data.value.mapValue.fields,\n      'previous'\n    );\n    result['bundle'] = buildDocumentSnapshotJsonBundle(\n      this._firestore,\n      document,\n      documentData,\n      this.ref.path\n    );\n    return result;\n  }\n}\n\n/**\n * Builds a `DocumentSnapshot` instance from a JSON object created by\n * {@link DocumentSnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `DocumentSnapshot` instance.\n * @returns an instance of {@link DocumentSnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function documentSnapshotFromJSON(\n  db: Firestore,\n  json: object\n): DocumentSnapshot;\n/**\n * Builds a `DocumentSnapshot` instance from a JSON object created by\n * {@link DocumentSnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `DocumentSnapshot` instance.\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentSnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function documentSnapshotFromJSON<\n  AppModelType,\n  DbModelType extends DocumentData = DocumentData\n>(\n  db: Firestore,\n  json: object,\n  converter: FirestoreDataConverter<AppModelType, DbModelType>\n): DocumentSnapshot<AppModelType, DbModelType>;\nexport function documentSnapshotFromJSON<\n  AppModelType,\n  DbModelType extends DocumentData = DocumentData\n>(\n  db: Firestore,\n  json: object,\n  converter?: FirestoreDataConverter<AppModelType, DbModelType>\n): DocumentSnapshot<AppModelType, DbModelType> {\n  if (validateJSON(json, DocumentSnapshot._jsonSchema)) {\n    if (json.bundle === NOT_SUPPORTED) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'The provided JSON object was created in a client environment, which is not supported.'\n      );\n    }\n    // Parse the bundle data.\n    const serializer = newSerializer(db._databaseId);\n    const bundleReader = createBundleReaderSync(json.bundle, serializer);\n    const elements = bundleReader.getElements();\n    const bundleLoader: BundleLoader = new BundleLoader(\n      bundleReader.getMetadata(),\n      serializer\n    );\n    for (const element of elements) {\n      bundleLoader.addSizedElement(element);\n    }\n\n    // Ensure that we have the correct number of documents in the bundle.\n    const bundledDocuments = bundleLoader.documents;\n    if (bundledDocuments.length !== 1) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        `Expected bundle data to contain 1 document, but it contains ${bundledDocuments.length} documents.`\n      );\n    }\n\n    // Build out the internal document data.\n    const document = fromDocument(serializer, bundledDocuments[0].document!);\n    const documentKey = new DocumentKey(\n      ResourcePath.fromString(json.bundleName)\n    );\n\n    // Return the external facing DocumentSnapshot.\n    return new DocumentSnapshot(\n      db,\n      new LiteUserDataWriter(db),\n      documentKey,\n      document,\n      new SnapshotMetadata(\n        /* hasPendingWrites= */ false,\n        /* fromCache= */ false\n      ),\n      converter ? converter : null\n    );\n  }\n  throw new FirestoreError(\n    Code.INTERNAL,\n    'Unexpected error creating DocumentSnapshot from JSON.'\n  );\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get(<field>)` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n  AppModelType = DocumentData,\n  DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot<AppModelType, DbModelType> {\n  /**\n   * Retrieves all fields in the document as an `Object`.\n   *\n   * By default, `serverTimestamp()` values that have not yet been\n   * set to their final value will be returned as `null`. You can override\n   * this by passing an options object.\n   *\n   * @override\n   * @param options - An options object to configure how data is retrieved from\n   * the snapshot (for example the desired behavior for server timestamps that\n   * have not yet been set to their final value).\n   * @returns An `Object` containing all fields in the document.\n   */\n  data(options: SnapshotOptions = {}): AppModelType {\n    return super.data(options) as AppModelType;\n  }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n  AppModelType = DocumentData,\n  DbModelType extends DocumentData = DocumentData\n> {\n  /**\n   * Metadata about this snapshot, concerning its source and if it has local\n   * modifications.\n   */\n  readonly metadata: SnapshotMetadata;\n\n  /**\n   * The query on which you called `get` or `onSnapshot` in order to get this\n   * `QuerySnapshot`.\n   */\n  readonly query: Query<AppModelType, DbModelType>;\n\n  private _cachedChanges?: Array<DocumentChange<AppModelType, DbModelType>>;\n  private _cachedChangesIncludeMetadataChanges?: boolean;\n\n  /** @hideconstructor */\n  constructor(\n    readonly _firestore: Firestore,\n    readonly _userDataWriter: AbstractUserDataWriter,\n    query: Query<AppModelType, DbModelType>,\n    readonly _snapshot: ViewSnapshot\n  ) {\n    this.metadata = new SnapshotMetadata(\n      _snapshot.hasPendingWrites,\n      _snapshot.fromCache\n    );\n    this.query = query;\n  }\n\n  /** An array of all the documents in the `QuerySnapshot`. */\n  get docs(): Array<QueryDocumentSnapshot<AppModelType, DbModelType>> {\n    const result: Array<QueryDocumentSnapshot<AppModelType, DbModelType>> = [];\n    this.forEach(doc => result.push(doc));\n    return result;\n  }\n\n  /** The number of documents in the `QuerySnapshot`. */\n  get size(): number {\n    return this._snapshot.docs.size;\n  }\n\n  /** True if there are no documents in the `QuerySnapshot`. */\n  get empty(): boolean {\n    return this.size === 0;\n  }\n\n  /**\n   * Enumerates all of the documents in the `QuerySnapshot`.\n   *\n   * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n   * each document in the snapshot.\n   * @param thisArg - The `this` binding for the callback.\n   */\n  forEach(\n    callback: (\n      result: QueryDocumentSnapshot<AppModelType, DbModelType>\n    ) => void,\n    thisArg?: unknown\n  ): void {\n    this._snapshot.docs.forEach(doc => {\n      callback.call(\n        thisArg,\n        new QueryDocumentSnapshot<AppModelType, DbModelType>(\n          this._firestore,\n          this._userDataWriter,\n          doc.key,\n          doc,\n          new SnapshotMetadata(\n            this._snapshot.mutatedKeys.has(doc.key),\n            this._snapshot.fromCache\n          ),\n          this.query.converter\n        )\n      );\n    });\n  }\n\n  /**\n   * Returns an array of the documents changes since the last snapshot. If this\n   * is the first snapshot, all documents will be in the list as 'added'\n   * changes.\n   *\n   * @param options - `SnapshotListenOptions` that control whether metadata-only\n   * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger\n   * snapshot events.\n   */\n  docChanges(\n    options: SnapshotListenOptions = {}\n  ): Array<DocumentChange<AppModelType, DbModelType>> {\n    const includeMetadataChanges = !!options.includeMetadataChanges;\n\n    if (includeMetadataChanges && this._snapshot.excludesMetadataChanges) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'To include metadata changes with your document changes, you must ' +\n          'also pass { includeMetadataChanges:true } to onSnapshot().'\n      );\n    }\n\n    if (\n      !this._cachedChanges ||\n      this._cachedChangesIncludeMetadataChanges !== includeMetadataChanges\n    ) {\n      this._cachedChanges = changesFromSnapshot(this, includeMetadataChanges);\n      this._cachedChangesIncludeMetadataChanges = includeMetadataChanges;\n    }\n\n    return this._cachedChanges;\n  }\n\n  static _jsonSchemaVersion: string = 'firestore/querySnapshot/1.0';\n  static _jsonSchema = {\n    type: property('string', QuerySnapshot._jsonSchemaVersion),\n    bundleSource: property('string', 'QuerySnapshot'),\n    bundleName: property('string'),\n    bundle: property('string')\n  };\n\n  /**\n   * Returns a JSON-serializable representation of this `QuerySnapshot` instance.\n   *\n   * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this\n   * `QuerySnapshot` has pending writes.\n   */\n  toJSON(): object {\n    if (this.metadata.hasPendingWrites) {\n      throw new FirestoreError(\n        Code.FAILED_PRECONDITION,\n        'QuerySnapshot.toJSON() attempted to serialize a document with pending writes. ' +\n          'Await waitForPendingWrites() before invoking toJSON().'\n      );\n    }\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    const result: any = {};\n    result['type'] = QuerySnapshot._jsonSchemaVersion;\n    result['bundleSource'] = 'QuerySnapshot';\n    result['bundleName'] = AutoId.newId();\n\n    const databaseId = this._firestore._databaseId.database;\n    const projectId = this._firestore._databaseId.projectId;\n    const parent = `projects/${projectId}/databases/${databaseId}/documents`;\n    const documents: Document[] = [];\n    const documentData: DocumentData[] = [];\n    const paths: string[] = [];\n\n    this.docs.forEach(doc => {\n      if (doc._document === null) {\n        return;\n      }\n      documents.push(doc._document);\n      documentData.push(\n        this._userDataWriter.convertObjectMap(\n          doc._document.data.value.mapValue.fields,\n          'previous'\n        )\n      );\n      paths.push(doc.ref.path);\n    });\n    result['bundle'] = buildQuerySnapshotJsonBundle(\n      this._firestore,\n      this.query._query,\n      result['bundleName'],\n      parent,\n      paths,\n      documents,\n      documentData\n    );\n    return result;\n  }\n}\n\n/**\n * Builds a `QuerySnapshot` instance from a JSON object created by\n * {@link QuerySnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `QuerySnapshot` instance.\n * @returns an instance of {@link QuerySnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function querySnapshotFromJSON(\n  db: Firestore,\n  json: object\n): QuerySnapshot;\n/**\n * Builds a `QuerySnapshot` instance from a JSON object created by\n * {@link QuerySnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `QuerySnapshot` instance.\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link QuerySnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function querySnapshotFromJSON<\n  AppModelType,\n  DbModelType extends DocumentData = DocumentData\n>(\n  db: Firestore,\n  json: object,\n  converter: FirestoreDataConverter<AppModelType, DbModelType>\n): QuerySnapshot<AppModelType, DbModelType>;\nexport function querySnapshotFromJSON<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  db: Firestore,\n  json: object,\n  converter?: FirestoreDataConverter<AppModelType, DbModelType>\n): QuerySnapshot<AppModelType, DbModelType> {\n  if (validateJSON(json, QuerySnapshot._jsonSchema)) {\n    if (json.bundle === NOT_SUPPORTED) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'The provided JSON object was created in a client environment, which is not supported.'\n      );\n    }\n    // Parse the bundle data.\n    const serializer = newSerializer(db._databaseId);\n    const bundleReader = createBundleReaderSync(json.bundle, serializer);\n    const elements = bundleReader.getElements();\n    const bundleLoader: BundleLoader = new BundleLoader(\n      bundleReader.getMetadata(),\n      serializer\n    );\n    for (const element of elements) {\n      bundleLoader.addSizedElement(element);\n    }\n\n    if (bundleLoader.queries.length !== 1) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        `Snapshot data expected 1 query but found ${bundleLoader.queries.length} queries.`\n      );\n    }\n\n    // Create an internal Query object from the named query in the bundle.\n    const query = fromBundledQuery(bundleLoader.queries[0].bundledQuery!);\n\n    // Construct the arrays of document data for the query.\n    const bundledDocuments = bundleLoader.documents;\n    let documentSet = new DocumentSet();\n    bundledDocuments.map(bundledDocument => {\n      const document = fromDocument(serializer, bundledDocument.document!);\n      documentSet = documentSet.add(document);\n    });\n    // Create a view snapshot of the query and documents.\n    const viewSnapshot = ViewSnapshot.fromInitialDocuments(\n      query,\n      documentSet,\n      documentKeySet() /* Zero mutated keys signifies no pending writes. */,\n      /* fromCache= */ false,\n      /* hasCachedResults= */ false\n    );\n\n    // Create an external Query object, required to construct the QuerySnapshot.\n    const externalQuery = new Query<AppModelType, DbModelType>(\n      db,\n      converter ? converter : null,\n      query\n    );\n\n    // Return a new QuerySnapshot with all of the collected data.\n    return new QuerySnapshot<AppModelType, DbModelType>(\n      db,\n      new LiteUserDataWriter(db),\n      externalQuery,\n      viewSnapshot\n    );\n  }\n  throw new FirestoreError(\n    Code.INTERNAL,\n    'Unexpected error creating QuerySnapshot from JSON.'\n  );\n}\n\n/** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */\nexport function changesFromSnapshot<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  querySnapshot: QuerySnapshot<AppModelType, DbModelType>,\n  includeMetadataChanges: boolean\n): Array<DocumentChange<AppModelType, DbModelType>> {\n  if (querySnapshot._snapshot.oldDocs.isEmpty()) {\n    // Special case the first snapshot because index calculation is easy and\n    // fast\n    let lastDoc: Document;\n    let index = 0;\n    return querySnapshot._snapshot.docChanges.map(change => {\n      debugAssert(\n        change.type === ChangeType.Added,\n        'Invalid event type for first snapshot'\n      );\n      debugAssert(\n        !lastDoc ||\n          newQueryComparator(querySnapshot._snapshot.query)(\n            lastDoc,\n            change.doc\n          ) < 0,\n        'Got added events in wrong order'\n      );\n      const doc = new QueryDocumentSnapshot<AppModelType, DbModelType>(\n        querySnapshot._firestore,\n        querySnapshot._userDataWriter,\n        change.doc.key,\n        change.doc,\n        new SnapshotMetadata(\n          querySnapshot._snapshot.mutatedKeys.has(change.doc.key),\n          querySnapshot._snapshot.fromCache\n        ),\n        querySnapshot.query.converter\n      );\n      lastDoc = change.doc;\n      return {\n        type: 'added' as DocumentChangeType,\n        doc,\n        oldIndex: -1,\n        newIndex: index++\n      };\n    });\n  } else {\n    // A `DocumentSet` that is updated incrementally as changes are applied to use\n    // to lookup the index of a document.\n    let indexTracker = querySnapshot._snapshot.oldDocs;\n    return querySnapshot._snapshot.docChanges\n      .filter(\n        change => includeMetadataChanges || change.type !== ChangeType.Metadata\n      )\n      .map(change => {\n        const doc = new QueryDocumentSnapshot<AppModelType, DbModelType>(\n          querySnapshot._firestore,\n          querySnapshot._userDataWriter,\n          change.doc.key,\n          change.doc,\n          new SnapshotMetadata(\n            querySnapshot._snapshot.mutatedKeys.has(change.doc.key),\n            querySnapshot._snapshot.fromCache\n          ),\n          querySnapshot.query.converter\n        );\n        let oldIndex = -1;\n        let newIndex = -1;\n        if (change.type !== ChangeType.Added) {\n          oldIndex = indexTracker.indexOf(change.doc.key);\n          debugAssert(oldIndex >= 0, 'Index for document not found');\n          indexTracker = indexTracker.delete(change.doc.key);\n        }\n        if (change.type !== ChangeType.Removed) {\n          indexTracker = indexTracker.add(change.doc);\n          newIndex = indexTracker.indexOf(change.doc.key);\n        }\n        return {\n          type: resultChangeType(change.type),\n          doc,\n          oldIndex,\n          newIndex\n        };\n      });\n  }\n}\n\nexport function resultChangeType(type: ChangeType): DocumentChangeType {\n  switch (type) {\n    case ChangeType.Added:\n      return 'added';\n    case ChangeType.Modified:\n    case ChangeType.Metadata:\n      return 'modified';\n    case ChangeType.Removed:\n      return 'removed';\n    default:\n      return fail(0xf03d, 'Unknown change type', { type });\n  }\n}\n\n// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot\n// metadata\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual<AppModelType, DbModelType extends DocumentData>(\n  left:\n    | DocumentSnapshot<AppModelType, DbModelType>\n    | QuerySnapshot<AppModelType, DbModelType>,\n  right:\n    | DocumentSnapshot<AppModelType, DbModelType>\n    | QuerySnapshot<AppModelType, DbModelType>\n): boolean {\n  if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n    return (\n      left._firestore === right._firestore &&\n      left._key.isEqual(right._key) &&\n      (left._document === null\n        ? right._document === null\n        : left._document.isEqual(right._document)) &&\n      left._converter === right._converter\n    );\n  } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n    return (\n      left._firestore === right._firestore &&\n      queryEqual(left.query, right.query) &&\n      left.metadata.isEqual(right.metadata) &&\n      left._snapshot.isEqual(right._snapshot)\n    );\n  }\n\n  return false;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n  maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n  /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n  readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n  if (options.maxAttempts < 1) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'Max attempts must be at least 1'\n    );\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n  DocumentData,\n  DocumentReference,\n  PartialWithFieldValue,\n  SetOptions,\n  UpdateData,\n  WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n  newUserDataReader,\n  parseSetData,\n  parseUpdateData,\n  parseUpdateVarargs,\n  UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n  // This is the lite version of the WriteBatch API used in the legacy SDK. The\n  // class is a close copy but takes different input types.\n\n  private readonly _dataReader: UserDataReader;\n  private _mutations = [] as Mutation[];\n  private _committed = false;\n\n  /** @hideconstructor */\n  constructor(\n    private readonly _firestore: Firestore,\n    private readonly _commitHandler: (m: Mutation[]) => Promise<void>\n  ) {\n    this._dataReader = newUserDataReader(_firestore);\n  }\n\n  /**\n   * Writes to the document referred to by the provided {@link\n   * DocumentReference}. If the document does not exist yet, it will be created.\n   *\n   * @param documentRef - A reference to the document to be set.\n   * @param data - An object of the fields and values for the document.\n   * @returns This `WriteBatch` instance. Used for chaining method calls.\n   */\n  set<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>,\n    data: WithFieldValue<AppModelType>\n  ): WriteBatch;\n  /**\n   * Writes to the document referred to by the provided {@link\n   * DocumentReference}. If the document does not exist yet, it will be created.\n   * If you provide `merge` or `mergeFields`, the provided data can be merged\n   * into an existing document.\n   *\n   * @param documentRef - A reference to the document to be set.\n   * @param data - An object of the fields and values for the document.\n   * @param options - An object to configure the set behavior.\n   * @throws Error - If the provided input is not a valid Firestore document.\n   * @returns This `WriteBatch` instance. Used for chaining method calls.\n   */\n  set<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>,\n    data: PartialWithFieldValue<AppModelType>,\n    options: SetOptions\n  ): WriteBatch;\n  set<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>,\n    data: WithFieldValue<AppModelType> | PartialWithFieldValue<AppModelType>,\n    options?: SetOptions\n  ): WriteBatch {\n    this._verifyNotCommitted();\n    const ref = validateReference(documentRef, this._firestore);\n\n    const convertedValue = applyFirestoreDataConverter(\n      ref.converter,\n      data,\n      options\n    );\n    const parsed = parseSetData(\n      this._dataReader,\n      'WriteBatch.set',\n      ref._key,\n      convertedValue,\n      ref.converter !== null,\n      options\n    );\n    this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n    return this;\n  }\n\n  /**\n   * Updates fields in the document referred to by the provided {@link\n   * DocumentReference}. The update will fail if applied to a document that does\n   * not exist.\n   *\n   * @param documentRef - A reference to the document to be updated.\n   * @param data - An object containing the fields and values with which to\n   * update the document. Fields can contain dots to reference nested fields\n   * within the document.\n   * @throws Error - If the provided input is not valid Firestore data.\n   * @returns This `WriteBatch` instance. Used for chaining method calls.\n   */\n  update<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>,\n    data: UpdateData<DbModelType>\n  ): WriteBatch;\n  /**\n   * Updates fields in the document referred to by this {@link\n   * DocumentReference}. The update will fail if applied to a document that does\n   * not exist.\n   *\n   * Nested fields can be update by providing dot-separated field path strings\n   * or by providing `FieldPath` objects.\n   *\n   * @param documentRef - A reference to the document to be updated.\n   * @param field - The first field to update.\n   * @param value - The first value.\n   * @param moreFieldsAndValues - Additional key value pairs.\n   * @throws Error - If the provided input is not valid Firestore data.\n   * @returns This `WriteBatch` instance. Used for chaining method calls.\n   */\n  update<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>,\n    field: string | FieldPath,\n    value: unknown,\n    ...moreFieldsAndValues: unknown[]\n  ): WriteBatch;\n  update<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>,\n    fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n    value?: unknown,\n    ...moreFieldsAndValues: unknown[]\n  ): WriteBatch {\n    this._verifyNotCommitted();\n    const ref = validateReference(documentRef, this._firestore);\n\n    // For Compat types, we have to \"extract\" the underlying types before\n    // performing validation.\n    fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n    let parsed;\n    if (\n      typeof fieldOrUpdateData === 'string' ||\n      fieldOrUpdateData instanceof FieldPath\n    ) {\n      parsed = parseUpdateVarargs(\n        this._dataReader,\n        'WriteBatch.update',\n        ref._key,\n        fieldOrUpdateData,\n        value,\n        moreFieldsAndValues\n      );\n    } else {\n      parsed = parseUpdateData(\n        this._dataReader,\n        'WriteBatch.update',\n        ref._key,\n        fieldOrUpdateData\n      );\n    }\n\n    this._mutations.push(\n      parsed.toMutation(ref._key, Precondition.exists(true))\n    );\n    return this;\n  }\n\n  /**\n   * Deletes the document referred to by the provided {@link DocumentReference}.\n   *\n   * @param documentRef - A reference to the document to be deleted.\n   * @returns This `WriteBatch` instance. Used for chaining method calls.\n   */\n  delete<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>\n  ): WriteBatch {\n    this._verifyNotCommitted();\n    const ref = validateReference(documentRef, this._firestore);\n    this._mutations = this._mutations.concat(\n      new DeleteMutation(ref._key, Precondition.none())\n    );\n    return this;\n  }\n\n  /**\n   * Commits all of the writes in this write batch as a single atomic unit.\n   *\n   * The result of these writes will only be reflected in document reads that\n   * occur after the returned promise resolves. If the client is offline, the\n   * write fails. If you would like to see local modifications or buffer writes\n   * until the client is online, use the full Firestore SDK.\n   *\n   * @returns A `Promise` resolved once all of the writes in the batch have been\n   * successfully written to the backend as an atomic unit (note that it won't\n   * resolve while you're offline).\n   */\n  commit(): Promise<void> {\n    this._verifyNotCommitted();\n    this._committed = true;\n    if (this._mutations.length > 0) {\n      return this._commitHandler(this._mutations);\n    }\n\n    return Promise.resolve();\n  }\n\n  private _verifyNotCommitted(): void {\n    if (this._committed) {\n      throw new FirestoreError(\n        Code.FAILED_PRECONDITION,\n        'A write batch can no longer be used after commit() ' +\n          'has been called.'\n      );\n    }\n  }\n}\n\nexport function validateReference<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  documentRef:\n    | DocumentReference<AppModelType, DbModelType>\n    | Compat<DocumentReference<AppModelType, DbModelType>>,\n  firestore: Firestore\n): DocumentReference<AppModelType, DbModelType> {\n  documentRef = getModularInstance(documentRef);\n\n  if (documentRef.firestore !== firestore) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'Provided document reference is from a different Firestore instance.'\n    );\n  } else {\n    return documentRef as DocumentReference<AppModelType, DbModelType>;\n  }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n  firestore = cast(firestore, Firestore);\n  const datastore = getDatastore(firestore);\n  return new WriteBatch(firestore, writes =>\n    invokeCommitRpc(datastore, writes)\n  );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n  DEFAULT_TRANSACTION_OPTIONS,\n  TransactionOptions as TransactionOptionsInternal,\n  validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n  DocumentData,\n  DocumentReference,\n  PartialWithFieldValue,\n  SetOptions,\n  UpdateData,\n  WithFieldValue\n} from './reference';\nimport {\n  applyFirestoreDataConverter,\n  LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n  newUserDataReader,\n  parseSetData,\n  parseUpdateData,\n  parseUpdateVarargs,\n  UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n  // This is the tree-shakeable version of the Transaction class used in the\n  // legacy SDK. The class is a close copy but takes different input and output\n  // types. The firestore-exp SDK further extends this class to return its API\n  // type.\n\n  private readonly _dataReader: UserDataReader;\n\n  /** @hideconstructor */\n  constructor(\n    protected readonly _firestore: Firestore,\n    private readonly _transaction: InternalTransaction\n  ) {\n    this._dataReader = newUserDataReader(_firestore);\n  }\n\n  /**\n   * Reads the document referenced by the provided {@link DocumentReference}.\n   *\n   * @param documentRef - A reference to the document to be read.\n   * @returns A `DocumentSnapshot` with the read data.\n   */\n  get<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>\n  ): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n    const ref = validateReference(documentRef, this._firestore);\n    const userDataWriter = new LiteUserDataWriter(this._firestore);\n    return this._transaction.lookup([ref._key]).then(docs => {\n      if (!docs || docs.length !== 1) {\n        return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n      }\n      const doc = docs[0];\n      if (doc.isFoundDocument()) {\n        return new DocumentSnapshot<AppModelType, DbModelType>(\n          this._firestore,\n          userDataWriter,\n          doc.key,\n          doc,\n          ref.converter\n        );\n      } else if (doc.isNoDocument()) {\n        return new DocumentSnapshot<AppModelType, DbModelType>(\n          this._firestore,\n          userDataWriter,\n          ref._key,\n          null,\n          ref.converter\n        );\n      } else {\n        throw fail(\n          0x4801,\n          'BatchGetDocumentsRequest returned unexpected document',\n          {\n            doc\n          }\n        );\n      }\n    });\n  }\n\n  /**\n   * Writes to the document referred to by the provided {@link\n   * DocumentReference}. If the document does not exist yet, it will be created.\n   *\n   * @param documentRef - A reference to the document to be set.\n   * @param data - An object of the fields and values for the document.\n   * @throws Error - If the provided input is not a valid Firestore document.\n   * @returns This `Transaction` instance. Used for chaining method calls.\n   */\n  set<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>,\n    data: WithFieldValue<AppModelType>\n  ): this;\n  /**\n   * Writes to the document referred to by the provided {@link\n   * DocumentReference}. If the document does not exist yet, it will be created.\n   * If you provide `merge` or `mergeFields`, the provided data can be merged\n   * into an existing document.\n   *\n   * @param documentRef - A reference to the document to be set.\n   * @param data - An object of the fields and values for the document.\n   * @param options - An object to configure the set behavior.\n   * @throws Error - If the provided input is not a valid Firestore document.\n   * @returns This `Transaction` instance. Used for chaining method calls.\n   */\n  set<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>,\n    data: PartialWithFieldValue<AppModelType>,\n    options: SetOptions\n  ): this;\n  set<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>,\n    value: PartialWithFieldValue<AppModelType>,\n    options?: SetOptions\n  ): this {\n    const ref = validateReference(documentRef, this._firestore);\n    const convertedValue = applyFirestoreDataConverter(\n      ref.converter,\n      value,\n      options\n    );\n    const parsed = parseSetData(\n      this._dataReader,\n      'Transaction.set',\n      ref._key,\n      convertedValue,\n      ref.converter !== null,\n      options\n    );\n    this._transaction.set(ref._key, parsed);\n    return this;\n  }\n\n  /**\n   * Updates fields in the document referred to by the provided {@link\n   * DocumentReference}. The update will fail if applied to a document that does\n   * not exist.\n   *\n   * @param documentRef - A reference to the document to be updated.\n   * @param data - An object containing the fields and values with which to\n   * update the document. Fields can contain dots to reference nested fields\n   * within the document.\n   * @throws Error - If the provided input is not valid Firestore data.\n   * @returns This `Transaction` instance. Used for chaining method calls.\n   */\n  update<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>,\n    data: UpdateData<DbModelType>\n  ): this;\n  /**\n   * Updates fields in the document referred to by the provided {@link\n   * DocumentReference}. The update will fail if applied to a document that does\n   * not exist.\n   *\n   * Nested fields can be updated by providing dot-separated field path\n   * strings or by providing `FieldPath` objects.\n   *\n   * @param documentRef - A reference to the document to be updated.\n   * @param field - The first field to update.\n   * @param value - The first value.\n   * @param moreFieldsAndValues - Additional key/value pairs.\n   * @throws Error - If the provided input is not valid Firestore data.\n   * @returns This `Transaction` instance. Used for chaining method calls.\n   */\n  update<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>,\n    field: string | FieldPath,\n    value: unknown,\n    ...moreFieldsAndValues: unknown[]\n  ): this;\n  update<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>,\n    fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n    value?: unknown,\n    ...moreFieldsAndValues: unknown[]\n  ): this {\n    const ref = validateReference(documentRef, this._firestore);\n\n    // For Compat types, we have to \"extract\" the underlying types before\n    // performing validation.\n    fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n    let parsed;\n    if (\n      typeof fieldOrUpdateData === 'string' ||\n      fieldOrUpdateData instanceof FieldPath\n    ) {\n      parsed = parseUpdateVarargs(\n        this._dataReader,\n        'Transaction.update',\n        ref._key,\n        fieldOrUpdateData,\n        value,\n        moreFieldsAndValues\n      );\n    } else {\n      parsed = parseUpdateData(\n        this._dataReader,\n        'Transaction.update',\n        ref._key,\n        fieldOrUpdateData\n      );\n    }\n\n    this._transaction.update(ref._key, parsed);\n    return this;\n  }\n\n  /**\n   * Deletes the document referred to by the provided {@link DocumentReference}.\n   *\n   * @param documentRef - A reference to the document to be deleted.\n   * @returns This `Transaction` instance. Used for chaining method calls.\n   */\n  delete<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>\n  ): this {\n    const ref = validateReference(documentRef, this._firestore);\n    this._transaction.delete(ref._key);\n    return this;\n  }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction<T>(\n  firestore: Firestore,\n  updateFunction: (transaction: Transaction) => Promise<T>,\n  options?: TransactionOptions\n): Promise<T> {\n  firestore = cast(firestore, Firestore);\n  const datastore = getDatastore(firestore);\n  const optionsWithDefaults: TransactionOptionsInternal = {\n    ...DEFAULT_TRANSACTION_OPTIONS,\n    ...options\n  };\n  validateTransactionOptions(optionsWithDefaults);\n  const deferred = new Deferred<T>();\n  new TransactionRunner<T>(\n    newAsyncQueue(),\n    datastore,\n    optionsWithDefaults,\n    internalTransaction =>\n      updateFunction(new Transaction(firestore, internalTransaction)),\n    deferred\n  ).run();\n  return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firestoreClientTransaction } from '../core/firestore_client';\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n  TransactionOptions as TransactionOptionsInternal,\n  DEFAULT_TRANSACTION_OPTIONS,\n  validateTransactionOptions\n} from '../core/transaction_options';\nimport { DocumentData, DocumentReference } from '../lite-api/reference';\nimport { Transaction as LiteTransaction } from '../lite-api/transaction';\nimport { validateReference } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { DocumentSnapshot, SnapshotMetadata } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport { ExpUserDataWriter } from './user_data_writer';\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction extends LiteTransaction {\n  // This class implements the same logic as the Transaction API in the Lite SDK\n  // but is subclassed in order to return its own DocumentSnapshot types.\n\n  /** @hideconstructor */\n  constructor(\n    protected readonly _firestore: Firestore,\n    _transaction: InternalTransaction\n  ) {\n    super(_firestore, _transaction);\n  }\n\n  /**\n   * Reads the document referenced by the provided {@link DocumentReference}.\n   *\n   * @param documentRef - A reference to the document to be read.\n   * @returns A `DocumentSnapshot` with the read data.\n   */\n  get<AppModelType, DbModelType extends DocumentData>(\n    documentRef: DocumentReference<AppModelType, DbModelType>\n  ): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n    const ref = validateReference(documentRef, this._firestore);\n    const userDataWriter = new ExpUserDataWriter(this._firestore);\n    return super\n      .get(documentRef)\n      .then(\n        liteDocumentSnapshot =>\n          new DocumentSnapshot(\n            this._firestore,\n            userDataWriter,\n            ref._key,\n            liteDocumentSnapshot._document,\n            new SnapshotMetadata(\n              /* hasPendingWrites= */ false,\n              /* fromCache= */ false\n            ),\n            ref.converter\n          )\n      );\n  }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction<T>(\n  firestore: Firestore,\n  updateFunction: (transaction: Transaction) => Promise<T>,\n  options?: TransactionOptions\n): Promise<T> {\n  firestore = cast(firestore, Firestore);\n  const optionsWithDefaults: TransactionOptionsInternal = {\n    ...DEFAULT_TRANSACTION_OPTIONS,\n    ...options\n  };\n  validateTransactionOptions(optionsWithDefaults);\n  const client = ensureFirestoreConfigured(firestore);\n  return firestoreClientTransaction(\n    client,\n    internalTransaction =>\n      updateFunction(new Transaction(firestore, internalTransaction)),\n    optionsWithDefaults\n  );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JsonObject } from '../model/object_value';\nimport { FirestoreError } from '../util/error';\n\n/**\n * Observer/Subscribe interfaces.\n */\nexport type NextFn<T> = (value: T) => void;\nexport type ErrorFn = (error: FirestoreError) => void;\nexport type CompleteFn = () => void;\n\n// Allow for any of the Observer methods to be undefined.\nexport interface PartialObserver<T> {\n  next?: NextFn<T>;\n  error?: ErrorFn;\n  complete?: CompleteFn;\n}\n\nexport function isPartialObserver<T>(obj: unknown): obj is PartialObserver<T> {\n  return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj: unknown, methods: string[]): boolean {\n  if (typeof obj !== 'object' || obj === null) {\n    return false;\n  }\n\n  const object = obj as JsonObject<unknown>;\n  for (const method of methods) {\n    if (method in object && typeof object[method] === 'function') {\n      return true;\n    }\n  }\n  return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { loadBundle, namedQuery } from '../api/database';\nimport {\n  CompleteFn,\n  ErrorFn,\n  isPartialObserver,\n  NextFn,\n  PartialObserver\n} from '../api/observer';\nimport { ListenerDataSource } from '../core/event_manager';\nimport {\n  firestoreClientAddSnapshotsInSyncListener,\n  firestoreClientGetDocumentFromLocalCache,\n  firestoreClientGetDocumentsFromLocalCache,\n  firestoreClientGetDocumentsViaSnapshotListener,\n  firestoreClientGetDocumentViaSnapshotListener,\n  firestoreClientListen,\n  firestoreClientWrite\n} from '../core/firestore_client';\nimport { newQueryForPath, Query as InternalQuery } from '../core/query';\nimport { ViewSnapshot } from '../core/view_snapshot';\nimport { FieldPath } from '../lite-api/field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from '../lite-api/query';\nimport {\n  CollectionReference,\n  doc,\n  DocumentData,\n  DocumentReference,\n  PartialWithFieldValue,\n  Query,\n  SetOptions,\n  UpdateData,\n  WithFieldValue\n} from '../lite-api/reference';\nimport { applyFirestoreDataConverter } from '../lite-api/reference_impl';\nimport {\n  newUserDataReader,\n  ParsedUpdateData,\n  parseSetData,\n  parseUpdateData,\n  parseUpdateVarargs\n} from '../lite-api/user_data_reader';\nimport { DocumentKey } from '../model/document_key';\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport {\n  DocumentSnapshot,\n  FirestoreDataConverter,\n  QuerySnapshot,\n  SnapshotMetadata\n} from './snapshot';\nimport { ExpUserDataWriter } from './user_data_writer';\n\n/**\n * An options object that can be passed to {@link (onSnapshot:1)} and {@link\n * QuerySnapshot.docChanges} to control which types of changes to include in the\n * result set.\n */\nexport interface SnapshotListenOptions {\n  /**\n   * Include a change even if only the metadata of the query or of a document\n   * changed. Default is false.\n   */\n  readonly includeMetadataChanges?: boolean;\n\n  /**\n   * Set the source the query listens to. Default to \"default\", which\n   * listens to both cache and server.\n   */\n  readonly source?: ListenSource;\n}\n\n/**\n * Describe the source a query listens to.\n *\n * Set to `default` to listen to both cache and server changes. Set to `cache`\n * to listen to changes in cache only.\n */\nexport type ListenSource = 'default' | 'cache';\n\n/**\n * Reads the document referred to by this `DocumentReference`.\n *\n * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting\n * for data from the server, but it may return cached data or fail if you are\n * offline and the server cannot be reached. To specify this behavior, invoke\n * {@link getDocFromCache} or {@link getDocFromServer}.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A `Promise` that resolves with a `DocumentSnapshot` containing the\n * document contents.\n */\nexport function getDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n  reference = cast<DocumentReference<AppModelType, DbModelType>>(\n    reference,\n    DocumentReference\n  );\n  const firestore = cast(reference.firestore, Firestore);\n  const client = ensureFirestoreConfigured(firestore);\n\n  return firestoreClientGetDocumentViaSnapshotListener(\n    client,\n    reference._key\n  ).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot));\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from cache.\n * Returns an error if the document is not currently cached.\n *\n * @returns A `Promise` that resolves with a `DocumentSnapshot` containing the\n * document contents.\n */\nexport function getDocFromCache<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n  reference = cast<DocumentReference<AppModelType, DbModelType>>(\n    reference,\n    DocumentReference\n  );\n  const firestore = cast(reference.firestore, Firestore);\n  const client = ensureFirestoreConfigured(firestore);\n  const userDataWriter = new ExpUserDataWriter(firestore);\n\n  return firestoreClientGetDocumentFromLocalCache(client, reference._key).then(\n    doc =>\n      new DocumentSnapshot<AppModelType, DbModelType>(\n        firestore,\n        userDataWriter,\n        reference._key,\n        doc,\n        new SnapshotMetadata(\n          doc !== null && doc.hasLocalMutations,\n          /* fromCache= */ true\n        ),\n        reference.converter\n      )\n  );\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from the server.\n * Returns an error if the network is not available.\n *\n * @returns A `Promise` that resolves with a `DocumentSnapshot` containing the\n * document contents.\n */\nexport function getDocFromServer<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n  reference = cast<DocumentReference<AppModelType, DbModelType>>(\n    reference,\n    DocumentReference\n  );\n  const firestore = cast(reference.firestore, Firestore);\n  const client = ensureFirestoreConfigured(firestore);\n\n  return firestoreClientGetDocumentViaSnapshotListener(client, reference._key, {\n    source: 'server'\n  }).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot`.\n *\n * Note: `getDocs()` attempts to provide up-to-date data when possible by\n * waiting for data from the server, but it may return cached data or fail if\n * you are offline and the server cannot be reached. To specify this behavior,\n * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.\n *\n * @returns A `Promise` that resolves with the results of the query.\n */\nexport function getDocs<AppModelType, DbModelType extends DocumentData>(\n  query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n  query = cast<Query<AppModelType, DbModelType>>(query, Query);\n  const firestore = cast(query.firestore, Firestore);\n  const client = ensureFirestoreConfigured(firestore);\n  const userDataWriter = new ExpUserDataWriter(firestore);\n\n  validateHasExplicitOrderByForLimitToLast(query._query);\n  return firestoreClientGetDocumentsViaSnapshotListener(\n    client,\n    query._query\n  ).then(\n    snapshot =>\n      new QuerySnapshot<AppModelType, DbModelType>(\n        firestore,\n        userDataWriter,\n        query,\n        snapshot\n      )\n  );\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from cache.\n * Returns an empty result set if no documents matching the query are currently\n * cached.\n *\n * @returns A `Promise` that resolves with the results of the query.\n */\nexport function getDocsFromCache<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n  query = cast<Query<AppModelType, DbModelType>>(query, Query);\n  const firestore = cast(query.firestore, Firestore);\n  const client = ensureFirestoreConfigured(firestore);\n  const userDataWriter = new ExpUserDataWriter(firestore);\n\n  return firestoreClientGetDocumentsFromLocalCache(client, query._query).then(\n    snapshot =>\n      new QuerySnapshot<AppModelType, DbModelType>(\n        firestore,\n        userDataWriter,\n        query,\n        snapshot\n      )\n  );\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from the\n * server. Returns an error if the network is not available.\n *\n * @returns A `Promise` that resolves with the results of the query.\n */\nexport function getDocsFromServer<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n  query = cast<Query<AppModelType, DbModelType>>(query, Query);\n  const firestore = cast(query.firestore, Firestore);\n  const client = ensureFirestoreConfigured(firestore);\n  const userDataWriter = new ExpUserDataWriter(firestore);\n\n  return firestoreClientGetDocumentsViaSnapshotListener(client, query._query, {\n    source: 'server'\n  }).then(\n    snapshot => new QuerySnapshot(firestore, userDataWriter, query, snapshot)\n  );\n}\n\n/**\n * Writes to the document referred to by this `DocumentReference`. If the\n * document does not yet exist, it will be created.\n *\n * Note that the returned `Promise` does _not_ resolve until the data is\n * successfully written to the remote Firestore backend and, similarly, is not\n * rejected until the remote Firestore backend reports an error saving the given\n * data. So if the client cannot reach the backend (for example, due to being\n * offline) then the returned `Promise` will not resolve for a potentially-long\n * time (for example, until the client has gone back online). That being said,\n * the given data _will_ be immediately saved to the local cache and will be\n * incorporated into future \"get\" operations as if it had been successfully\n * written to the remote Firestore server, a feature of Firestore called\n * \"latency compensation\". The data will _eventually_ be written to the remote\n * Firestore backend once a connection can be established. Therefore, it is\n * usually undesirable to `await` the `Promise` returned from this function\n * because the indefinite amount of time before which the promise resolves or\n * rejects can block application logic unnecessarily.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @returns A `Promise` that resolves once the data has been successfully\n * written to the backend or rejects once the backend reports an error writing\n * the data.\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  data: WithFieldValue<AppModelType>\n): Promise<void>;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * Note that the returned `Promise` does _not_ resolve until the data is\n * successfully written to the remote Firestore backend and, similarly, is not\n * rejected until the remote Firestore backend reports an error saving the given\n * data. So if the client cannot reach the backend (for example, due to being\n * offline) then the returned `Promise` will not resolve for a potentially-long\n * time (for example, until the client has gone back online). That being said,\n * the given data _will_ be immediately saved to the local cache and will be\n * incorporated into future \"get\" operations as if it had been successfully\n * written to the remote Firestore server, a feature of Firestore called\n * \"latency compensation\". The data will _eventually_ be written to the remote\n * Firestore backend once a connection can be established. Therefore, it is\n * usually undesirable to `await` the `Promise` returned from this function\n * because the indefinite amount of time before which the promise resolves or\n * rejects can block application logic unnecessarily.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @returns A `Promise` that resolves once the data has been successfully\n * written to the backend or rejects once the backend reports an error writing\n * the data.\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  data: PartialWithFieldValue<AppModelType>,\n  options: SetOptions\n): Promise<void>;\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  data: PartialWithFieldValue<AppModelType>,\n  options?: SetOptions\n): Promise<void> {\n  reference = cast<DocumentReference<AppModelType, DbModelType>>(\n    reference,\n    DocumentReference\n  );\n  const firestore = cast(reference.firestore, Firestore);\n\n  const convertedValue = applyFirestoreDataConverter(\n    reference.converter,\n    data as WithFieldValue<AppModelType>,\n    options\n  );\n  const dataReader = newUserDataReader(firestore);\n  const parsed = parseSetData(\n    dataReader,\n    'setDoc',\n    reference._key,\n    convertedValue,\n    reference.converter !== null,\n    options\n  );\n\n  const mutation = parsed.toMutation(reference._key, Precondition.none());\n  return executeWrite(firestore, [mutation]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * Note that the returned `Promise` does _not_ resolve until the data is\n * successfully written to the remote Firestore backend and, similarly, is not\n * rejected until the remote Firestore backend reports an error saving the given\n * data. So if the client cannot reach the backend (for example, due to being\n * offline) then the returned `Promise` will not resolve for a potentially-long\n * time (for example, until the client has gone back online). That being said,\n * the given data _will_ be immediately saved to the local cache and will be\n * incorporated into future \"get\" operations as if it had been successfully\n * written to the remote Firestore server, a feature of Firestore called\n * \"latency compensation\". The data will _eventually_ be written to the remote\n * Firestore backend once a connection can be established. Therefore, it is\n * usually undesirable to `await` the `Promise` returned from this function\n * because the indefinite amount of time before which the promise resolves or\n * rejects can block application logic unnecessarily.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @returns A `Promise` that resolves once the data has been successfully\n * written to the backend or rejects once the backend reports an error writing\n * the data.\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  data: UpdateData<DbModelType>\n): Promise<void>;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * Note that the returned `Promise` does _not_ resolve until the data is\n * successfully written to the remote Firestore backend and, similarly, is not\n * rejected until the remote Firestore backend reports an error saving the given\n * data. So if the client cannot reach the backend (for example, due to being\n * offline) then the returned `Promise` will not resolve for a potentially-long\n * time (for example, until the client has gone back online). That being said,\n * the given data _will_ be immediately saved to the local cache and will be\n * incorporated into future \"get\" operations as if it had been successfully\n * written to the remote Firestore server, a feature of Firestore called\n * \"latency compensation\". The data will _eventually_ be written to the remote\n * Firestore backend once a connection can be established. Therefore, it is\n * usually undesirable to `await` the `Promise` returned from this function\n * because the indefinite amount of time before which the promise resolves or\n * rejects can block application logic unnecessarily.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @returns A `Promise` that resolves once the data has been successfully\n * written to the backend or rejects once the backend reports an error writing\n * the data.\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  field: string | FieldPath,\n  value: unknown,\n  ...moreFieldsAndValues: unknown[]\n): Promise<void>;\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<unknown>,\n  fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n  value?: unknown,\n  ...moreFieldsAndValues: unknown[]\n): Promise<void> {\n  reference = cast<DocumentReference<AppModelType, DbModelType>>(\n    reference,\n    DocumentReference\n  );\n  const firestore = cast(reference.firestore, Firestore);\n\n  const dataReader = newUserDataReader(firestore);\n\n  // For Compat types, we have to \"extract\" the underlying types before\n  // performing validation.\n  fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n  let parsed: ParsedUpdateData;\n  if (\n    typeof fieldOrUpdateData === 'string' ||\n    fieldOrUpdateData instanceof FieldPath\n  ) {\n    parsed = parseUpdateVarargs(\n      dataReader,\n      'updateDoc',\n      reference._key,\n      fieldOrUpdateData,\n      value,\n      moreFieldsAndValues\n    );\n  } else {\n    parsed = parseUpdateData(\n      dataReader,\n      'updateDoc',\n      reference._key,\n      fieldOrUpdateData\n    );\n  }\n\n  const mutation = parsed.toMutation(reference._key, Precondition.exists(true));\n  return executeWrite(firestore, [mutation]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * Note that the returned `Promise` does _not_ resolve until the document is\n * successfully deleted from the remote Firestore backend and, similarly, is not\n * rejected until the remote Firestore backend reports an error deleting the given\n * document. So if the client cannot reach the backend (for example, due to being\n * offline) then the returned `Promise` will not resolve for a potentially-long\n * time (for example, until the client has gone back online). That being said,\n * the given data _will_ be immediately deleted from the local cache and will be\n * reflected in future \"get\" operations as if it had been successfully\n * deleted from the remote Firestore server, a feature of Firestore called\n * \"latency compensation\". The document will _eventually_ be deleted from the remote\n * Firestore backend once a connection can be established. Therefore, it is\n * usually undesirable to `await` the `Promise` returned from this function\n * because the indefinite amount of time before which the promise resolves or\n * rejects can block application logic unnecessarily.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` that resolves once the document has been successfully\n * deleted from the backend or rejects once the backend reports an error\n * deleting the document.\n */\nexport function deleteDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>\n): Promise<void> {\n  const firestore = cast(reference.firestore, Firestore);\n  const mutations = [new DeleteMutation(reference._key, Precondition.none())];\n  return executeWrite(firestore, mutations);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * Note that the returned `Promise` does _not_ resolve until the document is\n * successfully created to the remote Firestore backend and, similarly, is not\n * rejected until the remote Firestore backend reports an error creating the given\n * document. So if the client cannot reach the backend (for example, due to being\n * offline) then the returned `Promise` will not resolve for a potentially-long\n * time (for example, until the client has gone back online). That being said,\n * the given document _will_ be immediately created in the local cache and will be\n * incorporated into future \"get\" operations as if it had been successfully\n * created in the remote Firestore server, a feature of Firestore called\n * \"latency compensation\". The document will _eventually_ be created in the remote\n * Firestore backend once a connection can be established. Therefore, it is\n * usually undesirable to `await` the `Promise` returned from this function\n * because the indefinite amount of time before which the promise resolves or\n * rejects can block application logic unnecessarily.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @returns A `Promise` that resolves once the docoument has been successfully\n * created in the backend or rejects once the backend reports an error creating\n * the document.\n */\nexport function addDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: CollectionReference<AppModelType, DbModelType>,\n  data: WithFieldValue<AppModelType>\n): Promise<DocumentReference<AppModelType, DbModelType>> {\n  const firestore = cast(reference.firestore, Firestore);\n\n  const docRef = doc(reference);\n  const convertedValue = applyFirestoreDataConverter(reference.converter, data);\n\n  const dataReader = newUserDataReader(reference.firestore);\n  const parsed = parseSetData(\n    dataReader,\n    'addDoc',\n    docRef._key,\n    convertedValue,\n    reference.converter !== null,\n    {}\n  );\n\n  const mutation = parsed.toMutation(docRef._key, Precondition.exists(false));\n  return executeWrite(firestore, [mutation]).then(() => docRef);\n}\n\n/**\n * A function returned by `onSnapshot()` that removes the listener when invoked.\n */\nexport interface Unsubscribe {\n  /** Removes the listener when invoked. */\n  (): void;\n}\n\n// TODO(firestorexp): Make sure these overloads are tested via the Firestore\n// integration tests\n\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  observer: {\n    next?: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void;\n    error?: (error: FirestoreError) => void;\n    complete?: () => void;\n  }\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  options: SnapshotListenOptions,\n  observer: {\n    next?: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void;\n    error?: (error: FirestoreError) => void;\n    complete?: () => void;\n  }\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  onNext: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void,\n  onError?: (error: FirestoreError) => void,\n  onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  options: SnapshotListenOptions,\n  onNext: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void,\n  onError?: (error: FirestoreError) => void,\n  onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n  query: Query<AppModelType, DbModelType>,\n  observer: {\n    next?: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void;\n    error?: (error: FirestoreError) => void;\n    complete?: () => void;\n  }\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n  query: Query<AppModelType, DbModelType>,\n  options: SnapshotListenOptions,\n  observer: {\n    next?: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void;\n    error?: (error: FirestoreError) => void;\n    complete?: () => void;\n  }\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param onNext - A callback to be called every time a new `QuerySnapshot` is available.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n  query: Query<AppModelType, DbModelType>,\n  onNext: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void,\n  onError?: (error: FirestoreError) => void,\n  onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `QuerySnapshot` is available.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n  query: Query<AppModelType, DbModelType>,\n  options: SnapshotListenOptions,\n  onNext: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void,\n  onError?: (error: FirestoreError) => void,\n  onCompletion?: () => void\n): Unsubscribe;\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n  reference:\n    | Query<AppModelType, DbModelType>\n    | DocumentReference<AppModelType, DbModelType>,\n  ...args: unknown[]\n): Unsubscribe {\n  // onSnapshot for Query or Document.\n  reference = getModularInstance(reference);\n  let options: SnapshotListenOptions = {\n    includeMetadataChanges: false,\n    source: 'default'\n  };\n  let currArg = 0;\n  if (typeof args[currArg] === 'object' && !isPartialObserver(args[currArg])) {\n    options = args[currArg++] as SnapshotListenOptions;\n  }\n\n  const internalOptions = {\n    includeMetadataChanges: options.includeMetadataChanges,\n    source: options.source as ListenerDataSource\n  };\n\n  if (isPartialObserver(args[currArg])) {\n    const userObserver = args[currArg] as PartialObserver<\n      QuerySnapshot<AppModelType, DbModelType>\n    >;\n    args[currArg] = userObserver.next?.bind(userObserver);\n    args[currArg + 1] = userObserver.error?.bind(userObserver);\n    args[currArg + 2] = userObserver.complete?.bind(userObserver);\n  }\n\n  let observer: PartialObserver<ViewSnapshot>;\n  let firestore: Firestore;\n  let internalQuery: InternalQuery;\n\n  if (reference instanceof DocumentReference) {\n    firestore = cast(reference.firestore, Firestore);\n    internalQuery = newQueryForPath(reference._key.path);\n\n    observer = {\n      next: snapshot => {\n        if (args[currArg]) {\n          (\n            args[currArg] as NextFn<DocumentSnapshot<AppModelType, DbModelType>>\n          )(\n            convertToDocSnapshot(\n              firestore,\n              reference as DocumentReference<AppModelType, DbModelType>,\n              snapshot\n            )\n          );\n        }\n      },\n      error: args[currArg + 1] as ErrorFn,\n      complete: args[currArg + 2] as CompleteFn\n    };\n  } else {\n    const query = cast<Query<AppModelType, DbModelType>>(reference, Query);\n    firestore = cast(query.firestore, Firestore);\n    internalQuery = query._query;\n    const userDataWriter = new ExpUserDataWriter(firestore);\n    observer = {\n      next: snapshot => {\n        if (args[currArg]) {\n          (args[currArg] as NextFn<QuerySnapshot<AppModelType, DbModelType>>)(\n            new QuerySnapshot(firestore, userDataWriter, query, snapshot)\n          );\n        }\n      },\n      error: args[currArg + 1] as ErrorFn,\n      complete: args[currArg + 2] as CompleteFn\n    };\n\n    validateHasExplicitOrderByForLimitToLast(reference._query);\n  }\n\n  const client = ensureFirestoreConfigured(firestore);\n  return firestoreClientListen(\n    client,\n    internalQuery,\n    internalOptions,\n    observer\n  );\n}\n\n/**\n * Attaches a listener for `QuerySnapshot` events based on data generated by invoking\n * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param onNext - A callback to be called every time a new `QuerySnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  firestore: Firestore,\n  snapshotJson: object,\n  onNext: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void,\n  onError?: (error: FirestoreError) => void,\n  onCompletion?: () => void,\n  converter?: FirestoreDataConverter<DbModelType>\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  firestore: Firestore,\n  snapshotJson: object,\n  onNext: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void,\n  onError?: (error: FirestoreError) => void,\n  onCompletion?: () => void,\n  converter?: FirestoreDataConverter<DbModelType>\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on data generated by invoking\n * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `QuerySnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  firestore: Firestore,\n  snapshotJson: object,\n  options: SnapshotListenOptions,\n  onNext: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void,\n  onError?: (error: FirestoreError) => void,\n  onCompletion?: () => void,\n  converter?: FirestoreDataConverter<DbModelType>\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks\n * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled\n * by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  firestore: Firestore,\n  snapshotJson: object,\n  options: SnapshotListenOptions,\n  onNext: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void,\n  onError?: (error: FirestoreError) => void,\n  onCompletion?: () => void,\n  converter?: FirestoreDataConverter<DbModelType>\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking\n * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  firestore: Firestore,\n  snapshotJson: object,\n  observer: {\n    next: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void;\n    error?: (error: FirestoreError) => void;\n    complete?: () => void;\n  },\n  converter?: FirestoreDataConverter<DbModelType>\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks\n * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled\n * by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  firestore: Firestore,\n  snapshotJson: object,\n  observer: {\n    next: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void;\n    error?: (error: FirestoreError) => void;\n    complete?: () => void;\n  },\n  converter?: FirestoreDataConverter<DbModelType>\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking\n * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  firestore: Firestore,\n  snapshotJson: object,\n  options: SnapshotListenOptions,\n  observer: {\n    next: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void;\n    error?: (error: FirestoreError) => void;\n    complete?: () => void;\n  },\n  converter?: FirestoreDataConverter<DbModelType>\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on QuerySnapshot data generated by\n * invoking {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError`\n * callbacks or pass a single observer object with `next` and `error` callbacks. The listener can be\n * cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  firestore: Firestore,\n  snapshotJson: object,\n  options: SnapshotListenOptions,\n  observer: {\n    next: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void;\n    error?: (error: FirestoreError) => void;\n    complete?: () => void;\n  },\n  converter?: FirestoreDataConverter<DbModelType>\n): Unsubscribe;\nexport function onSnapshotResume<\n  AppModelType,\n  DbModelType extends DocumentData\n>(reference: Firestore, snapshotJson: object, ...args: unknown[]): Unsubscribe {\n  const db = getModularInstance(reference);\n  const json = normalizeSnapshotJsonFields(snapshotJson);\n  if (json.error) {\n    throw new FirestoreError(Code.INVALID_ARGUMENT, json.error);\n  }\n  let curArg = 0;\n  let options: SnapshotListenOptions | undefined = undefined;\n  if (typeof args[curArg] === 'object' && !isPartialObserver(args[curArg])) {\n    options = args[curArg++] as SnapshotListenOptions;\n  }\n\n  if (json.bundleSource === 'QuerySnapshot') {\n    let observer: {\n      next: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void;\n      error?: (error: FirestoreError) => void;\n      complete?: () => void;\n    } | null = null;\n    if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) {\n      const userObserver = args[curArg++] as PartialObserver<\n        QuerySnapshot<AppModelType, DbModelType>\n      >;\n      observer = {\n        next: userObserver.next!,\n        error: userObserver.error,\n        complete: userObserver.complete\n      };\n    } else {\n      observer = {\n        next: args[curArg++] as (\n          snapshot: QuerySnapshot<AppModelType, DbModelType>\n        ) => void,\n        error: args[curArg++] as (error: FirestoreError) => void,\n        complete: args[curArg++] as () => void\n      };\n    }\n    return onSnapshotQuerySnapshotBundle(\n      db,\n      json,\n      options,\n      observer!,\n      args[curArg] as FirestoreDataConverter<DbModelType>\n    );\n  } else if (json.bundleSource === 'DocumentSnapshot') {\n    let observer: {\n      next: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void;\n      error?: (error: FirestoreError) => void;\n      complete?: () => void;\n    } | null = null;\n    if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) {\n      const userObserver = args[curArg++] as PartialObserver<\n        DocumentSnapshot<AppModelType, DbModelType>\n      >;\n      observer = {\n        next: userObserver.next!,\n        error: userObserver.error,\n        complete: userObserver.complete\n      };\n    } else {\n      observer = {\n        next: args[curArg++] as (\n          snapshot: DocumentSnapshot<AppModelType, DbModelType>\n        ) => void,\n        error: args[curArg++] as (error: FirestoreError) => void,\n        complete: args[curArg++] as () => void\n      };\n    }\n    return onSnapshotDocumentSnapshotBundle(\n      db,\n      json,\n      options,\n      observer!,\n      args[curArg] as FirestoreDataConverter<DbModelType>\n    );\n  } else {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      `unsupported bundle source: ${json.bundleSource}`\n    );\n  }\n}\n\n// TODO(firestorexp): Make sure these overloads are tested via the Firestore\n// integration tests\n\n/**\n * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync\n * event indicates that all listeners affected by a given change have fired,\n * even if a single server-generated change affects multiple listeners.\n *\n * NOTE: The snapshots-in-sync event only indicates that listeners are in sync\n * with each other, but does not relate to whether those snapshots are in sync\n * with the server. Use SnapshotMetadata in the individual listeners to\n * determine if a snapshot is from the cache or the server.\n *\n * @param firestore - The instance of Firestore for synchronizing snapshots.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n */\nexport function onSnapshotsInSync(\n  firestore: Firestore,\n  observer: {\n    next?: (value: void) => void;\n    error?: (error: FirestoreError) => void;\n    complete?: () => void;\n  }\n): Unsubscribe;\n/**\n * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync\n * event indicates that all listeners affected by a given change have fired,\n * even if a single server-generated change affects multiple listeners.\n *\n * NOTE: The snapshots-in-sync event only indicates that listeners are in sync\n * with each other, but does not relate to whether those snapshots are in sync\n * with the server. Use `SnapshotMetadata` in the individual listeners to\n * determine if a snapshot is from the cache or the server.\n *\n * @param firestore - The `Firestore` instance for synchronizing snapshots.\n * @param onSync - A callback to be called every time all snapshot listeners are\n * in sync with each other.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n */\nexport function onSnapshotsInSync(\n  firestore: Firestore,\n  onSync: () => void\n): Unsubscribe;\nexport function onSnapshotsInSync(\n  firestore: Firestore,\n  arg: unknown\n): Unsubscribe {\n  firestore = cast(firestore, Firestore);\n  const client = ensureFirestoreConfigured(firestore);\n  const observer = isPartialObserver(arg)\n    ? (arg as PartialObserver<void>)\n    : {\n        next: arg as () => void\n      };\n\n  return firestoreClientAddSnapshotsInSyncListener(client, observer);\n}\n\n/**\n * Locally writes `mutations` on the async queue.\n * @internal\n */\nexport function executeWrite(\n  firestore: Firestore,\n  mutations: Mutation[]\n): Promise<void> {\n  const client = ensureFirestoreConfigured(firestore);\n  return firestoreClientWrite(client, mutations);\n}\n\n/**\n * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`\n * to a {@link DocumentSnapshot}.\n */\nfunction convertToDocSnapshot<AppModelType, DbModelType extends DocumentData>(\n  firestore: Firestore,\n  ref: DocumentReference<AppModelType, DbModelType>,\n  snapshot: ViewSnapshot\n): DocumentSnapshot<AppModelType, DbModelType> {\n  debugAssert(\n    snapshot.docs.size <= 1,\n    'Expected zero or a single result on a document-only query'\n  );\n  const doc = snapshot.docs.get(ref._key);\n\n  const userDataWriter = new ExpUserDataWriter(firestore);\n  return new DocumentSnapshot<AppModelType, DbModelType>(\n    firestore,\n    userDataWriter,\n    ref._key,\n    doc,\n    new SnapshotMetadata(snapshot.hasPendingWrites, snapshot.fromCache),\n    ref.converter\n  );\n}\n\n/**\n * Ensures the data required to construct an {@link onSnapshot} listener exist in a `snapshotJson`\n * object that originates from {@link DocumentSnapshot.toJSON} or {@link Querysnapshot.toJSON}. The\n * data is normalized into a typed object.\n *\n * @param snapshotJson - The JSON object that the app provided to {@link onSnapshot}.\n * @returns A normalized object that contains all of the required bundle JSON fields. If\n * {@link snapshotJson} doesn't contain the required fields, or if the fields exist as empty\n * strings, then the {@link snapshotJson.error} field will be a non empty string.\n *\n * @internal\n */\nfunction normalizeSnapshotJsonFields(snapshotJson: object): {\n  bundle: string;\n  bundleName: string;\n  bundleSource: string;\n  error?: string;\n} {\n  const result: {\n    bundle: string;\n    bundleName: string;\n    bundleSource: string;\n    error?: string;\n  } = {\n    bundle: '',\n    bundleName: '',\n    bundleSource: ''\n  };\n  const requiredKeys = ['bundle', 'bundleName', 'bundleSource'];\n  for (const key of requiredKeys) {\n    if (!(key in snapshotJson)) {\n      result.error = `snapshotJson missing required field: ${key}`;\n      break;\n    }\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    const value = (snapshotJson as any)[key];\n    if (typeof value !== 'string') {\n      result.error = `snapshotJson field '${key}' must be a string.`;\n      break;\n    }\n    if (value.length === 0) {\n      result.error = `snapshotJson field '${key}' cannot be an empty string.`;\n      break;\n    }\n    if (key === 'bundle') {\n      result.bundle = value;\n    } else if (key === 'bundleName') {\n      result.bundleName = value;\n    } else if (key === 'bundleSource') {\n      result.bundleSource = value;\n    }\n  }\n  return result;\n}\n\n/**\n * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a\n * {@link DocumentReference} for the document in the bundle.\n *\n * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request.\n * @param json - The JSON bundle to load, produced by {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n *\n * @internal\n */\nfunction onSnapshotDocumentSnapshotBundle<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  db: Firestore,\n  json: { bundle: string; bundleName: string; bundleSource: string },\n  options: SnapshotListenOptions | undefined,\n  observer: {\n    next: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void;\n    error?: (error: FirestoreError) => void;\n    complete?: () => void;\n  },\n  converter?: FirestoreDataConverter<DbModelType>\n): Unsubscribe {\n  let unsubscribed: boolean = false;\n  let internalUnsubscribe: Unsubscribe | undefined;\n  const loadTask = loadBundle(db, json.bundle);\n  loadTask\n    .then(() => {\n      if (!unsubscribed) {\n        const docReference = new DocumentReference(\n          db,\n          converter ? converter : null,\n          DocumentKey.fromPath(json.bundleName)\n        );\n        internalUnsubscribe = onSnapshot(\n          docReference as DocumentReference<AppModelType, DbModelType>,\n          options ? options : {},\n          observer\n        );\n      }\n    })\n    .catch(e => {\n      if (observer.error) {\n        observer.error(e);\n      }\n      return () => {};\n    });\n  return () => {\n    if (unsubscribed) {\n      return;\n    }\n    unsubscribed = true;\n    if (internalUnsubscribe) {\n      internalUnsubscribe();\n    }\n  };\n}\n\n/**\n * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a\n * {@link Query} that represents the Query in the bundle.\n *\n * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request.\n * @param json - The JSON bundle to load, produced by {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n *\n * @internal\n */\nfunction onSnapshotQuerySnapshotBundle<\n  AppModelType,\n  DbModelType extends DocumentData\n>(\n  db: Firestore,\n  json: { bundle: string; bundleName: string; bundleSource: string },\n  options: SnapshotListenOptions | undefined,\n  observer: {\n    next: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void;\n    error?: (error: FirestoreError) => void;\n    complete?: () => void;\n  },\n  converter?: FirestoreDataConverter<DbModelType>\n): Unsubscribe {\n  let unsubscribed: boolean = false;\n  let internalUnsubscribe: Unsubscribe | undefined;\n  const loadTask = loadBundle(db, json.bundle);\n  loadTask\n    .then(() => namedQuery(db, json.bundleName))\n    .then(query => {\n      if (query && !unsubscribed) {\n        const realQuery: Query = (query as Query)!;\n        if (converter) {\n          realQuery.withConverter(converter);\n        }\n        internalUnsubscribe = onSnapshot(\n          query as Query<AppModelType, DbModelType>,\n          options ? options : {},\n          observer\n        );\n      }\n    })\n    .catch(e => {\n      if (observer.error) {\n        observer.error(e);\n      }\n      return () => {};\n    });\n  return () => {\n    if (unsubscribed) {\n      return;\n    }\n    unsubscribed = true;\n    if (internalUnsubscribe) {\n      internalUnsubscribe();\n    }\n  };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WriteBatch } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { executeWrite } from './reference_impl';\n\nexport { WriteBatch };\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n  firestore = cast(firestore, Firestore);\n  ensureFirestoreConfigured(firestore);\n  return new WriteBatch(firestore, mutations =>\n    executeWrite(firestore, mutations)\n  );\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firestoreClientSetIndexConfiguration } from '../core/firestore_client';\nimport { fieldPathFromDotSeparatedString } from '../lite-api/user_data_reader';\nimport {\n  FieldIndex,\n  IndexKind,\n  IndexSegment,\n  IndexState\n} from '../model/field_index';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\n\nexport {\n  connectFirestoreEmulator,\n  EmulatorMockTokenOptions\n} from '../lite-api/database';\n\n/**\n * A single field element in an index configuration.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexField {\n  /** The field path to index. */\n  readonly fieldPath: string;\n  /**\n   * What type of array index to create. Set to `CONTAINS` for `array-contains`\n   * and `array-contains-any` indexes.\n   *\n   * Only one of `arrayConfig` or `order` should be set;\n   */\n  readonly arrayConfig?: 'CONTAINS';\n  /**\n   * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for\n   * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters.\n   *\n   * Only one of `arrayConfig` or `order` should be set.\n   */\n  readonly order?: 'ASCENDING' | 'DESCENDING';\n\n  [key: string]: unknown;\n}\n\n/**\n * The SDK definition of a Firestore index.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface Index {\n  /** The ID of the collection to index. */\n  readonly collectionGroup: string;\n  /** A list of fields to index. */\n  readonly fields?: IndexField[];\n\n  [key: string]: unknown;\n}\n\n/**\n * A list of Firestore indexes to speed up local query execution.\n *\n * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format}\n * for a description of the format of the index definition.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexConfiguration {\n  /** A list of all Firestore indexes. */\n  readonly indexes?: Index[];\n\n  [key: string]: unknown;\n}\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. If IndexedDb is not\n * enabled, any index configuration is ignored.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param configuration -The index definition.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n  firestore: Firestore,\n  configuration: IndexConfiguration\n): Promise<void>;\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. Invoke either\n * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()`\n * before setting an index configuration. If IndexedDb is not enabled, any\n * index configuration is ignored.\n *\n * The method accepts the JSON format exported by the Firebase CLI (`firebase\n * firestore:indexes`). If the JSON format is invalid, this method throws an\n * error.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param json -The JSON format exported by the Firebase CLI.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n  firestore: Firestore,\n  json: string\n): Promise<void>;\n\nexport function setIndexConfiguration(\n  firestore: Firestore,\n  jsonOrConfiguration: string | IndexConfiguration\n): Promise<void> {\n  firestore = cast(firestore, Firestore);\n  const client = ensureFirestoreConfigured(firestore);\n  if (\n    !client._uninitializedComponentsProvider ||\n    client._uninitializedComponentsProvider._offline.kind === 'memory'\n  ) {\n    // PORTING NOTE: We don't return an error if the user has not enabled\n    // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n    logWarn('Cannot enable indexes when persistence is disabled');\n    return Promise.resolve();\n  }\n  const parsedIndexes = parseIndexes(jsonOrConfiguration);\n  return firestoreClientSetIndexConfiguration(client, parsedIndexes);\n}\n\nexport function parseIndexes(\n  jsonOrConfiguration: string | IndexConfiguration\n): FieldIndex[] {\n  const indexConfiguration =\n    typeof jsonOrConfiguration === 'string'\n      ? (tryParseJson(jsonOrConfiguration) as IndexConfiguration)\n      : jsonOrConfiguration;\n  const parsedIndexes: FieldIndex[] = [];\n\n  if (Array.isArray(indexConfiguration.indexes)) {\n    for (const index of indexConfiguration.indexes) {\n      const collectionGroup = tryGetString(index, 'collectionGroup');\n\n      const segments: IndexSegment[] = [];\n      if (Array.isArray(index.fields)) {\n        for (const field of index.fields) {\n          const fieldPathString = tryGetString(field, 'fieldPath');\n          const fieldPath = fieldPathFromDotSeparatedString(\n            'setIndexConfiguration',\n            fieldPathString\n          );\n\n          if (field.arrayConfig === 'CONTAINS') {\n            segments.push(new IndexSegment(fieldPath, IndexKind.CONTAINS));\n          } else if (field.order === 'ASCENDING') {\n            segments.push(new IndexSegment(fieldPath, IndexKind.ASCENDING));\n          } else if (field.order === 'DESCENDING') {\n            segments.push(new IndexSegment(fieldPath, IndexKind.DESCENDING));\n          }\n        }\n      }\n\n      parsedIndexes.push(\n        new FieldIndex(\n          FieldIndex.UNKNOWN_ID,\n          collectionGroup,\n          segments,\n          IndexState.empty()\n        )\n      );\n    }\n  }\n  return parsedIndexes;\n}\n\nfunction tryParseJson(json: string): Record<string, unknown> {\n  try {\n    return JSON.parse(json);\n  } catch (e) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'Failed to parse JSON: ' + (e as Error)?.message\n    );\n  }\n}\n\nfunction tryGetString(data: Record<string, unknown>, property: string): string {\n  if (typeof data[property] !== 'string') {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'Missing string value for: ' + property\n    );\n  }\n  return data[property] as string;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  firestoreClientDeleteAllFieldIndexes,\n  firestoreClientSetPersistentCacheIndexAutoCreationEnabled\n} from '../core/firestore_client';\nimport { cast } from '../util/input_validation';\nimport { logDebug, logWarn } from '../util/log';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\n\n/**\n * A `PersistentCacheIndexManager` for configuring persistent cache indexes used\n * for local query execution.\n *\n * To use, call `getPersistentCacheIndexManager()` to get an instance.\n */\nexport class PersistentCacheIndexManager {\n  /** A type string to uniquely identify instances of this class. */\n  readonly type: 'PersistentCacheIndexManager' = 'PersistentCacheIndexManager';\n\n  /** @hideconstructor */\n  constructor(readonly _firestore: Firestore) {}\n}\n\n/**\n * Returns the PersistentCache Index Manager used by the given `Firestore`\n * object.\n *\n * @returns The `PersistentCacheIndexManager` instance, or `null` if local\n * persistent storage is not in use.\n */\nexport function getPersistentCacheIndexManager(\n  firestore: Firestore\n): PersistentCacheIndexManager | null {\n  firestore = cast(firestore, Firestore);\n\n  const cachedInstance = persistentCacheIndexManagerByFirestore.get(firestore);\n  if (cachedInstance) {\n    return cachedInstance;\n  }\n\n  const client = ensureFirestoreConfigured(firestore);\n  if (client._uninitializedComponentsProvider?._offline.kind !== 'persistent') {\n    return null;\n  }\n\n  const instance = new PersistentCacheIndexManager(firestore);\n  persistentCacheIndexManagerByFirestore.set(firestore, instance);\n  return instance;\n}\n\n/**\n * Enables the SDK to create persistent cache indexes automatically for local\n * query execution when the SDK believes cache indexes can help improve\n * performance.\n *\n * This feature is disabled by default.\n */\nexport function enablePersistentCacheIndexAutoCreation(\n  indexManager: PersistentCacheIndexManager\n): void {\n  setPersistentCacheIndexAutoCreationEnabled(indexManager, true);\n}\n\n/**\n * Stops creating persistent cache indexes automatically for local query\n * execution. The indexes which have been created by calling\n * `enablePersistentCacheIndexAutoCreation()` still take effect.\n */\nexport function disablePersistentCacheIndexAutoCreation(\n  indexManager: PersistentCacheIndexManager\n): void {\n  setPersistentCacheIndexAutoCreationEnabled(indexManager, false);\n}\n\n/**\n * Removes all persistent cache indexes.\n *\n * Please note this function will also deletes indexes generated by\n * `setIndexConfiguration()`, which is deprecated.\n */\nexport function deleteAllPersistentCacheIndexes(\n  indexManager: PersistentCacheIndexManager\n): void {\n  const client = ensureFirestoreConfigured(indexManager._firestore);\n  const promise = firestoreClientDeleteAllFieldIndexes(client);\n\n  promise\n    .then(_ => logDebug('deleting all persistent cache indexes succeeded'))\n    .catch(error =>\n      logWarn('deleting all persistent cache indexes failed', error)\n    );\n}\n\nfunction setPersistentCacheIndexAutoCreationEnabled(\n  indexManager: PersistentCacheIndexManager,\n  isEnabled: boolean\n): void {\n  const client = ensureFirestoreConfigured(indexManager._firestore);\n  const promise = firestoreClientSetPersistentCacheIndexAutoCreationEnabled(\n    client,\n    isEnabled\n  );\n\n  promise\n    .then(_ =>\n      logDebug(\n        `setting persistent cache index auto creation ` +\n          `isEnabled=${isEnabled} succeeded`\n      )\n    )\n    .catch(error =>\n      logWarn(\n        `setting persistent cache index auto creation ` +\n          `isEnabled=${isEnabled} failed`,\n        error\n      )\n    );\n}\n\n/**\n * Maps `Firestore` instances to their corresponding\n * `PersistentCacheIndexManager` instances.\n *\n * Use a `WeakMap` so that the mapping will be automatically dropped when the\n * `Firestore` instance is garbage collected. This emulates a private member\n * as described in https://goo.gle/454yvug.\n */\nconst persistentCacheIndexManagerByFirestore = new WeakMap<\n  Firestore,\n  PersistentCacheIndexManager\n>();\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Unsubscribe } from '../api/reference_impl';\n\nimport {\n  setTestingHooksSpi,\n  ExistenceFilterMismatchInfo,\n  TestingHooksSpi\n} from './testing_hooks_spi';\n\n/**\n * Testing hooks for use by Firestore's integration test suite to reach into the\n * SDK internals to validate logic and behavior that is not visible from the\n * public API surface.\n *\n * @internal\n */\nexport class TestingHooks {\n  private constructor() {\n    throw new Error('instances of this class should not be created');\n  }\n\n  /**\n   * Registers a callback to be notified when an existence filter mismatch\n   * occurs in the Watch listen stream.\n   *\n   * The relative order in which callbacks are notified is unspecified; do not\n   * rely on any particular ordering. If a given callback is registered multiple\n   * times then it will be notified multiple times, once per registration.\n   *\n   * @param callback - the callback to invoke upon existence filter mismatch.\n   *\n   * @returns a function that, when called, unregisters the given callback; only\n   * the first invocation of the returned function does anything; all subsequent\n   * invocations do nothing.\n   */\n  static onExistenceFilterMismatch(\n    callback: ExistenceFilterMismatchCallback\n  ): Unsubscribe {\n    return TestingHooksSpiImpl.instance.onExistenceFilterMismatch(callback);\n  }\n}\n\n/**\n * The signature of callbacks registered with\n * `TestingUtils.onExistenceFilterMismatch()`.\n *\n * The return value, if any, is ignored.\n *\n * @internal\n */\nexport type ExistenceFilterMismatchCallback = (\n  info: ExistenceFilterMismatchInfo\n) => unknown;\n\n/**\n * The implementation of `TestingHooksSpi`.\n */\nclass TestingHooksSpiImpl implements TestingHooksSpi {\n  private readonly existenceFilterMismatchCallbacksById = new Map<\n    Symbol,\n    ExistenceFilterMismatchCallback\n  >();\n\n  private constructor() {}\n\n  static get instance(): TestingHooksSpiImpl {\n    if (!testingHooksSpiImplInstance) {\n      testingHooksSpiImplInstance = new TestingHooksSpiImpl();\n      setTestingHooksSpi(testingHooksSpiImplInstance);\n    }\n    return testingHooksSpiImplInstance;\n  }\n\n  notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void {\n    this.existenceFilterMismatchCallbacksById.forEach(callback =>\n      callback(info)\n    );\n  }\n\n  onExistenceFilterMismatch(\n    callback: ExistenceFilterMismatchCallback\n  ): Unsubscribe {\n    const id = Symbol();\n    const callbacks = this.existenceFilterMismatchCallbacksById;\n    callbacks.set(id, callback);\n    return () => callbacks.delete(id);\n  }\n}\n\nlet testingHooksSpiImplInstance: TestingHooksSpiImpl | null = null;\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerFirestore } from './register';\n\nregisterFirestore('node');\n\nexport * from './api';\n"],"names":["name","DocumentSnapshot","QueryDocumentSnapshot","LiteDocumentSnapshot","Transaction","LiteTransaction"],"mappings":";;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAmBa,SAAA,iBAAiB,CAC/B,OAAgB,EAChB,eAAe,GAAG,IAAI,EAAA;IAEtB,aAAa,CAAC,WAAW,CAAC,CAAC;AAC3B,IAAA,kBAAkB,CAChB,IAAI,SAAS,CACX,WAAW,EACX,CAAC,SAAS,EAAE,EAAE,kBAAkB,EAAE,UAAU,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAI;QACnE,MAAM,GAAG,GAAG,SAAS,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,YAAY,EAAG,CAAC;AACzD,QAAA,MAAM,iBAAiB,GAAG,IAAI,SAAS,CACrC,IAAI,+BAA+B,CACjC,SAAS,CAAC,WAAW,CAAC,eAAe,CAAC,CACvC,EACD,IAAI,6BAA6B,CAC/B,GAAG,EACH,SAAS,CAAC,WAAW,CAAC,oBAAoB,CAAC,C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