@firebase/firestore
Version:
The Cloud Firestore component of the Firebase JS SDK.
1,236 lines (1,164 loc) • 222 kB
TypeScript
/**
* Cloud Firestore
*
* @packageDocumentation
*/
import { DocumentData as DocumentData_2 } from '@firebase/firestore-types';
import { EmulatorMockTokenOptions } from '@firebase/util';
import { FirebaseApp } from '@firebase/app-exp';
import { FirebaseAuthInternalName } from '@firebase/auth-interop-types';
import { _FirebaseService } from '@firebase/app-exp';
import { LogLevelString as LogLevel } from '@firebase/logger';
import { Provider } from '@firebase/component';
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;
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<T>(reference: CollectionReference<T>, data: T): Promise<DocumentReference<T>>;
declare interface ApiClientObjectMap<T> {
[k: string]: T;
}
/**
* Returns a special value that can be used with {@link (setDoc:1)} or {@link
* updateDoc:1} that tells the server to remove the given elements from any
* array value that already exists on the server. All instances of each element
* specified will be removed from the array. If the field being modified is not
* already an array it will be overwritten with an empty array.
*
* @param elements - The elements to remove from the array.
* @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
* `updateDoc()`
*/
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()`.
*/
enterRestrictedMode(): 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;
}
/**
* 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[];
static comparator<T extends BasePath<T>>(p1: BasePath<T>, p2: BasePath<T>): number;
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 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 before: boolean;
constructor(position: Value[], before: 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.
*/
declare class ByteString {
private readonly binaryString;
static readonly EMPTY_BYTE_STRING: ByteString;
private constructor();
static fromBase64String(base64: string): ByteString;
static fromUint8Array(array: Uint8Array): ByteString;
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
* `Firestore` instance.
*/
export declare const CACHE_SIZE_UNLIMITED = -1;
declare const enum ChangeType {
Added = 0,
Removed = 1,
Modified = 2,
Metadata = 3
}
/**
* Clears the persistent storage. This includes pending writes and cached
* documents.
*
* Must be called while the `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})). If the `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 `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: FirebaseFirestore): 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: FirebaseFirestore_2, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;
/**
* Gets a `CollectionReference` instance that refers to a subcollection of
* `reference` at the the specified relative path.
*
* @param reference - A reference to a collection.
* @param path - A slash-separated path to a collection.
* @param pathSegments - Additional path segments to apply relative to the first
* argument.
* @throws If the final path has an even number of segments and does not point
* to a collection.
* @returns The `CollectionReference` instance.
*/
export declare function collection(reference: CollectionReference<unknown>, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;
/**
* Gets a `CollectionReference` instance that refers to a subcollection of
* `reference` at the the specified relative path.
*
* @param reference - A reference to a Firestore document.
* @param path - A slash-separated path to a collection.
* @param pathSegments - Additional path segments that will be applied relative
* to the first argument.
* @throws If the final path has an even number of segments and does not point
* to a collection.
* @returns The `CollectionReference` instance.
*/
export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference<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: FirebaseFirestore_2, collectionId: string): Query<DocumentData>;
/**
* A `CollectionReference` object can be used for adding documents, getting
* document references, and querying for documents (using {@link query}).
*/
export declare class CollectionReference<T = DocumentData> extends Query<T> {
readonly _path: ResourcePath;
/** The type of this Firestore reference. */
readonly type = "collection";
/** @hideconstructor */
constructor(firestore: FirebaseFirestore_2, converter: FirestoreDataConverter_2<T> | 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> | 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 and your custom type `U`.
*
* @param converter - Converts objects to and from Firestore.
* @returns A `CollectionReference<U>` that uses the provided converter.
*/
withConverter<U>(converter: FirestoreDataConverter_2<U>): CollectionReference<U>;
/**
* Removes the current converter.
*
* @param converter - `null` removes the current converter.
* @returns A `CollectionReference<DocumentData>` that does not use a
* converter.
*/
withConverter(converter: null): CollectionReference<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;
credentials: CredentialsProvider;
clientId: ClientId;
initialUser: User;
maxConcurrentLimboResolutions: number;
}
declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND';
/**
* 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 = (user: User) => Promise<void>;
/**
* Provides methods for getting the uid and token for the current user and
* listening for changes.
*/
declare interface CredentialsProvider {
/** 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;
/**
* 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.
*/
setChangeListener(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void;
/** Removes the previously-set change listener. */
removeChangeListener(): void;
}
/** Settings for private credentials */
declare type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings;
/** Represents the database ID a Firestore client is associated with. */
declare class DatabaseId {
readonly projectId: string;
readonly database: string;
constructor(projectId: string, database?: string);
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 useFetchStreams: 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 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, useFetchStreams: 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;
}
/**
* 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();
/**
* 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;
}
/**
* Deletes the document referred to by the specified `DocumentReference`.
*
* @param reference - A reference to the document to delete.
* @returns A Promise resolved once the document has been successfully
* deleted from the backend (note that it won't resolve while you're offline).
*/
export declare function deleteDoc(reference: DocumentReference<unknown>): 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: FirebaseFirestore): Promise<void>;
/**
* Gets a `DocumentReference` instance that refers to the document at the
* specified abosulute 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: FirebaseFirestore_2, path: string, ...pathSegments: string[]): DocumentReference<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-genrated 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<T>(reference: CollectionReference<T>, path?: string, ...pathSegments: string[]): DocumentReference<T>;
/**
* Gets a `DocumentReference` instance that refers to a document within
* `reference` at the specified relative path.
*
* @param reference - A reference to a Firestore document.
* @param path - A slash-separated path to a document.
* @param pathSegments - Additional path segments that will be applied relative
* to the first argument.
* @throws If the final path has an odd number of segments and does not point to
* a document.
* @returns The `DocumentReference` instance.
*/
export declare function doc(reference: DocumentReference<unknown>, path: string, ...pathSegments: string[]): DocumentReference<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 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;
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<T = DocumentData> {
/** The type of change ('added', 'modified', or 'removed'). */
readonly type: DocumentChangeType;
/** The document affected by this change. */
readonly doc: QueryDocumentSnapshot<T>;
/**
* 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;
declare class DocumentKey {
readonly path: ResourcePath;
constructor(path: ResourcePath);
static fromPath(path: string): DocumentKey;
static fromName(name: string): DocumentKey;
/** Returns true if the document is in the specified collectionId. */
hasCollectionId(collectionId: string): boolean;
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 DocumentKeySet = SortedSet<DocumentKey>;
declare type DocumentMap = SortedMap<DocumentKey, Document_2>;
/**
* 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<T = DocumentData> {
/**
* If provided, the `FirestoreDataConverter` associated with this instance.
*/
readonly converter: FirestoreDataConverter_2<T> | null;
readonly _key: DocumentKey;
/** The type of this Firestore reference. */
readonly type = "document";
/**
* The {@link FirebaseFirestore} the document is in.
* This is useful for performing transactions, for example.
*/
readonly firestore: FirebaseFirestore_2;
/** @hideconstructor */
constructor(firestore: FirebaseFirestore_2,
/**
* If provided, the `FirestoreDataConverter` associated with this instance.
*/
converter: FirestoreDataConverter_2<T> | null, _key: DocumentKey);
get _path(): ResourcePath;
/**
* The document's identifier within its collection.
*/
get id(): string;
/**
* A string representing the path of the referenced document (relative
* to the root of the database).
*/
get path(): string;
/**
* The collection this `DocumentReference` belongs to.
*/
get parent(): CollectionReference<T>;
/**
* Applies a custom data converter to this `DocumentReference`, allowing you
* to use your own custom model objects with Firestore. When you call {@link
* @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`
* instance, the provided converter will convert between Firestore data and
* your custom type `U`.
*
* @param converter - Converts objects to and from Firestore.
* @returns A `DocumentReference<U>` that uses the provided converter.
*/
withConverter<U>(converter: FirestoreDataConverter_2<U>): DocumentReference<U>;
/**
* Removes the current converter.
*
* @param converter - `null` removes the current converter.
* @returns A `DocumentReference<DocumentData>` that does not use a converter.
*/
withConverter(converter: null): DocumentReference<DocumentData>;
}
/**
* DocumentSet is an immutable (copy-on-write) collection that holds documents
* in order specified by the provided comparator. We always add a document key
* comparator on top of what is provided to guarantee document equality based on
* the key.
*/
declare class DocumentSet {
/**
* Returns an empty copy of the existing DocumentSet, using the same
* comparator.
*/
static emptySet(oldSet: DocumentSet): DocumentSet;
private comparator;
private keyedMap;
private sortedSet;
/** The default ordering is by key if the comparator is omitted */
constructor(comp?: DocumentComparator);
has(key: DocumentKey): boolean;
get(key: DocumentKey): Document_2 | null;
first(): Document_2 | null;
last(): Document_2 | null;
isEmpty(): boolean;
/**
* Returns the index of the provided key in the document set, or -1 if the
* document key is not present in the set;
*/
indexOf(key: DocumentKey): number;
get size(): number;
/** Iterates documents in order defined by "comparator" */
forEach(cb: (doc: Document_2) => void): void;
/** Inserts or updates a document with the same key */
add(doc: Document_2): DocumentSet;
/** Deletes a document with a given key */
delete(key: DocumentKey): DocumentSet;
isEqual(other: DocumentSet | null | undefined): boolean;
toString(): string;
private copy;
}
/**
* A `DocumentSnapshot` contains data read from a document in your Firestore
* database. The data can be extracted with `.data()` or `.get(<field>)` to
* get a specific field.
*
* For a `DocumentSnapshot` that points to a non-existing document, any data
* access will return 'undefined'. You can use the `exists()` method to
* explicitly verify a document's existence.
*/
export declare class DocumentSnapshot<T = DocumentData> extends DocumentSnapshot_2<T> {
readonly _firestore: FirebaseFirestore;
private readonly _firestoreImpl;
/**
* Metadata about the `DocumentSnapshot`, including information about its
* source and local modifications.
*/
readonly metadata: SnapshotMetadata;
/** @hideconstructor protected */
constructor(_firestore: FirebaseFirestore, userDataWriter: AbstractUserDataWriter, key: DocumentKey, document: Document_2 | null, metadata: SnapshotMetadata, converter: UntypedFirestoreDataConverter<T> | null);
/**
* Property of the `DocumentSnapshot` that signals whether or not the data
* exists. True if the document exists.
*/
exists(): this is QueryDocumentSnapshot<T>;
/**
* Retrieves all fields in the document as an `Object`. Returns `undefined` if
* the document doesn't exist.
*
* By default, `FieldValue.serverTimestamp()` values that have not yet been
* set to their final value will be returned as `null`. You can override
* this by passing an options object.
*
* @param options - An options object to configure how data is retrieved from
* the snapshot (for example the desired behavior for server timestamps that
* have not yet been set to their final value).
* @returns An `Object` containing all fields in the document or `undefined` if
* the document doesn't exist.
*/
data(options?: SnapshotOptions): T | undefined;
/**
* Retrieves the field specified by `fieldPath`. Returns `undefined` if the
* document or field doesn't exist.
*
* By default, a `FieldValue.serverTimestamp()` that has not yet been set to
* its final value will be returned as `null`. You can override this by
* passing an options object.
*
* @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
* field.
* @param options - An options object to configure how the field is retrieved
* from the snapshot (for example the desired behavior for server timestamps
* that have not yet been set to their final value).
* @returns The data at the specified field location or undefined if no such
* field exists in the document.
*/
get(fieldPath: string | FieldPath, options?: SnapshotOptions): any;
}
/**
* A `DocumentSnapshot` contains data read from a document in your Firestore
* database. The data can be extracted with `.data()` or `.get(<field>)` to
* get a specific field.
*
* For a `DocumentSnapshot` that points to a non-existing document, any data
* access will return 'undefined'. You can use the `exists()` method to
* explicitly verify a document's existence.
*/
declare class DocumentSnapshot_2<T = DocumentData> {
_firestore: FirebaseFirestore_2;
_userDataWriter: AbstractUserDataWriter;
_key: DocumentKey;
_document: Document_2 | null;
_converter: UntypedFirestoreDataConverter<T> | null;
/** @hideconstructor protected */
constructor(_firestore: FirebaseFirestore_2, _userDataWriter: AbstractUserDataWriter, _key: DocumentKey, _document: Document_2 | null, _converter: UntypedFirestoreDataConverter<T> | null);
/** Property of the `DocumentSnapshot` that provides the document's ID. */
get id(): string;
/**
* The `DocumentReference` for the document included in the `DocumentSnapshot`.
*/
get ref(): DocumentReference<T>;
/**
* Signals whether or not the document at the snapshot's location exists.
*
* @returns true if the document exists.
*/
exists(): this is QueryDocumentSnapshot_2<T>;
/**
* Retrieves all fields in the document as an `Object`. Returns `undefined` if
* the document doesn't exist.
*
* @returns An `Object` containing all fields in the document or `undefined`
* if the document doesn't exist.
*/
data(): T | undefined;
/**
* Retrieves the field specified by `fieldPath`. Returns `undefined` if the
* document or field doesn't exist.
*
* @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
* field.
* @returns The data at the specified field location or undefined if no such
* field exists in the document.
*/
get(fieldPath: string | FieldPath): any;
}
declare type DocumentVersionMap = SortedMap<DocumentKey, SnapshotVersion>;
declare interface DocumentViewChange {
type: ChangeType;
doc: Document_2;
}
/**
* Attempts to enable persistent storage, if possible.
*
* Must be called before any other functions (other than
* {@link initializeFirestore}, {@link getFirestore} or
* {@link clearIndexedDbPersistence}.
*
* If this fails, `enableIndexedDbPersistence()` will reject the promise it
* returns. Note that even after this failure, the `Firestore` instance will
* remain usable, however offline persistence will be disabled.
*
* There are several reasons why this can fail, which can be identified by
* the `code` on the error.
*
* * failed-precondition: The app is already open in another browser tab.
* * unimplemented: The browser is incompatible with the offline
* persistence implementation.
*
* @param firestore - The `Firestore` instance to enable persistence for.
* @param persistenceSettings - Optional settings object to configure
* persistence.
* @returns A promise that represents successfully enabling persistent storage.
*/
export declare function enableIndexedDbPersistence(firestore: FirebaseFirestore, persistenceSettings?: PersistenceSettings): Promise<void>;
/**
* Attempts to enable multi-tab persistent storage, if possible. If enabled
* across all tabs, all operations share access to local persistence, including
* shared execution of queries and latency-compensated local document updates
* across all connected instances.
*
* If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise
* it returns. Note that even after this failure, the `Firestore` instance will
* remain usable, however offline persistence will be disabled.
*
* There are several reasons why this can fail, which can be identified by
* the `code` on the error.
*
* * failed-precondition: The app is already open in another browser tab and
* multi-tab is not enabled.
* * unimplemented: The browser is incompatible with the offline
* persistence implementation.
*
* @param firestore - The `Firestore` instance to enable persistence for.
* @returns A promise that represents successfully enabling persistent
* storage.
*/
export declare function enableMultiTabIndexedDbPersistence(firestore: FirebaseFirestore): Promise<void>;
/**
* Re-enables use of the network for this Firestore instance after a prior
* call to {@link disableNetwork}.
*
* @returns A promise that is resolved once the network has been enabled.
*/
export declare function enableNetwork(firestore: FirebaseFirestore): Promise<void>;
/**
* Creates a `QueryConstraint` that modifies the result set to end at the
* provided document (inclusive). The end position is relative to the order of
* the query. The document must contain all of the fields provided in the
* orderBy of the query.
*
* @param snapshot - The snapshot of the document to end at.
* @returns A `QueryConstraint` to pass to `query()`
*/
export declare function endAt(snapshot: DocumentSnapshot_2<unknown>): QueryConstraint;
/**
* Creates a `QueryConstraint` that modifies the result set to end at the
* provided fields relative to the order of the query. The order of the field
* values must match the order of the order by clauses of the query.
*
* @param fieldValues - The field values to end this query at, in order
* of the query's order by.
* @returns A `QueryConstraint` to pass to `query()`
*/
export declare function endAt(...fieldValues: unknown[]): QueryConstraint;
/**
* Creates a `QueryConstraint` that modifies the result set to end before the
* provided document (exclusive). The end position is relative to the order of
* the query. The document must contain all of the fields provided in the
* orderBy of the query.
*
* @param snapshot - The snapshot of the document to end before.
* @returns A `QueryConstraint` to pass to `query()`
*/
export declare function endBefore(snapshot: DocumentSnapshot_2<unknown>): QueryConstraint;
/**
* Creates a `QueryConstraint` that modifies the result set to end before the
* provided fields relative to the order of the query. The order of the field
* values must match the order of the order by clauses of the query.
*
* @param fieldValues - The field values to end this query before, in order
* of the query's order by.
* @returns A `QueryConstraint` to pass to `query()`
*/
export declare function endBefore(...fieldValues: unknown[]): QueryConstraint;
/**
* @internal
*/
export declare function ensureFirestoreConfigured(firestore: FirebaseFirestore): FirestoreClient;
declare interface Entry<K, V> {
key: K;
value: V;
}
/**
* EventManager is responsible for mapping queries to query event emitters.
* It handles "fan-out". -- Identical queries will re-use the same watch on the
* backend.
*
* PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be
* assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This
* allows users to tree-shake the Watch logic.
*/
declare interface EventManager {
onListen?: (query: Query_2) => Promise<ViewSnapshot>;
onUnlisten?: (query: Query_2) => Promise<void>;
}
/**
* Locally writes `mutations` on the async queue.
* @internal
*/
export declare function executeWrite(firestore: FirebaseFirestore, mutations: Mutation[]): Promise<void>;
declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN';
/**
* Provides a set of fields that can be used to partially patch a document.
* FieldMask is used in conjunction with ObjectValue.
* Examples:
* foo - Overwrites foo entirely with the provided value. If foo is not
* present in the companion ObjectValue, the field is deleted.
* foo.bar - Overwrites only the field bar of the object foo.
* If foo is not an object, foo is replaced with an object
* containing foo
*/
declare class FieldMask {
readonly fields: FieldPath_2[];
constructor(fields: FieldPath_2[]);