UNPKG

@firebase/firestore

Version:

The Cloud Firestore component of the Firebase JS SDK.

1,240 lines (1,163 loc) • 321 kB
/** * Cloud Firestore * * @packageDocumentation */ import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; import { EmulatorMockTokenOptions } from '@firebase/util'; import { FirebaseApp } from '@firebase/app'; import { FirebaseError } from '@firebase/util'; import { _FirebaseService } from '@firebase/app'; import { LogLevelString as LogLevel } from '@firebase/logger'; import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; /** * Converts Firestore's internal types to the JavaScript types that we expose * to the user. * * @internal */ export declare abstract class AbstractUserDataWriter { convertValue(value: Value, serverTimestampBehavior?: ServerTimestampBehavior): unknown; private convertObject; /** * @internal */ convertObjectMap(fields: ApiClientObjectMap<Value> | undefined, serverTimestampBehavior?: ServerTimestampBehavior): DocumentData_2; /** * @internal */ convertVectorValue(mapValue: MapValue): VectorValue; private convertGeoPoint; private convertArray; private convertServerTimestamp; private convertTimestamp; protected convertDocumentKey(name: string, expectedDatabaseId: _DatabaseId): _DocumentKey; protected abstract convertReference(name: string): unknown; protected abstract convertBytes(bytes: _ByteString): unknown; } /** * Describes a map whose keys are active target ids. We do not care about the type of the * values. */ declare type ActiveTargets = SortedMap<TargetId, unknown>; /** * Add a new document to specified `CollectionReference` with the given data, * assigning it a document ID automatically. * * @param reference - A reference to the collection to add this document to. * @param data - An Object containing the data for the new document. * @returns A `Promise` resolved with a `DocumentReference` pointing to the * newly created document after it has been written to the backend (Note that it * won't resolve while you're offline). */ export declare function addDoc<AppModelType, DbModelType extends DocumentData>(reference: CollectionReference<AppModelType, DbModelType>, data: WithFieldValue<AppModelType>): Promise<DocumentReference<AppModelType, DbModelType>>; /** * Returns a new map where every key is prefixed with the outer key appended * to a dot. */ export declare type AddPrefixToKeys<Prefix extends string, T extends Record<string, unknown>> = { [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; }; /** * Represents an aggregation that can be performed by Firestore. */ export declare class AggregateField<T> { readonly _internalFieldPath?: _FieldPath | undefined; /** A type string to uniquely identify instances of this class. */ readonly type = "AggregateField"; /** Indicates the aggregation operation of this AggregateField. */ readonly aggregateType: AggregateType; /** * Create a new AggregateField<T> * @param aggregateType Specifies the type of aggregation operation to perform. * @param _internalFieldPath Optionally specifies the field that is aggregated. * @internal */ constructor(aggregateType?: AggregateType, _internalFieldPath?: _FieldPath | undefined); } /** * Compares two 'AggregateField` instances for equality. * * @param left Compare this AggregateField to the `right`. * @param right Compare this AggregateField to the `left`. */ export declare function aggregateFieldEqual(left: AggregateField<unknown>, right: AggregateField<unknown>): boolean; /** * The union of all `AggregateField` types that are supported by Firestore. */ export declare type AggregateFieldType = ReturnType<typeof sum> | ReturnType<typeof average> | ReturnType<typeof count>; /** * The results of executing an aggregation query. */ export declare class AggregateQuerySnapshot<AggregateSpecType extends AggregateSpec, AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> { private readonly _userDataWriter; private readonly _data; /** A type string to uniquely identify instances of this class. */ readonly type = "AggregateQuerySnapshot"; /** * The underlying query over which the aggregations recorded in this * `AggregateQuerySnapshot` were performed. */ readonly query: Query<AppModelType, DbModelType>; /** @hideconstructor */ constructor(query: Query<AppModelType, DbModelType>, _userDataWriter: AbstractUserDataWriter, _data: ApiClientObjectMap<Value>); /** * Returns the results of the aggregations performed over the underlying * query. * * The keys of the returned object will be the same as those of the * `AggregateSpec` object specified to the aggregation method, and the values * will be the corresponding aggregation result. * * @returns The results of the aggregations performed over the underlying * query. */ data(): AggregateSpecData<AggregateSpecType>; } /** * Compares two `AggregateQuerySnapshot` instances for equality. * * Two `AggregateQuerySnapshot` instances are considered "equal" if they have * underlying queries that compare equal, and the same data. * * @param left - The first `AggregateQuerySnapshot` to compare. * @param right - The second `AggregateQuerySnapshot` to compare. * * @returns `true` if the objects are "equal", as defined above, or `false` * otherwise. */ export declare function aggregateQuerySnapshotEqual<AggregateSpecType extends AggregateSpec, AppModelType, DbModelType extends DocumentData>(left: AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>, right: AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>): boolean; /** * Specifies a set of aggregations and their aliases. */ export declare interface AggregateSpec { [field: string]: AggregateFieldType; } /** * A type whose keys are taken from an `AggregateSpec`, and whose values are the * result of the aggregation performed by the corresponding `AggregateField` * from the input `AggregateSpec`. */ export declare type AggregateSpecData<T extends AggregateSpec> = { [P in keyof T]: T[P] extends AggregateField<infer U> ? U : never; }; /** * Union type representing the aggregate type to be performed. */ export declare type AggregateType = 'count' | 'avg' | 'sum'; /** * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of * the given filter constraints. A conjunction filter includes a document if it * satisfies all of the given filters. * * @param queryConstraints - Optional. The list of * {@link QueryFilterConstraint}s to perform a conjunction for. These must be * created with calls to {@link where}, {@link or}, or {@link and}. * @returns The newly created {@link QueryCompositeFilterConstraint}. */ export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; declare interface ApiClientObjectMap<T> { [k: string]: T; } /** * An `AppliableConstraint` is an abstraction of a constraint that can be applied * to a Firestore query. */ declare abstract class AppliableConstraint { /** * Takes the provided {@link Query} and returns a copy of the {@link Query} with this * {@link AppliableConstraint} applied. */ abstract _apply<AppModelType, DbModelType extends DocumentData>(query: Query<AppModelType, DbModelType>): Query<AppModelType, DbModelType>; } /** * Returns a special value that can be used with {@link (setDoc:1)} or {@link * updateDoc:1} that tells the server to remove the given elements from any * array value that already exists on the server. All instances of each element * specified will be removed from the array. If the field being modified is not * already an array it will be overwritten with an empty array. * * @param elements - The elements to remove from the array. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or * `updateDoc()` */ export declare function arrayRemove(...elements: unknown[]): FieldValue; /** * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array * value that already exists on the server. Each specified element that doesn't * already exist in the array will be added to the end. If the field being * modified is not already an array it will be overwritten with an array * containing exactly the specified elements. * * @param elements - The elements to union into the array. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or * `updateDoc()`. */ export declare function arrayUnion(...elements: unknown[]): FieldValue; declare interface AsyncQueue { readonly isShuttingDown: boolean; /** * Adds a new operation to the queue without waiting for it to complete (i.e. * we ignore the Promise result). */ enqueueAndForget<T extends unknown>(op: () => Promise<T>): void; /** * Regardless if the queue has initialized shutdown, adds a new operation to the * queue without waiting for it to complete (i.e. we ignore the Promise result). */ enqueueAndForgetEvenWhileRestricted<T extends unknown>(op: () => Promise<T>): void; /** * Initialize the shutdown of this queue. Once this method is called, the * only possible way to request running an operation is through * `enqueueEvenWhileRestricted()`. * * @param purgeExistingTasks Whether already enqueued tasked should be * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults * to false. */ enterRestrictedMode(purgeExistingTasks?: boolean): void; /** * Adds a new operation to the queue. Returns a promise that will be resolved * when the promise returned by the new operation is (with its value). */ enqueue<T extends unknown>(op: () => Promise<T>): Promise<T>; /** * Enqueue a retryable operation. * * A retryable operation is rescheduled with backoff if it fails with a * IndexedDbTransactionError (the error type used by SimpleDb). All * retryable operations are executed in order and only run if all prior * operations were retried successfully. */ enqueueRetryable(op: () => Promise<void>): void; /** * Schedules an operation to be queued on the AsyncQueue once the specified * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel * or fast-forward the operation prior to its running. */ enqueueAfterDelay<T extends unknown>(timerId: TimerId, delayMs: number, op: () => Promise<T>): DelayedOperation<T>; /** * Verifies there's an operation currently in-progress on the AsyncQueue. * Unfortunately we can't verify that the running code is in the promise chain * of that operation, so this isn't a foolproof check, but it should be enough * to catch some bugs. */ verifyOperationInProgress(): void; } /** * @internal */ export declare type AuthTokenFactory = () => string; /** * A utility class for generating unique alphanumeric IDs of a specified length. * * @internal * Exported internally for testing purposes. */ export declare class _AutoId { static newId(): string; } /** * Create an AggregateField object that can be used to compute the average of * a specified field over a range of documents in the result set of a query. * @param field Specifies the field to average across the result set. */ export declare function average(field: string | FieldPath): AggregateField<number | null>; /** * Path represents an ordered sequence of string segments. */ declare abstract class BasePath<B extends BasePath<B>> { private segments; private offset; private len; constructor(segments: string[], offset?: number, length?: number); /** * Abstract constructor method to construct an instance of B with the given * parameters. */ protected abstract construct(segments: string[], offset?: number, length?: number): B; /** * Returns a String representation. * * Implementing classes are required to provide deterministic implementations as * the String representation is used to obtain canonical Query IDs. */ abstract toString(): string; get length(): number; isEqual(other: B): boolean; child(nameOrPath: string | B): B; /** The index of one past the last segment of the path. */ private limit; popFirst(size?: number): B; popLast(): B; firstSegment(): string; lastSegment(): string; get(index: number): string; isEmpty(): boolean; isPrefixOf(other: this): boolean; isImmediateParentOf(potentialChild: this): boolean; forEach(fn: (segment: string) => void): void; toArray(): string[]; /** * Compare 2 paths segment by segment, prioritizing numeric IDs * (e.g., "__id123__") in numeric ascending order, followed by string * segments in lexicographical order. */ static comparator<T extends BasePath<T>>(p1: BasePath<T>, p2: BasePath<T>): number; private static compareSegments; private static isNumericId; private static extractNumericId; } /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * BatchID is a locally assigned ID for a batch of mutations that have been * applied. */ declare type BatchId = number; /** * Represents a bound of a query. * * The bound is specified with the given components representing a position and * whether it's just before or just after the position (relative to whatever the * query order is). * * The position represents a logical index position for a query. It's a prefix * of values for the (potentially implicit) order by clauses of a query. * * Bound provides a function to determine whether a document comes before or * after a bound. This is influenced by whether the position is just before or * just after the provided values. */ declare class Bound { readonly position: Value[]; readonly inclusive: boolean; constructor(position: Value[], inclusive: boolean); } /** * Provides interfaces to save and read Firestore bundles. */ declare interface BundleCache { /** * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined * if no bundle metadata is found under the given id. */ getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise<BundleMetadata | undefined>; /** * Saves a `BundleMetadata` from a bundle into local storage, using its id as * the persistent key. */ saveBundleMetadata(transaction: PersistenceTransaction, metadata: BundleMetadata_2): PersistencePromise<void>; /** * Gets a saved `NamedQuery` for the given query name. Returns undefined if * no queries are found under the given name. */ getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise<NamedQuery | undefined>; /** * Saves a `NamedQuery` from a bundle, using its name as the persistent key. */ saveNamedQuery(transaction: PersistenceTransaction, query: NamedQuery_2): PersistencePromise<void>; } /** Properties of a BundledQuery. */ declare interface BundledQuery { /** BundledQuery parent */ parent?: string | null; /** BundledQuery structuredQuery */ structuredQuery?: StructuredQuery | null; /** BundledQuery limitType */ limitType?: LimitType_2 | null; } /** * Represents a Firestore bundle saved by the SDK in its local storage. */ declare interface BundleMetadata { /** * Id of the bundle. It is used together with `createTime` to determine if a * bundle has been loaded by the SDK. */ readonly id: string; /** Schema version of the bundle. */ readonly version: number; /** * Set to the snapshot version of the bundle if created by the Server SDKs. * Otherwise set to SnapshotVersion.MIN. */ readonly createTime: SnapshotVersion; } /** Properties of a BundleMetadata. */ declare interface BundleMetadata_2 { /** BundleMetadata id */ id?: string | null; /** BundleMetadata createTime */ createTime?: Timestamp_2 | null; /** BundleMetadata version */ version?: number | null; /** BundleMetadata totalDocuments */ totalDocuments?: number | null; /** BundleMetadata totalBytes */ totalBytes?: number | null; } /** * An immutable object representing an array of bytes. */ export declare class Bytes { _byteString: _ByteString; /** @hideconstructor */ constructor(byteString: _ByteString); /** * Creates a new `Bytes` object from the given Base64 string, converting it to * bytes. * * @param base64 - The Base64 string used to create the `Bytes` object. */ static fromBase64String(base64: string): Bytes; /** * Creates a new `Bytes` object from the given Uint8Array. * * @param array - The Uint8Array used to create the `Bytes` object. */ static fromUint8Array(array: Uint8Array): Bytes; /** * Returns the underlying bytes as a Base64-encoded string. * * @returns The Base64-encoded string created from the `Bytes` object. */ toBase64(): string; /** * Returns the underlying bytes in a new `Uint8Array`. * * @returns The Uint8Array created from the `Bytes` object. */ toUint8Array(): Uint8Array; /** * Returns a string representation of the `Bytes` object. * * @returns A string representation of the `Bytes` object. */ toString(): string; /** * Returns true if this `Bytes` object is equal to the provided one. * * @param other - The `Bytes` object to compare against. * @returns true if this `Bytes` object is equal to the provided one. */ isEqual(other: Bytes): boolean; } /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Immutable class that represents a "proto" byte string. * * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when * sent on the wire. This class abstracts away this differentiation by holding * the proto byte string in a common class that must be converted into a string * before being sent as a proto. * @internal */ export declare class _ByteString { private readonly binaryString; static readonly EMPTY_BYTE_STRING: _ByteString; private constructor(); static fromBase64String(base64: string): _ByteString; static fromUint8Array(array: Uint8Array): _ByteString; [Symbol.iterator](): Iterator<number>; toBase64(): string; toUint8Array(): Uint8Array; approximateByteSize(): number; compareTo(other: _ByteString): number; isEqual(other: _ByteString): boolean; } /** * Constant used to indicate the LRU garbage collection should be disabled. * Set this value as the `cacheSizeBytes` on the settings passed to the * {@link Firestore} instance. */ export declare const CACHE_SIZE_UNLIMITED = -1; /** * Casts `obj` to `T`, optionally unwrapping Compat types to expose the * underlying instance. Throws if `obj` is not an instance of `T`. * * This cast is used in the Lite and Full SDK to verify instance types for * arguments passed to the public API. * @internal */ export declare function _cast<T>(obj: object, constructor: { new (...args: any[]): T; }): T | never; declare const enum ChangeType { Added = 0, Removed = 1, Modified = 2, Metadata = 3 } /** * Helper for calculating the nested fields for a given type T1. This is needed * to distribute union types such as `undefined | {...}` (happens for optional * props) or `{a: A} | {b: B}`. * * In this use case, `V` is used to distribute the union types of `T[K]` on * `Record`, since `T[K]` is evaluated as an expression and not distributed. * * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types */ export declare type ChildUpdateFields<K extends string, V> = V extends Record<string, unknown> ? AddPrefixToKeys<K, UpdateData<V>> : never; /** * Clears the persistent storage. This includes pending writes and cached * documents. * * Must be called while the {@link Firestore} instance is not started (after the app is * terminated or when the app is first initialized). On startup, this function * must be called before other functions (other than {@link * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} * instance is still running, the promise will be rejected with the error code * of `failed-precondition`. * * Note: `clearIndexedDbPersistence()` is primarily intended to help write * reliable tests that use Cloud Firestore. It uses an efficient mechanism for * dropping existing data but does not attempt to securely overwrite or * otherwise make cached data unrecoverable. For applications that are sensitive * to the disclosure of cached data in between user sessions, we strongly * recommend not enabling persistence at all. * * @param firestore - The {@link Firestore} instance to clear persistence for. * @returns A `Promise` that is resolved when the persistent storage is * cleared. Otherwise, the promise is rejected with an error. */ export declare function clearIndexedDbPersistence(firestore: Firestore): Promise<void>; /** * A randomly-generated key assigned to each Firestore instance at startup. */ declare type ClientId = string; /** * Gets a `CollectionReference` instance that refers to the collection at * the specified absolute path. * * @param firestore - A reference to the root `Firestore` instance. * @param path - A slash-separated path to a collection. * @param pathSegments - Additional path segments to apply relative to the first * argument. * @throws If the final path has an even number of segments and does not point * to a collection. * @returns The `CollectionReference` instance. */ export declare function collection(firestore: Firestore_2, path: string, ...pathSegments: string[]): CollectionReference<DocumentData, DocumentData>; /** * Gets a `CollectionReference` instance that refers to a subcollection of * `reference` at the specified relative path. * * @param reference - A reference to a collection. * @param path - A slash-separated path to a collection. * @param pathSegments - Additional path segments to apply relative to the first * argument. * @throws If the final path has an even number of segments and does not point * to a collection. * @returns The `CollectionReference` instance. */ export declare function collection<AppModelType, DbModelType extends DocumentData>(reference: CollectionReference<AppModelType, DbModelType>, path: string, ...pathSegments: string[]): CollectionReference<DocumentData, DocumentData>; /** * Gets a `CollectionReference` instance that refers to a subcollection of * `reference` at the specified relative path. * * @param reference - A reference to a Firestore document. * @param path - A slash-separated path to a collection. * @param pathSegments - Additional path segments that will be applied relative * to the first argument. * @throws If the final path has an even number of segments and does not point * to a collection. * @returns The `CollectionReference` instance. */ export declare function collection<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>, path: string, ...pathSegments: string[]): CollectionReference<DocumentData, DocumentData>; /** * Creates and returns a new `Query` instance that includes all documents in the * database that are contained in a collection or subcollection with the * given `collectionId`. * * @param firestore - A reference to the root `Firestore` instance. * @param collectionId - Identifies the collections to query over. Every * collection or subcollection with this ID as the last segment of its path * will be included. Cannot contain a slash. * @returns The created `Query`. */ export declare function collectionGroup(firestore: Firestore_2, collectionId: string): Query<DocumentData, DocumentData>; /** * A `CollectionReference` object can be used for adding documents, getting * document references, and querying for documents (using {@link (query:1)}). */ export declare class CollectionReference<AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> extends Query<AppModelType, DbModelType> { readonly _path: _ResourcePath; /** The type of this Firestore reference. */ readonly type = "collection"; /** @hideconstructor */ constructor(firestore: Firestore_2, converter: FirestoreDataConverter_2<AppModelType, DbModelType> | null, _path: _ResourcePath); /** The collection's identifier. */ get id(): string; /** * A string representing the path of the referenced collection (relative * to the root of the database). */ get path(): string; /** * A reference to the containing `DocumentReference` if this is a * subcollection. If this isn't a subcollection, the reference is null. */ get parent(): DocumentReference<DocumentData, DocumentData> | null; /** * Applies a custom data converter to this `CollectionReference`, allowing you * to use your own custom model objects with Firestore. When you call {@link * addDoc} with the returned `CollectionReference` instance, the provided * converter will convert between Firestore data of type `NewDbModelType` and * your custom type `NewAppModelType`. * * @param converter - Converts objects to and from Firestore. * @returns A `CollectionReference` that uses the provided converter. */ withConverter<NewAppModelType, NewDbModelType extends DocumentData = DocumentData>(converter: FirestoreDataConverter_2<NewAppModelType, NewDbModelType>): CollectionReference<NewAppModelType, NewDbModelType>; /** * Removes the current converter. * * @param converter - `null` removes the current converter. * @returns A `CollectionReference<DocumentData, DocumentData>` that does not * use a converter. */ withConverter(converter: null): CollectionReference<DocumentData, DocumentData>; } /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ declare type Comparator<K> = (key1: K, key2: K) => number; declare interface ComponentConfiguration { asyncQueue: AsyncQueue; databaseInfo: DatabaseInfo; authCredentials: CredentialsProvider<User>; appCheckCredentials: CredentialsProvider<string>; clientId: ClientId; initialUser: User; maxConcurrentLimboResolutions: number; } declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; declare const enum CompositeOperator { OR = "or", AND = "and" } /** * Modify this instance to communicate with the Cloud Firestore emulator. * * Note: This must be called before this instance has been used to do any * operations. * * @param firestore - The `Firestore` instance to configure to connect to the * emulator. * @param host - the emulator host (ex: localhost). * @param port - the emulator port (ex: 9000). * @param options.mockUserToken - the mock auth token to use for unit testing * Security Rules. */ export declare function connectFirestoreEmulator(firestore: Firestore_2, host: string, port: number, options?: { mockUserToken?: EmulatorMockTokenOptions | string; }): void; /** * Create an AggregateField object that can be used to compute the count of * documents in the result set of a query. */ export declare function count(): AggregateField<number>; /** * A Listener for credential change events. The listener should fetch a new * token and may need to invalidate other state if the current user has also * changed. */ declare type CredentialChangeListener<T> = (credential: T) => Promise<void>; /** * Provides methods for getting the uid and token for the current user and * listening for changes. */ declare interface CredentialsProvider<T> { /** * Starts the credentials provider and specifies a listener to be notified of * credential changes (sign-in / sign-out, token changes). It is immediately * called once with the initial user. * * The change listener is invoked on the provided AsyncQueue. */ start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener<T>): void; /** Requests a token for the current user. */ getToken(): Promise<Token | null>; /** * Marks the last retrieved token as invalid, making the next GetToken request * force-refresh the token. */ invalidateToken(): void; shutdown(): void; } /** Settings for private credentials */ declare type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings; /** * Represents the database ID a Firestore client is associated with. * @internal */ export declare class _DatabaseId { readonly projectId: string; readonly database: string; constructor(projectId: string, database?: string); static empty(): _DatabaseId; get isDefaultDatabase(): boolean; isEqual(other: {}): boolean; } /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ declare class DatabaseInfo { readonly databaseId: _DatabaseId; readonly appId: string; readonly persistenceKey: string; readonly host: string; readonly ssl: boolean; readonly forceLongPolling: boolean; readonly autoDetectLongPolling: boolean; readonly longPollingOptions: ExperimentalLongPollingOptions; readonly useFetchStreams: boolean; readonly isUsingEmulator: boolean; /** * Constructs a DatabaseInfo using the provided host, databaseId and * persistenceKey. * * @param databaseId - The database to use. * @param appId - The Firebase App Id. * @param persistenceKey - A unique identifier for this Firestore's local * storage (used in conjunction with the databaseId). * @param host - The Firestore backend host to connect to. * @param ssl - Whether to use SSL when connecting. * @param forceLongPolling - Whether to use the forceLongPolling option * when using WebChannel as the network transport. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy * option when using WebChannel as the network transport. * @param longPollingOptions Options that configure long-polling. * @param useFetchStreams Whether to use the Fetch API instead of * XMLHTTPRequest */ constructor(databaseId: _DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, longPollingOptions: ExperimentalLongPollingOptions, useFetchStreams: boolean, isUsingEmulator: boolean); } /** * Datastore and its related methods are a wrapper around the external Google * Cloud Datastore grpc API, which provides an interface that is more convenient * for the rest of the client SDK architecture to consume. */ declare abstract class Datastore { abstract terminate(): void; abstract serializer: JsonProtoSerializer; } /** * Fails if the given assertion condition is false, throwing an Error with the * given message if it did. * * The code of callsites invoking this function are stripped out in production * builds. Any side-effects of code within the debugAssert() invocation will not * happen in this case. * * @internal */ export declare function _debugAssert(assertion: boolean, message: string): asserts assertion; /** * Represents an operation scheduled to be run in the future on an AsyncQueue. * * It is created via DelayedOperation.createAndSchedule(). * * Supports cancellation (via cancel()) and early execution (via skipDelay()). * * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type * in newer versions of TypeScript defines `finally`, which is not available in * IE. */ declare class DelayedOperation<T extends unknown> implements PromiseLike<T> { private readonly asyncQueue; readonly timerId: TimerId; readonly targetTimeMs: number; private readonly op; private readonly removalCallback; private timerHandle; private readonly deferred; private constructor(); get promise(): Promise<T>; /** * Creates and returns a DelayedOperation that has been scheduled to be * executed on the provided asyncQueue after the provided delayMs. * * @param asyncQueue - The queue to schedule the operation on. * @param id - A Timer ID identifying the type of operation this is. * @param delayMs - The delay (ms) before the operation should be scheduled. * @param op - The operation to run. * @param removalCallback - A callback to be called synchronously once the * operation is executed or canceled, notifying the AsyncQueue to remove it * from its delayedOperations list. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and * the DelayedOperation class public. */ static createAndSchedule<R extends unknown>(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise<R>, removalCallback: (op: DelayedOperation<R>) => void): DelayedOperation<R>; /** * Starts the timer. This is called immediately after construction by * createAndSchedule(). */ private start; /** * Queues the operation to run immediately (if it hasn't already been run or * canceled). */ skipDelay(): void; /** * Cancels the operation if it hasn't already been executed or canceled. The * promise will be rejected. * * As long as the operation has not yet been run, calling cancel() provides a * guarantee that the operation will not be run. */ cancel(reason?: string): void; then: <TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined) => Promise<TResult1 | TResult2>; private handleDelayElapsed; private clearTimeout; } /** * Removes all persistent cache indexes. * * Please note this function will also deletes indexes generated by * `setIndexConfiguration()`, which is deprecated. */ export declare function deleteAllPersistentCacheIndexes(indexManager: PersistentCacheIndexManager): void; /** * Deletes the document referred to by the specified `DocumentReference`. * * @param reference - A reference to the document to delete. * @returns A Promise resolved once the document has been successfully * deleted from the backend (note that it won't resolve while you're offline). */ export declare function deleteDoc<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>): Promise<void>; /** * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. */ export declare function deleteField(): FieldValue; /** * The direction of sorting in an order by. */ declare const enum Direction { ASCENDING = "asc", DESCENDING = "desc" } /** * Disables network usage for this instance. It can be re-enabled via {@link * enableNetwork}. While the network is disabled, any snapshot listeners, * `getDoc()` or `getDocs()` calls will return results from cache, and any write * operations will be queued until the network is restored. * * @returns A `Promise` that is resolved once the network has been disabled. */ export declare function disableNetwork(firestore: Firestore): Promise<void>; /** * Stops creating persistent cache indexes automatically for local query * execution. The indexes which have been created by calling * `enablePersistentCacheIndexAutoCreation()` still take effect. */ export declare function disablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; /** * Gets a `DocumentReference` instance that refers to the document at the * specified absolute path. * * @param firestore - A reference to the root `Firestore` instance. * @param path - A slash-separated path to a document. * @param pathSegments - Additional path segments that will be applied relative * to the first argument. * @throws If the final path has an odd number of segments and does not point to * a document. * @returns The `DocumentReference` instance. */ export declare function doc(firestore: Firestore_2, path: string, ...pathSegments: string[]): DocumentReference<DocumentData, DocumentData>; /** * Gets a `DocumentReference` instance that refers to a document within * `reference` at the specified relative path. If no path is specified, an * automatically-generated unique ID will be used for the returned * `DocumentReference`. * * @param reference - A reference to a collection. * @param path - A slash-separated path to a document. Has to be omitted to use * auto-generated IDs. * @param pathSegments - Additional path segments that will be applied relative * to the first argument. * @throws If the final path has an odd number of segments and does not point to * a document. * @returns The `DocumentReference` instance. */ export declare function doc<AppModelType, DbModelType extends DocumentData>(reference: CollectionReference<AppModelType, DbModelType>, path?: string, ...pathSegments: string[]): DocumentReference<AppModelType, DbModelType>; /** * Gets a `DocumentReference` instance that refers to a document within * `reference` at the specified relative path. * * @param reference - A reference to a Firestore document. * @param path - A slash-separated path to a document. * @param pathSegments - Additional path segments that will be applied relative * to the first argument. * @throws If the final path has an odd number of segments and does not point to * a document. * @returns The `DocumentReference` instance. */ export declare function doc<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>, path: string, ...pathSegments: string[]): DocumentReference<DocumentData, DocumentData>; /** * Represents a document in Firestore with a key, version, data and whether the * data has local mutations applied to it. */ declare interface Document_2 { /** The key for this document */ readonly key: _DocumentKey; /** * The version of this document if it exists or a version at which this * document was guaranteed to not exist. */ readonly version: SnapshotVersion; /** * The timestamp at which this document was read from the remote server. Uses * `SnapshotVersion.min()` for documents created by the user. */ readonly readTime: SnapshotVersion; /** * The timestamp at which the document was created. This value increases * monotonically when a document is deleted then recreated. It can also be * compared to `createTime` of other documents and the `readTime` of a query. */ readonly createTime: SnapshotVersion; /** The underlying data of this document or an empty value if no data exists. */ readonly data: ObjectValue; /** Returns whether local mutations were applied via the mutation queue. */ readonly hasLocalMutations: boolean; /** Returns whether mutations were applied based on a write acknowledgment. */ readonly hasCommittedMutations: boolean; /** * Whether this document had a local mutation applied that has not yet been * acknowledged by Watch. */ readonly hasPendingWrites: boolean; /** * Returns whether this document is valid (i.e. it is an entry in the * RemoteDocumentCache, was created by a mutation or read from the backend). */ isValidDocument(): boolean; /** * Returns whether the document exists and its data is known at the current * version. */ isFoundDocument(): boolean; /** * Returns whether the document is known to not exist at the current version. */ isNoDocument(): boolean; /** * Returns whether the document exists and its data is unknown at the current * version. */ isUnknownDocument(): boolean; isEqual(other: Document_2 | null | undefined): boolean; /** Creates a mutable copy of this document. */ mutableCopy(): MutableDocument; toString(): string; } /** * A `DocumentChange` represents a change to the documents matching a query. * It contains the document affected and the type of change that occurred. */ export declare interface DocumentChange<AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> { /** The type of change ('added', 'modified', or 'removed'). */ readonly type: DocumentChangeType; /** The document affected by this change. */ readonly doc: QueryDocumentSnapshot<AppModelType, DbModelType>; /** * The index of the changed document in the result set immediately prior to * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects * have been applied). Is `-1` for 'added' events. */ readonly oldIndex: number; /** * The index of the changed document in the result set immediately after * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` * objects and the current `DocumentChange` object have been applied). * Is -1 for 'removed' events. */ readonly newIndex: number; } /** * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'. */ export declare type DocumentChangeType = 'added' | 'removed' | 'modified'; declare type DocumentComparator = (doc1: Document_2, doc2: Document_2) => number; /** * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to * values. */ export declare interface DocumentData { /** A mapping between a field and its value. */ [field: string]: any; } /** * Returns a special sentinel `FieldPath` to refer to the ID of a document. * It can be used in queries to sort or filter by the document ID. */ export declare function documentId(): FieldPath; /** * @internal */ export declare class _DocumentKey { readonly path: _ResourcePath; constructor(path: _ResourcePath); static fromPath(path: string): _DocumentKey; static fromName(name: string): _DocumentKey; static empty(): _DocumentKey; get collectionGroup(): string; /** Returns true if the document is in the specified collectionId. */ hasCollectionId(collectionId: string): boolean; /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup(): string; /** Returns the fully qualified path to the parent collection. */ getCollectionPath(): _ResourcePath; isEqual(other: _DocumentKey | null): boolean; toString(): string; static comparator(k1: _DocumentKey, k2: _DocumentKey): number; static isDocumentKey(path: _ResourcePath): boolean; /** * Creates and returns a new document key with the given segments. * * @param segments - The segments of the path to the document * @returns A new instance of DocumentKey */ static fromSegments(segments: string[]): _DocumentKey; } declare type DocumentKeyMap<T> = ObjectMap<_DocumentKey, T>; declare type DocumentKeySet = SortedSet<_DocumentKey>; declare type DocumentMap = SortedMap<_DocumentKey, Document_2>; /** * Provides methods to read and write document overlays. * * An overlay is a saved mutation, that gives a local view of a document when * applied to the remote version of the document. * * Each overlay stores the largest batch ID that is included in the overlay, * which allows us to remove the overlay once all batches leading up to it have * been acknowledged. */ declare interface DocumentOverlayCache { /** * Gets the saved overlay mutation for the given document key. * Returns null if there is no overlay for that key. */ getOverlay(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise<Overlay | null>; /** * Gets the saved overlay mutation for the given document keys. Skips keys for * which there are no overlays. */ getOverlays(transaction: PersistenceTransaction, keys: _DocumentKey[]): PersistencePromise<OverlayMap>; /** * Saves the given document mutation map to persistence as overlays. * All overlays will have their largest batch id set to `largestBatchId`. */ saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise<void>; /** Removes overlays for the given document keys and batch ID. */ removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise<void>; /** * Returns all saved overlays for the given collection. * * @param transaction - The persistence transaction to use for this operation. * @param collection - The collection path to get the overlays for. * @param sinceBatchId - The minimum batch ID to filter by (exclusive). * Only overlays that contain a change past `sinceBatchId` are returned. * @returns Mapping of each document key in the collection to its overlay. */ getOverlaysForCollection(transaction: PersistenceTransaction, collection: _ResourcePath, sinceBatchId: number): PersistencePromise<OverlayMap>; /** * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the * provided collection group, processed by ascending batch ID. The method * always returns all overlays for a batch even if the last batch contains * more documents than the remaining limit. * * @param transaction - The persistence transaction used for this operation. * @param collectionGroup - The collection group to get the overlays for. * @param sinceBatchId - The minimum batch ID to filter by (exclusive). * Only overlays that contain a change past `sinceBatchId` are returned. * @param count - The number of overlays to return. Can be exceeded if the last * batch contains more entries. * @return Mapping of each document key in the collection group to its overlay. */ getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise<OverlayMap>; } /** * A `DocumentReference` refers to a document location in a Firestore database * and can be used to write, read, or listen to the location. The document at * the referenced location may or may not exist. */ export declare class DocumentReference<AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> { /** * If provided, the `FirestoreDataConverter` associated with this instance. */ readonly converter: FirestoreDataConverter_2<AppModelType, DbModelType> | null; readonly _key: _DocumentKey; /** The type of this Firestore reference. */ readonly type = "document"; /** * The {@link Firestore} instance the document is in. * This is useful for performing transactions, for example. */ readonly firestore: Firestore_2; /** @hideconstructor */ constructor(firestore: Firestore_2, /** * If provided, the `FirestoreDataConverter` associated with this instance. */ converter: FirestoreDataConve