UNPKG

255 kBTypeScriptView Raw
1/**
2 * Cloud Firestore
3 *
4 * @packageDocumentation
5 */
6
7import { DocumentData as DocumentData_2 } from '@firebase/firestore-types';
8import { EmulatorMockTokenOptions } from '@firebase/util';
9import { FirebaseApp } from '@firebase/app';
10import { FirebaseError } from '@firebase/util';
11import { _FirebaseService } from '@firebase/app';
12import { LogLevelString as LogLevel } from '@firebase/logger';
13import { SetOptions as SetOptions_2 } from '@firebase/firestore-types';
14
15/**
16 * Converts Firestore's internal types to the JavaScript types that we expose
17 * to the user.
18 *
19 * @internal
20 */
21export declare abstract class AbstractUserDataWriter {
22 convertValue(value: Value, serverTimestampBehavior?: ServerTimestampBehavior): unknown;
23 private convertObject;
24 private convertGeoPoint;
25 private convertArray;
26 private convertServerTimestamp;
27 private convertTimestamp;
28 protected convertDocumentKey(name: string, expectedDatabaseId: _DatabaseId): _DocumentKey;
29 protected abstract convertReference(name: string): unknown;
30 protected abstract convertBytes(bytes: _ByteString): unknown;
31}
32
33/**
34 * Describes a map whose keys are active target ids. We do not care about the type of the
35 * values.
36 */
37declare type ActiveTargets = SortedMap<TargetId, unknown>;
38
39/**
40 * Add a new document to specified `CollectionReference` with the given data,
41 * assigning it a document ID automatically.
42 *
43 * @param reference - A reference to the collection to add this document to.
44 * @param data - An Object containing the data for the new document.
45 * @returns A `Promise` resolved with a `DocumentReference` pointing to the
46 * newly created document after it has been written to the backend (Note that it
47 * won't resolve while you're offline).
48 */
49export declare function addDoc<T>(reference: CollectionReference<T>, data: WithFieldValue<T>): Promise<DocumentReference<T>>;
50
51/**
52 * Returns a new map where every key is prefixed with the outer key appended
53 * to a dot.
54 */
55export declare type AddPrefixToKeys<Prefix extends string, T extends Record<string, unknown>> = {
56 [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
57};
58
59/**
60 * Represents an aggregation that can be performed by Firestore.
61 */
62export declare class AggregateField<T> {
63 /** A type string to uniquely identify instances of this class. */
64 type: string;
65}
66
67/**
68 * The union of all `AggregateField` types that are supported by Firestore.
69 */
70export declare type AggregateFieldType = AggregateField<number>;
71
72/**
73 * The results of executing an aggregation query.
74 */
75export declare class AggregateQuerySnapshot<T extends AggregateSpec> {
76 private readonly _data;
77 /** A type string to uniquely identify instances of this class. */
78 readonly type = "AggregateQuerySnapshot";
79 /**
80 * The underlying query over which the aggregations recorded in this
81 * `AggregateQuerySnapshot` were performed.
82 */
83 readonly query: Query<unknown>;
84 /** @hideconstructor */
85 constructor(query: Query<unknown>, _data: AggregateSpecData<T>);
86 /**
87 * Returns the results of the aggregations performed over the underlying
88 * query.
89 *
90 * The keys of the returned object will be the same as those of the
91 * `AggregateSpec` object specified to the aggregation method, and the values
92 * will be the corresponding aggregation result.
93 *
94 * @returns The results of the aggregations performed over the underlying
95 * query.
96 */
97 data(): AggregateSpecData<T>;
98}
99
100/**
101 * Compares two `AggregateQuerySnapshot` instances for equality.
102 *
103 * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
104 * underlying queries that compare equal, and the same data.
105 *
106 * @param left - The first `AggregateQuerySnapshot` to compare.
107 * @param right - The second `AggregateQuerySnapshot` to compare.
108 *
109 * @returns `true` if the objects are "equal", as defined above, or `false`
110 * otherwise.
111 */
112export declare function aggregateQuerySnapshotEqual<T extends AggregateSpec>(left: AggregateQuerySnapshot<T>, right: AggregateQuerySnapshot<T>): boolean;
113
114/**
115 * A type whose property values are all `AggregateField` objects.
116 */
117export declare interface AggregateSpec {
118 [field: string]: AggregateFieldType;
119}
120
121/**
122 * A type whose keys are taken from an `AggregateSpec`, and whose values are the
123 * result of the aggregation performed by the corresponding `AggregateField`
124 * from the input `AggregateSpec`.
125 */
126export declare type AggregateSpecData<T extends AggregateSpec> = {
127 [P in keyof T]: T[P] extends AggregateField<infer U> ? U : never;
128};
129
130declare interface ApiClientObjectMap<T> {
131 [k: string]: T;
132}
133
134/**
135 * Returns a special value that can be used with {@link (setDoc:1)} or {@link
136 * updateDoc:1} that tells the server to remove the given elements from any
137 * array value that already exists on the server. All instances of each element
138 * specified will be removed from the array. If the field being modified is not
139 * already an array it will be overwritten with an empty array.
140 *
141 * @param elements - The elements to remove from the array.
142 * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
143 * `updateDoc()`
144 */
145export declare function arrayRemove(...elements: unknown[]): FieldValue;
146
147/**
148 * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
149 * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
150 * value that already exists on the server. Each specified element that doesn't
151 * already exist in the array will be added to the end. If the field being
152 * modified is not already an array it will be overwritten with an array
153 * containing exactly the specified elements.
154 *
155 * @param elements - The elements to union into the array.
156 * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
157 * `updateDoc()`.
158 */
159export declare function arrayUnion(...elements: unknown[]): FieldValue;
160
161declare interface AsyncQueue {
162 readonly isShuttingDown: boolean;
163 /**
164 * Adds a new operation to the queue without waiting for it to complete (i.e.
165 * we ignore the Promise result).
166 */
167 enqueueAndForget<T extends unknown>(op: () => Promise<T>): void;
168 /**
169 * Regardless if the queue has initialized shutdown, adds a new operation to the
170 * queue without waiting for it to complete (i.e. we ignore the Promise result).
171 */
172 enqueueAndForgetEvenWhileRestricted<T extends unknown>(op: () => Promise<T>): void;
173 /**
174 * Initialize the shutdown of this queue. Once this method is called, the
175 * only possible way to request running an operation is through
176 * `enqueueEvenWhileRestricted()`.
177 *
178 * @param purgeExistingTasks Whether already enqueued tasked should be
179 * rejected (unless enqueued wih `enqueueEvenWhileRestricted()`). Defaults
180 * to false.
181 */
182 enterRestrictedMode(purgeExistingTasks?: boolean): void;
183 /**
184 * Adds a new operation to the queue. Returns a promise that will be resolved
185 * when the promise returned by the new operation is (with its value).
186 */
187 enqueue<T extends unknown>(op: () => Promise<T>): Promise<T>;
188 /**
189 * Enqueue a retryable operation.
190 *
191 * A retryable operation is rescheduled with backoff if it fails with a
192 * IndexedDbTransactionError (the error type used by SimpleDb). All
193 * retryable operations are executed in order and only run if all prior
194 * operations were retried successfully.
195 */
196 enqueueRetryable(op: () => Promise<void>): void;
197 /**
198 * Schedules an operation to be queued on the AsyncQueue once the specified
199 * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel
200 * or fast-forward the operation prior to its running.
201 */
202 enqueueAfterDelay<T extends unknown>(timerId: TimerId, delayMs: number, op: () => Promise<T>): DelayedOperation<T>;
203 /**
204 * Verifies there's an operation currently in-progress on the AsyncQueue.
205 * Unfortunately we can't verify that the running code is in the promise chain
206 * of that operation, so this isn't a foolproof check, but it should be enough
207 * to catch some bugs.
208 */
209 verifyOperationInProgress(): void;
210}
211
212declare type AuthTokenFactory = () => string;
213
214/**
215 * Path represents an ordered sequence of string segments.
216 */
217declare abstract class BasePath<B extends BasePath<B>> {
218 private segments;
219 private offset;
220 private len;
221 constructor(segments: string[], offset?: number, length?: number);
222 /**
223 * Abstract constructor method to construct an instance of B with the given
224 * parameters.
225 */
226 protected abstract construct(segments: string[], offset?: number, length?: number): B;
227 /**
228 * Returns a String representation.
229 *
230 * Implementing classes are required to provide deterministic implementations as
231 * the String representation is used to obtain canonical Query IDs.
232 */
233 abstract toString(): string;
234 get length(): number;
235 isEqual(other: B): boolean;
236 child(nameOrPath: string | B): B;
237 /** The index of one past the last segment of the path. */
238 private limit;
239 popFirst(size?: number): B;
240 popLast(): B;
241 firstSegment(): string;
242 lastSegment(): string;
243 get(index: number): string;
244 isEmpty(): boolean;
245 isPrefixOf(other: this): boolean;
246 isImmediateParentOf(potentialChild: this): boolean;
247 forEach(fn: (segment: string) => void): void;
248 toArray(): string[];
249 static comparator<T extends BasePath<T>>(p1: BasePath<T>, p2: BasePath<T>): number;
250}
251
252/**
253 * @license
254 * Copyright 2017 Google LLC
255 *
256 * Licensed under the Apache License, Version 2.0 (the "License");
257 * you may not use this file except in compliance with the License.
258 * You may obtain a copy of the License at
259 *
260 * http://www.apache.org/licenses/LICENSE-2.0
261 *
262 * Unless required by applicable law or agreed to in writing, software
263 * distributed under the License is distributed on an "AS IS" BASIS,
264 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
265 * See the License for the specific language governing permissions and
266 * limitations under the License.
267 */
268/**
269 * BatchID is a locally assigned ID for a batch of mutations that have been
270 * applied.
271 */
272declare type BatchId = number;
273
274/**
275 * Represents a bound of a query.
276 *
277 * The bound is specified with the given components representing a position and
278 * whether it's just before or just after the position (relative to whatever the
279 * query order is).
280 *
281 * The position represents a logical index position for a query. It's a prefix
282 * of values for the (potentially implicit) order by clauses of a query.
283 *
284 * Bound provides a function to determine whether a document comes before or
285 * after a bound. This is influenced by whether the position is just before or
286 * just after the provided values.
287 */
288declare class Bound {
289 readonly position: Value[];
290 readonly inclusive: boolean;
291 constructor(position: Value[], inclusive: boolean);
292}
293
294/**
295 * Provides interfaces to save and read Firestore bundles.
296 */
297declare interface BundleCache {
298 /**
299 * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined
300 * if no bundle metadata is found under the given id.
301 */
302 getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise<BundleMetadata | undefined>;
303 /**
304 * Saves a `BundleMetadata` from a bundle into local storage, using its id as
305 * the persistent key.
306 */
307 saveBundleMetadata(transaction: PersistenceTransaction, metadata: BundleMetadata_2): PersistencePromise<void>;
308 /**
309 * Gets a saved `NamedQuery` for the given query name. Returns undefined if
310 * no queries are found under the given name.
311 */
312 getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise<NamedQuery | undefined>;
313 /**
314 * Saves a `NamedQuery` from a bundle, using its name as the persistent key.
315 */
316 saveNamedQuery(transaction: PersistenceTransaction, query: NamedQuery_2): PersistencePromise<void>;
317}
318
319/** Properties of a BundledQuery. */
320declare interface BundledQuery {
321 /** BundledQuery parent */
322 parent?: string | null;
323 /** BundledQuery structuredQuery */
324 structuredQuery?: StructuredQuery | null;
325 /** BundledQuery limitType */
326 limitType?: LimitType_2 | null;
327}
328
329/**
330 * Represents a Firestore bundle saved by the SDK in its local storage.
331 */
332declare interface BundleMetadata {
333 /**
334 * Id of the bundle. It is used together with `createTime` to determine if a
335 * bundle has been loaded by the SDK.
336 */
337 readonly id: string;
338 /** Schema version of the bundle. */
339 readonly version: number;
340 /**
341 * Set to the snapshot version of the bundle if created by the Server SDKs.
342 * Otherwise set to SnapshotVersion.MIN.
343 */
344 readonly createTime: SnapshotVersion;
345}
346
347/** Properties of a BundleMetadata. */
348declare interface BundleMetadata_2 {
349 /** BundleMetadata id */
350 id?: string | null;
351 /** BundleMetadata createTime */
352 createTime?: Timestamp_2 | null;
353 /** BundleMetadata version */
354 version?: number | null;
355 /** BundleMetadata totalDocuments */
356 totalDocuments?: number | null;
357 /** BundleMetadata totalBytes */
358 totalBytes?: number | null;
359}
360
361/**
362 * An immutable object representing an array of bytes.
363 */
364export declare class Bytes {
365 _byteString: _ByteString;
366 /** @hideconstructor */
367 constructor(byteString: _ByteString);
368 /**
369 * Creates a new `Bytes` object from the given Base64 string, converting it to
370 * bytes.
371 *
372 * @param base64 - The Base64 string used to create the `Bytes` object.
373 */
374 static fromBase64String(base64: string): Bytes;
375 /**
376 * Creates a new `Bytes` object from the given Uint8Array.
377 *
378 * @param array - The Uint8Array used to create the `Bytes` object.
379 */
380 static fromUint8Array(array: Uint8Array): Bytes;
381 /**
382 * Returns the underlying bytes as a Base64-encoded string.
383 *
384 * @returns The Base64-encoded string created from the `Bytes` object.
385 */
386 toBase64(): string;
387 /**
388 * Returns the underlying bytes in a new `Uint8Array`.
389 *
390 * @returns The Uint8Array created from the `Bytes` object.
391 */
392 toUint8Array(): Uint8Array;
393 /**
394 * Returns a string representation of the `Bytes` object.
395 *
396 * @returns A string representation of the `Bytes` object.
397 */
398 toString(): string;
399 /**
400 * Returns true if this `Bytes` object is equal to the provided one.
401 *
402 * @param other - The `Bytes` object to compare against.
403 * @returns true if this `Bytes` object is equal to the provided one.
404 */
405 isEqual(other: Bytes): boolean;
406}
407
408/**
409 * @license
410 * Copyright 2020 Google LLC
411 *
412 * Licensed under the Apache License, Version 2.0 (the "License");
413 * you may not use this file except in compliance with the License.
414 * You may obtain a copy of the License at
415 *
416 * http://www.apache.org/licenses/LICENSE-2.0
417 *
418 * Unless required by applicable law or agreed to in writing, software
419 * distributed under the License is distributed on an "AS IS" BASIS,
420 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
421 * See the License for the specific language governing permissions and
422 * limitations under the License.
423 */
424/**
425 * Immutable class that represents a "proto" byte string.
426 *
427 * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
428 * sent on the wire. This class abstracts away this differentiation by holding
429 * the proto byte string in a common class that must be converted into a string
430 * before being sent as a proto.
431 * @internal
432 */
433export declare class _ByteString {
434 private readonly binaryString;
435 static readonly EMPTY_BYTE_STRING: _ByteString;
436 private constructor();
437 static fromBase64String(base64: string): _ByteString;
438 static fromUint8Array(array: Uint8Array): _ByteString;
439 [Symbol.iterator](): Iterator<number>;
440 toBase64(): string;
441 toUint8Array(): Uint8Array;
442 approximateByteSize(): number;
443 compareTo(other: _ByteString): number;
444 isEqual(other: _ByteString): boolean;
445}
446
447/**
448 * Constant used to indicate the LRU garbage collection should be disabled.
449 * Set this value as the `cacheSizeBytes` on the settings passed to the
450 * {@link Firestore} instance.
451 */
452export declare const CACHE_SIZE_UNLIMITED = -1;
453
454/**
455 * Casts `obj` to `T`, optionally unwrapping Compat types to expose the
456 * underlying instance. Throws if `obj` is not an instance of `T`.
457 *
458 * This cast is used in the Lite and Full SDK to verify instance types for
459 * arguments passed to the public API.
460 * @internal
461 */
462export declare function _cast<T>(obj: object, constructor: {
463 new (...args: any[]): T;
464}): T | never;
465
466declare const enum ChangeType {
467 Added = 0,
468 Removed = 1,
469 Modified = 2,
470 Metadata = 3
471}
472
473/**
474 * Helper for calculating the nested fields for a given type T1. This is needed
475 * to distribute union types such as `undefined | {...}` (happens for optional
476 * props) or `{a: A} | {b: B}`.
477 *
478 * In this use case, `V` is used to distribute the union types of `T[K]` on
479 * `Record`, since `T[K]` is evaluated as an expression and not distributed.
480 *
481 * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types
482 */
483export declare type ChildUpdateFields<K extends string, V> = V extends Record<string, unknown> ? AddPrefixToKeys<K, UpdateData<V>> : never;
484
485/**
486 * Clears the persistent storage. This includes pending writes and cached
487 * documents.
488 *
489 * Must be called while the {@link Firestore} instance is not started (after the app is
490 * terminated or when the app is first initialized). On startup, this function
491 * must be called before other functions (other than {@link
492 * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}
493 * instance is still running, the promise will be rejected with the error code
494 * of `failed-precondition`.
495 *
496 * Note: `clearIndexedDbPersistence()` is primarily intended to help write
497 * reliable tests that use Cloud Firestore. It uses an efficient mechanism for
498 * dropping existing data but does not attempt to securely overwrite or
499 * otherwise make cached data unrecoverable. For applications that are sensitive
500 * to the disclosure of cached data in between user sessions, we strongly
501 * recommend not enabling persistence at all.
502 *
503 * @param firestore - The {@link Firestore} instance to clear persistence for.
504 * @returns A `Promise` that is resolved when the persistent storage is
505 * cleared. Otherwise, the promise is rejected with an error.
506 */
507export declare function clearIndexedDbPersistence(firestore: Firestore): Promise<void>;
508
509/**
510 * A randomly-generated key assigned to each Firestore instance at startup.
511 */
512declare type ClientId = string;
513
514/**
515 * Gets a `CollectionReference` instance that refers to the collection at
516 * the specified absolute path.
517 *
518 * @param firestore - A reference to the root `Firestore` instance.
519 * @param path - A slash-separated path to a collection.
520 * @param pathSegments - Additional path segments to apply relative to the first
521 * argument.
522 * @throws If the final path has an even number of segments and does not point
523 * to a collection.
524 * @returns The `CollectionReference` instance.
525 */
526export declare function collection(firestore: Firestore_2, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;
527
528/**
529 * Gets a `CollectionReference` instance that refers to a subcollection of
530 * `reference` at the the specified relative path.
531 *
532 * @param reference - A reference to a collection.
533 * @param path - A slash-separated path to a collection.
534 * @param pathSegments - Additional path segments to apply relative to the first
535 * argument.
536 * @throws If the final path has an even number of segments and does not point
537 * to a collection.
538 * @returns The `CollectionReference` instance.
539 */
540export declare function collection(reference: CollectionReference<unknown>, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;
541
542/**
543 * Gets a `CollectionReference` instance that refers to a subcollection of
544 * `reference` at the the specified relative path.
545 *
546 * @param reference - A reference to a Firestore document.
547 * @param path - A slash-separated path to a collection.
548 * @param pathSegments - Additional path segments that will be applied relative
549 * to the first argument.
550 * @throws If the final path has an even number of segments and does not point
551 * to a collection.
552 * @returns The `CollectionReference` instance.
553 */
554export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;
555
556/**
557 * Creates and returns a new `Query` instance that includes all documents in the
558 * database that are contained in a collection or subcollection with the
559 * given `collectionId`.
560 *
561 * @param firestore - A reference to the root `Firestore` instance.
562 * @param collectionId - Identifies the collections to query over. Every
563 * collection or subcollection with this ID as the last segment of its path
564 * will be included. Cannot contain a slash.
565 * @returns The created `Query`.
566 */
567export declare function collectionGroup(firestore: Firestore_2, collectionId: string): Query<DocumentData>;
568
569/**
570 * A `CollectionReference` object can be used for adding documents, getting
571 * document references, and querying for documents (using {@link query}).
572 */
573export declare class CollectionReference<T = DocumentData> extends Query<T> {
574 readonly _path: _ResourcePath;
575 /** The type of this Firestore reference. */
576 readonly type = "collection";
577 /** @hideconstructor */
578 constructor(firestore: Firestore_2, converter: FirestoreDataConverter_2<T> | null, _path: _ResourcePath);
579 /** The collection's identifier. */
580 get id(): string;
581 /**
582 * A string representing the path of the referenced collection (relative
583 * to the root of the database).
584 */
585 get path(): string;
586 /**
587 * A reference to the containing `DocumentReference` if this is a
588 * subcollection. If this isn't a subcollection, the reference is null.
589 */
590 get parent(): DocumentReference<DocumentData> | null;
591 /**
592 * Applies a custom data converter to this `CollectionReference`, allowing you
593 * to use your own custom model objects with Firestore. When you call {@link
594 * addDoc} with the returned `CollectionReference` instance, the provided
595 * converter will convert between Firestore data and your custom type `U`.
596 *
597 * @param converter - Converts objects to and from Firestore.
598 * @returns A `CollectionReference<U>` that uses the provided converter.
599 */
600 withConverter<U>(converter: FirestoreDataConverter_2<U>): CollectionReference<U>;
601 /**
602 * Removes the current converter.
603 *
604 * @param converter - `null` removes the current converter.
605 * @returns A `CollectionReference<DocumentData>` that does not use a
606 * converter.
607 */
608 withConverter(converter: null): CollectionReference<DocumentData>;
609}
610
611/**
612 * @license
613 * Copyright 2017 Google LLC
614 *
615 * Licensed under the Apache License, Version 2.0 (the "License");
616 * you may not use this file except in compliance with the License.
617 * You may obtain a copy of the License at
618 *
619 * http://www.apache.org/licenses/LICENSE-2.0
620 *
621 * Unless required by applicable law or agreed to in writing, software
622 * distributed under the License is distributed on an "AS IS" BASIS,
623 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
624 * See the License for the specific language governing permissions and
625 * limitations under the License.
626 */
627declare type Comparator<K> = (key1: K, key2: K) => number;
628
629declare interface ComponentConfiguration {
630 asyncQueue: AsyncQueue;
631 databaseInfo: DatabaseInfo;
632 authCredentials: CredentialsProvider<User>;
633 appCheckCredentials: CredentialsProvider<string>;
634 clientId: ClientId;
635 initialUser: User;
636 maxConcurrentLimboResolutions: number;
637}
638
639declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND';
640
641/**
642 * Modify this instance to communicate with the Cloud Firestore emulator.
643 *
644 * Note: This must be called before this instance has been used to do any
645 * operations.
646 *
647 * @param firestore - The `Firestore` instance to configure to connect to the
648 * emulator.
649 * @param host - the emulator host (ex: localhost).
650 * @param port - the emulator port (ex: 9000).
651 * @param options.mockUserToken - the mock auth token to use for unit testing
652 * Security Rules.
653 */
654export declare function connectFirestoreEmulator(firestore: Firestore_2, host: string, port: number, options?: {
655 mockUserToken?: EmulatorMockTokenOptions | string;
656}): void;
657
658/**
659 * A Listener for credential change events. The listener should fetch a new
660 * token and may need to invalidate other state if the current user has also
661 * changed.
662 */
663declare type CredentialChangeListener<T> = (credential: T) => Promise<void>;
664
665/**
666 * Provides methods for getting the uid and token for the current user and
667 * listening for changes.
668 */
669declare interface CredentialsProvider<T> {
670 /**
671 * Starts the credentials provider and specifies a listener to be notified of
672 * credential changes (sign-in / sign-out, token changes). It is immediately
673 * called once with the initial user.
674 *
675 * The change listener is invoked on the provided AsyncQueue.
676 */
677 start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener<T>): void;
678 /** Requests a token for the current user. */
679 getToken(): Promise<Token | null>;
680 /**
681 * Marks the last retrieved token as invalid, making the next GetToken request
682 * force-refresh the token.
683 */
684 invalidateToken(): void;
685 shutdown(): void;
686}
687
688/** Settings for private credentials */
689declare type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings;
690
691/**
692 * Represents the database ID a Firestore client is associated with.
693 * @internal
694 */
695export declare class _DatabaseId {
696 readonly projectId: string;
697 readonly database: string;
698 constructor(projectId: string, database?: string);
699 static empty(): _DatabaseId;
700 get isDefaultDatabase(): boolean;
701 isEqual(other: {}): boolean;
702}
703
704/**
705 * @license
706 * Copyright 2017 Google LLC
707 *
708 * Licensed under the Apache License, Version 2.0 (the "License");
709 * you may not use this file except in compliance with the License.
710 * You may obtain a copy of the License at
711 *
712 * http://www.apache.org/licenses/LICENSE-2.0
713 *
714 * Unless required by applicable law or agreed to in writing, software
715 * distributed under the License is distributed on an "AS IS" BASIS,
716 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
717 * See the License for the specific language governing permissions and
718 * limitations under the License.
719 */
720declare class DatabaseInfo {
721 readonly databaseId: _DatabaseId;
722 readonly appId: string;
723 readonly persistenceKey: string;
724 readonly host: string;
725 readonly ssl: boolean;
726 readonly forceLongPolling: boolean;
727 readonly autoDetectLongPolling: boolean;
728 readonly useFetchStreams: boolean;
729 /**
730 * Constructs a DatabaseInfo using the provided host, databaseId and
731 * persistenceKey.
732 *
733 * @param databaseId - The database to use.
734 * @param appId - The Firebase App Id.
735 * @param persistenceKey - A unique identifier for this Firestore's local
736 * storage (used in conjunction with the databaseId).
737 * @param host - The Firestore backend host to connect to.
738 * @param ssl - Whether to use SSL when connecting.
739 * @param forceLongPolling - Whether to use the forceLongPolling option
740 * when using WebChannel as the network transport.
741 * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
742 * option when using WebChannel as the network transport.
743 * @param useFetchStreams Whether to use the Fetch API instead of
744 * XMLHTTPRequest
745 */
746 constructor(databaseId: _DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, useFetchStreams: boolean);
747}
748
749/**
750 * Datastore and its related methods are a wrapper around the external Google
751 * Cloud Datastore grpc API, which provides an interface that is more convenient
752 * for the rest of the client SDK architecture to consume.
753 */
754declare abstract class Datastore {
755 abstract terminate(): void;
756}
757
758/**
759 * Fails if the given assertion condition is false, throwing an Error with the
760 * given message if it did.
761 *
762 * The code of callsites invoking this function are stripped out in production
763 * builds. Any side-effects of code within the debugAssert() invocation will not
764 * happen in this case.
765 *
766 * @internal
767 */
768export declare function _debugAssert(assertion: boolean, message: string): asserts assertion;
769
770/**
771 * Represents an operation scheduled to be run in the future on an AsyncQueue.
772 *
773 * It is created via DelayedOperation.createAndSchedule().
774 *
775 * Supports cancellation (via cancel()) and early execution (via skipDelay()).
776 *
777 * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
778 * in newer versions of TypeScript defines `finally`, which is not available in
779 * IE.
780 */
781declare class DelayedOperation<T extends unknown> implements PromiseLike<T> {
782 private readonly asyncQueue;
783 readonly timerId: TimerId;
784 readonly targetTimeMs: number;
785 private readonly op;
786 private readonly removalCallback;
787 private timerHandle;
788 private readonly deferred;
789 private constructor();
790 /**
791 * Creates and returns a DelayedOperation that has been scheduled to be
792 * executed on the provided asyncQueue after the provided delayMs.
793 *
794 * @param asyncQueue - The queue to schedule the operation on.
795 * @param id - A Timer ID identifying the type of operation this is.
796 * @param delayMs - The delay (ms) before the operation should be scheduled.
797 * @param op - The operation to run.
798 * @param removalCallback - A callback to be called synchronously once the
799 * operation is executed or canceled, notifying the AsyncQueue to remove it
800 * from its delayedOperations list.
801 * PORTING NOTE: This exists to prevent making removeDelayedOperation() and
802 * the DelayedOperation class public.
803 */
804 static createAndSchedule<R extends unknown>(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise<R>, removalCallback: (op: DelayedOperation<R>) => void): DelayedOperation<R>;
805 /**
806 * Starts the timer. This is called immediately after construction by
807 * createAndSchedule().
808 */
809 private start;
810 /**
811 * Queues the operation to run immediately (if it hasn't already been run or
812 * canceled).
813 */
814 skipDelay(): void;
815 /**
816 * Cancels the operation if it hasn't already been executed or canceled. The
817 * promise will be rejected.
818 *
819 * As long as the operation has not yet been run, calling cancel() provides a
820 * guarantee that the operation will not be run.
821 */
822 cancel(reason?: string): void;
823 then: <TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined) => Promise<TResult1 | TResult2>;
824 private handleDelayElapsed;
825 private clearTimeout;
826}
827
828/**
829 * Deletes the document referred to by the specified `DocumentReference`.
830 *
831 * @param reference - A reference to the document to delete.
832 * @returns A Promise resolved once the document has been successfully
833 * deleted from the backend (note that it won't resolve while you're offline).
834 */
835export declare function deleteDoc(reference: DocumentReference<unknown>): Promise<void>;
836
837/**
838 * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
839 * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
840 */
841export declare function deleteField(): FieldValue;
842
843/**
844 * The direction of sorting in an order by.
845 */
846declare const enum Direction {
847 ASCENDING = "asc",
848 DESCENDING = "desc"
849}
850
851/**
852 * Disables network usage for this instance. It can be re-enabled via {@link
853 * enableNetwork}. While the network is disabled, any snapshot listeners,
854 * `getDoc()` or `getDocs()` calls will return results from cache, and any write
855 * operations will be queued until the network is restored.
856 *
857 * @returns A `Promise` that is resolved once the network has been disabled.
858 */
859export declare function disableNetwork(firestore: Firestore): Promise<void>;
860
861/**
862 * Gets a `DocumentReference` instance that refers to the document at the
863 * specified absolute path.
864 *
865 * @param firestore - A reference to the root `Firestore` instance.
866 * @param path - A slash-separated path to a document.
867 * @param pathSegments - Additional path segments that will be applied relative
868 * to the first argument.
869 * @throws If the final path has an odd number of segments and does not point to
870 * a document.
871 * @returns The `DocumentReference` instance.
872 */
873export declare function doc(firestore: Firestore_2, path: string, ...pathSegments: string[]): DocumentReference<DocumentData>;
874
875/**
876 * Gets a `DocumentReference` instance that refers to a document within
877 * `reference` at the specified relative path. If no path is specified, an
878 * automatically-generated unique ID will be used for the returned
879 * `DocumentReference`.
880 *
881 * @param reference - A reference to a collection.
882 * @param path - A slash-separated path to a document. Has to be omitted to use
883 * auto-genrated IDs.
884 * @param pathSegments - Additional path segments that will be applied relative
885 * to the first argument.
886 * @throws If the final path has an odd number of segments and does not point to
887 * a document.
888 * @returns The `DocumentReference` instance.
889 */
890export declare function doc<T>(reference: CollectionReference<T>, path?: string, ...pathSegments: string[]): DocumentReference<T>;
891
892/**
893 * Gets a `DocumentReference` instance that refers to a document within
894 * `reference` at the specified relative path.
895 *
896 * @param reference - A reference to a Firestore document.
897 * @param path - A slash-separated path to a document.
898 * @param pathSegments - Additional path segments that will be applied relative
899 * to the first argument.
900 * @throws If the final path has an odd number of segments and does not point to
901 * a document.
902 * @returns The `DocumentReference` instance.
903 */
904export declare function doc(reference: DocumentReference<unknown>, path: string, ...pathSegments: string[]): DocumentReference<DocumentData>;
905
906/**
907 * Represents a document in Firestore with a key, version, data and whether the
908 * data has local mutations applied to it.
909 */
910declare interface Document_2 {
911 /** The key for this document */
912 readonly key: _DocumentKey;
913 /**
914 * The version of this document if it exists or a version at which this
915 * document was guaranteed to not exist.
916 */
917 readonly version: SnapshotVersion;
918 /**
919 * The timestamp at which this document was read from the remote server. Uses
920 * `SnapshotVersion.min()` for documents created by the user.
921 */
922 readonly readTime: SnapshotVersion;
923 /** The underlying data of this document or an empty value if no data exists. */
924 readonly data: ObjectValue;
925 /** Returns whether local mutations were applied via the mutation queue. */
926 readonly hasLocalMutations: boolean;
927 /** Returns whether mutations were applied based on a write acknowledgment. */
928 readonly hasCommittedMutations: boolean;
929 /**
930 * Whether this document had a local mutation applied that has not yet been
931 * acknowledged by Watch.
932 */
933 readonly hasPendingWrites: boolean;
934 /**
935 * Returns whether this document is valid (i.e. it is an entry in the
936 * RemoteDocumentCache, was created by a mutation or read from the backend).
937 */
938 isValidDocument(): boolean;
939 /**
940 * Returns whether the document exists and its data is known at the current
941 * version.
942 */
943 isFoundDocument(): boolean;
944 /**
945 * Returns whether the document is known to not exist at the current version.
946 */
947 isNoDocument(): boolean;
948 /**
949 * Returns whether the document exists and its data is unknown at the current
950 * version.
951 */
952 isUnknownDocument(): boolean;
953 isEqual(other: Document_2 | null | undefined): boolean;
954 /** Creates a mutable copy of this document. */
955 mutableCopy(): MutableDocument;
956 toString(): string;
957}
958
959/**
960 * A `DocumentChange` represents a change to the documents matching a query.
961 * It contains the document affected and the type of change that occurred.
962 */
963export declare interface DocumentChange<T = DocumentData> {
964 /** The type of change ('added', 'modified', or 'removed'). */
965 readonly type: DocumentChangeType;
966 /** The document affected by this change. */
967 readonly doc: QueryDocumentSnapshot<T>;
968 /**
969 * The index of the changed document in the result set immediately prior to
970 * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects
971 * have been applied). Is `-1` for 'added' events.
972 */
973 readonly oldIndex: number;
974 /**
975 * The index of the changed document in the result set immediately after
976 * this `DocumentChange` (i.e. supposing that all prior `DocumentChange`
977 * objects and the current `DocumentChange` object have been applied).
978 * Is -1 for 'removed' events.
979 */
980 readonly newIndex: number;
981}
982
983/**
984 * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'.
985 */
986export declare type DocumentChangeType = 'added' | 'removed' | 'modified';
987
988declare type DocumentComparator = (doc1: Document_2, doc2: Document_2) => number;
989
990/**
991 * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to
992 * values.
993 */
994export declare interface DocumentData {
995 /** A mapping between a field and its value. */
996 [field: string]: any;
997}
998
999/**
1000 * Returns a special sentinel `FieldPath` to refer to the ID of a document.
1001 * It can be used in queries to sort or filter by the document ID.
1002 */
1003export declare function documentId(): FieldPath;
1004
1005/**
1006 * @internal
1007 */
1008export declare class _DocumentKey {
1009 readonly path: _ResourcePath;
1010 constructor(path: _ResourcePath);
1011 static fromPath(path: string): _DocumentKey;
1012 static fromName(name: string): _DocumentKey;
1013 static empty(): _DocumentKey;
1014 get collectionGroup(): string;
1015 /** Returns true if the document is in the specified collectionId. */
1016 hasCollectionId(collectionId: string): boolean;
1017 /** Returns the collection group (i.e. the name of the parent collection) for this key. */
1018 getCollectionGroup(): string;
1019 /** Returns the fully qualified path to the parent collection. */
1020 getCollectionPath(): _ResourcePath;
1021 isEqual(other: _DocumentKey | null): boolean;
1022 toString(): string;
1023 static comparator(k1: _DocumentKey, k2: _DocumentKey): number;
1024 static isDocumentKey(path: _ResourcePath): boolean;
1025 /**
1026 * Creates and returns a new document key with the given segments.
1027 *
1028 * @param segments - The segments of the path to the document
1029 * @returns A new instance of DocumentKey
1030 */
1031 static fromSegments(segments: string[]): _DocumentKey;
1032}
1033
1034declare type DocumentKeyMap<T> = ObjectMap<_DocumentKey, T>;
1035
1036declare type DocumentKeySet = SortedSet<_DocumentKey>;
1037
1038declare type DocumentMap = SortedMap<_DocumentKey, Document_2>;
1039
1040/**
1041 * Provides methods to read and write document overlays.
1042 *
1043 * An overlay is a saved mutation, that gives a local view of a document when
1044 * applied to the remote version of the document.
1045 *
1046 * Each overlay stores the largest batch ID that is included in the overlay,
1047 * which allows us to remove the overlay once all batches leading up to it have
1048 * been acknowledged.
1049 */
1050declare interface DocumentOverlayCache {
1051 /**
1052 * Gets the saved overlay mutation for the given document key.
1053 * Returns null if there is no overlay for that key.
1054 */
1055 getOverlay(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise<Overlay | null>;
1056 /**
1057 * Gets the saved overlay mutation for the given document keys. Skips keys for
1058 * which there are no overlays.
1059 */
1060 getOverlays(transaction: PersistenceTransaction, keys: _DocumentKey[]): PersistencePromise<OverlayMap>;
1061 /**
1062 * Saves the given document mutation map to persistence as overlays.
1063 * All overlays will have their largest batch id set to `largestBatchId`.
1064 */
1065 saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise<void>;
1066 /** Removes overlays for the given document keys and batch ID. */
1067 removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise<void>;
1068 /**
1069 * Returns all saved overlays for the given collection.
1070 *
1071 * @param transaction - The persistence transaction to use for this operation.
1072 * @param collection - The collection path to get the overlays for.
1073 * @param sinceBatchId - The minimum batch ID to filter by (exclusive).
1074 * Only overlays that contain a change past `sinceBatchId` are returned.
1075 * @returns Mapping of each document key in the collection to its overlay.
1076 */
1077 getOverlaysForCollection(transaction: PersistenceTransaction, collection: _ResourcePath, sinceBatchId: number): PersistencePromise<OverlayMap>;
1078 /**
1079 * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the
1080 * provided collection group, processed by ascending batch ID. The method
1081 * always returns all overlays for a batch even if the last batch contains
1082 * more documents than the remaining limit.
1083 *
1084 * @param transaction - The persistence transaction used for this operation.
1085 * @param collectionGroup - The collection group to get the overlays for.
1086 * @param sinceBatchId - The minimum batch ID to filter by (exclusive).
1087 * Only overlays that contain a change past `sinceBatchId` are returned.
1088 * @param count - The number of overlays to return. Can be exceeded if the last
1089 * batch contains more entries.
1090 * @return Mapping of each document key in the collection group to its overlay.
1091 */
1092 getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise<OverlayMap>;
1093}
1094
1095/**
1096 * A `DocumentReference` refers to a document location in a Firestore database
1097 * and can be used to write, read, or listen to the location. The document at
1098 * the referenced location may or may not exist.
1099 */
1100export declare class DocumentReference<T = DocumentData> {
1101 /**
1102 * If provided, the `FirestoreDataConverter` associated with this instance.
1103 */
1104 readonly converter: FirestoreDataConverter_2<T> | null;
1105 readonly _key: _DocumentKey;
1106 /** The type of this Firestore reference. */
1107 readonly type = "document";
1108 /**
1109 * The {@link Firestore} instance the document is in.
1110 * This is useful for performing transactions, for example.
1111 */
1112 readonly firestore: Firestore_2;
1113 /** @hideconstructor */
1114 constructor(firestore: Firestore_2,
1115 /**
1116 * If provided, the `FirestoreDataConverter` associated with this instance.
1117 */
1118 converter: FirestoreDataConverter_2<T> | null, _key: _DocumentKey);
1119 get _path(): _ResourcePath;
1120 /**
1121 * The document's identifier within its collection.
1122 */
1123 get id(): string;
1124 /**
1125 * A string representing the path of the referenced document (relative
1126 * to the root of the database).
1127 */
1128 get path(): string;
1129 /**
1130 * The collection this `DocumentReference` belongs to.
1131 */
1132 get parent(): CollectionReference<T>;
1133 /**
1134 * Applies a custom data converter to this `DocumentReference`, allowing you
1135 * to use your own custom model objects with Firestore. When you call {@link
1136 * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`
1137 * instance, the provided converter will convert between Firestore data and
1138 * your custom type `U`.
1139 *
1140 * @param converter - Converts objects to and from Firestore.
1141 * @returns A `DocumentReference<U>` that uses the provided converter.
1142 */
1143 withConverter<U>(converter: FirestoreDataConverter_2<U>): DocumentReference<U>;
1144 /**
1145 * Removes the current converter.
1146 *
1147 * @param converter - `null` removes the current converter.
1148 * @returns A `DocumentReference<DocumentData>` that does not use a converter.
1149 */
1150 withConverter(converter: null): DocumentReference<DocumentData>;
1151}
1152
1153/**
1154 * DocumentSet is an immutable (copy-on-write) collection that holds documents
1155 * in order specified by the provided comparator. We always add a document key
1156 * comparator on top of what is provided to guarantee document equality based on
1157 * the key.
1158 */
1159declare class DocumentSet {
1160 /**
1161 * Returns an empty copy of the existing DocumentSet, using the same
1162 * comparator.
1163 */
1164 static emptySet(oldSet: DocumentSet): DocumentSet;
1165 private comparator;
1166 private keyedMap;
1167 private sortedSet;
1168 /** The default ordering is by key if the comparator is omitted */
1169 constructor(comp?: DocumentComparator);
1170 has(key: _DocumentKey): boolean;
1171 get(key: _DocumentKey): Document_2 | null;
1172 first(): Document_2 | null;
1173 last(): Document_2 | null;
1174 isEmpty(): boolean;
1175 /**
1176 * Returns the index of the provided key in the document set, or -1 if the
1177 * document key is not present in the set;
1178 */
1179 indexOf(key: _DocumentKey): number;
1180 get size(): number;
1181 /** Iterates documents in order defined by "comparator" */
1182 forEach(cb: (doc: Document_2) => void): void;
1183 /** Inserts or updates a document with the same key */
1184 add(doc: Document_2): DocumentSet;
1185 /** Deletes a document with a given key */
1186 delete(key: _DocumentKey): DocumentSet;
1187 isEqual(other: DocumentSet | null | undefined): boolean;
1188 toString(): string;
1189 private copy;
1190}
1191
1192/**
1193 * A `DocumentSnapshot` contains data read from a document in your Firestore
1194 * database. The data can be extracted with `.data()` or `.get(<field>)` to
1195 * get a specific field.
1196 *
1197 * For a `DocumentSnapshot` that points to a non-existing document, any data
1198 * access will return 'undefined'. You can use the `exists()` method to
1199 * explicitly verify a document's existence.
1200 */
1201export declare class DocumentSnapshot<T = DocumentData> extends DocumentSnapshot_2<T> {
1202 readonly _firestore: Firestore;
1203 private readonly _firestoreImpl;
1204 /**
1205 * Metadata about the `DocumentSnapshot`, including information about its
1206 * source and local modifications.
1207 */
1208 readonly metadata: SnapshotMetadata;
1209 /** @hideconstructor protected */
1210 constructor(_firestore: Firestore, userDataWriter: AbstractUserDataWriter, key: _DocumentKey, document: Document_2 | null, metadata: SnapshotMetadata, converter: UntypedFirestoreDataConverter<T> | null);
1211 /**
1212 * Returns whether or not the data exists. True if the document exists.
1213 */
1214 exists(): this is QueryDocumentSnapshot<T>;
1215 /**
1216 * Retrieves all fields in the document as an `Object`. Returns `undefined` if
1217 * the document doesn't exist.
1218 *
1219 * By default, `serverTimestamp()` values that have not yet been
1220 * set to their final value will be returned as `null`. You can override
1221 * this by passing an options object.
1222 *
1223 * @param options - An options object to configure how data is retrieved from
1224 * the snapshot (for example the desired behavior for server timestamps that
1225 * have not yet been set to their final value).
1226 * @returns An `Object` containing all fields in the document or `undefined` if
1227 * the document doesn't exist.
1228 */
1229 data(options?: SnapshotOptions): T | undefined;
1230 /**
1231 * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
1232 * document or field doesn't exist.
1233 *
1234 * By default, a `serverTimestamp()` that has not yet been set to
1235 * its final value will be returned as `null`. You can override this by
1236 * passing an options object.
1237 *
1238 * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
1239 * field.
1240 * @param options - An options object to configure how the field is retrieved
1241 * from the snapshot (for example the desired behavior for server timestamps
1242 * that have not yet been set to their final value).
1243 * @returns The data at the specified field location or undefined if no such
1244 * field exists in the document.
1245 */
1246 get(fieldPath: string | FieldPath, options?: SnapshotOptions): any;
1247}
1248
1249/**
1250 * A `DocumentSnapshot` contains data read from a document in your Firestore
1251 * database. The data can be extracted with `.data()` or `.get(<field>)` to
1252 * get a specific field.
1253 *
1254 * For a `DocumentSnapshot` that points to a non-existing document, any data
1255 * access will return 'undefined'. You can use the `exists()` method to
1256 * explicitly verify a document's existence.
1257 */
1258declare class DocumentSnapshot_2<T = DocumentData> {
1259 _firestore: Firestore_2;
1260 _userDataWriter: AbstractUserDataWriter;
1261 _key: _DocumentKey;
1262 _document: Document_2 | null;
1263 _converter: UntypedFirestoreDataConverter<T> | null;
1264 /** @hideconstructor protected */
1265 constructor(_firestore: Firestore_2, _userDataWriter: AbstractUserDataWriter, _key: _DocumentKey, _document: Document_2 | null, _converter: UntypedFirestoreDataConverter<T> | null);
1266 /** Property of the `DocumentSnapshot` that provides the document's ID. */
1267 get id(): string;
1268 /**
1269 * The `DocumentReference` for the document included in the `DocumentSnapshot`.
1270 */
1271 get ref(): DocumentReference<T>;
1272 /**
1273 * Signals whether or not the document at the snapshot's location exists.
1274 *
1275 * @returns true if the document exists.
1276 */
1277 exists(): this is QueryDocumentSnapshot_2<T>;
1278 /**
1279 * Retrieves all fields in the document as an `Object`. Returns `undefined` if
1280 * the document doesn't exist.
1281 *
1282 * @returns An `Object` containing all fields in the document or `undefined`
1283 * if the document doesn't exist.
1284 */
1285 data(): T | undefined;
1286 /**
1287 * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
1288 * document or field doesn't exist.
1289 *
1290 * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
1291 * field.
1292 * @returns The data at the specified field location or undefined if no such
1293 * field exists in the document.
1294 */
1295 get(fieldPath: string | FieldPath): any;
1296}
1297
1298declare type DocumentVersionMap = SortedMap<_DocumentKey, SnapshotVersion>;
1299
1300declare interface DocumentViewChange {
1301 type: ChangeType;
1302 doc: Document_2;
1303}
1304
1305/**
1306 * An AppCheck token provider that always yields an empty token.
1307 * @internal
1308 */
1309export declare class _EmptyAppCheckTokenProvider implements CredentialsProvider<string> {
1310 getToken(): Promise<Token | null>;
1311 invalidateToken(): void;
1312 start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener<string>): void;
1313 shutdown(): void;
1314}
1315
1316/**
1317 * A CredentialsProvider that always yields an empty token.
1318 * @internal
1319 */
1320export declare class _EmptyAuthCredentialsProvider implements CredentialsProvider<User> {
1321 getToken(): Promise<Token | null>;
1322 invalidateToken(): void;
1323 start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener<User>): void;
1324 shutdown(): void;
1325}
1326export { EmulatorMockTokenOptions }
1327
1328/**
1329 * Attempts to enable persistent storage, if possible.
1330 *
1331 * Must be called before any other functions (other than
1332 * {@link initializeFirestore}, {@link (getFirestore:1)} or
1333 * {@link clearIndexedDbPersistence}.
1334 *
1335 * If this fails, `enableIndexedDbPersistence()` will reject the promise it
1336 * returns. Note that even after this failure, the {@link Firestore} instance will
1337 * remain usable, however offline persistence will be disabled.
1338 *
1339 * There are several reasons why this can fail, which can be identified by
1340 * the `code` on the error.
1341 *
1342 * * failed-precondition: The app is already open in another browser tab.
1343 * * unimplemented: The browser is incompatible with the offline
1344 * persistence implementation.
1345 *
1346 * @param firestore - The {@link Firestore} instance to enable persistence for.
1347 * @param persistenceSettings - Optional settings object to configure
1348 * persistence.
1349 * @returns A `Promise` that represents successfully enabling persistent storage.
1350 */
1351export declare function enableIndexedDbPersistence(firestore: Firestore, persistenceSettings?: PersistenceSettings): Promise<void>;
1352
1353/**
1354 * Attempts to enable multi-tab persistent storage, if possible. If enabled
1355 * across all tabs, all operations share access to local persistence, including
1356 * shared execution of queries and latency-compensated local document updates
1357 * across all connected instances.
1358 *
1359 * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise
1360 * it returns. Note that even after this failure, the {@link Firestore} instance will
1361 * remain usable, however offline persistence will be disabled.
1362 *
1363 * There are several reasons why this can fail, which can be identified by
1364 * the `code` on the error.
1365 *
1366 * * failed-precondition: The app is already open in another browser tab and
1367 * multi-tab is not enabled.
1368 * * unimplemented: The browser is incompatible with the offline
1369 * persistence implementation.
1370 *
1371 * @param firestore - The {@link Firestore} instance to enable persistence for.
1372 * @returns A `Promise` that represents successfully enabling persistent
1373 * storage.
1374 */
1375export declare function enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise<void>;
1376
1377/**
1378 * Re-enables use of the network for this {@link Firestore} instance after a prior
1379 * call to {@link disableNetwork}.
1380 *
1381 * @returns A `Promise` that is resolved once the network has been enabled.
1382 */
1383export declare function enableNetwork(firestore: Firestore): Promise<void>;
1384
1385/**
1386 * Creates a {@link QueryConstraint} that modifies the result set to end at the
1387 * provided document (inclusive). The end position is relative to the order of
1388 * the query. The document must contain all of the fields provided in the
1389 * orderBy of the query.
1390 *
1391 * @param snapshot - The snapshot of the document to end at.
1392 * @returns A {@link QueryConstraint} to pass to `query()`
1393 */
1394export declare function endAt(snapshot: DocumentSnapshot_2<unknown>): QueryConstraint;
1395
1396/**
1397 * Creates a {@link QueryConstraint} that modifies the result set to end at the
1398 * provided fields relative to the order of the query. The order of the field
1399 * values must match the order of the order by clauses of the query.
1400 *
1401 * @param fieldValues - The field values to end this query at, in order
1402 * of the query's order by.
1403 * @returns A {@link QueryConstraint} to pass to `query()`
1404 */
1405export declare function endAt(...fieldValues: unknown[]): QueryConstraint;
1406
1407/**
1408 * Creates a {@link QueryConstraint} that modifies the result set to end before the
1409 * provided document (exclusive). The end position is relative to the order of
1410 * the query. The document must contain all of the fields provided in the
1411 * orderBy of the query.
1412 *
1413 * @param snapshot - The snapshot of the document to end before.
1414 * @returns A {@link QueryConstraint} to pass to `query()`
1415 */
1416export declare function endBefore(snapshot: DocumentSnapshot_2<unknown>): QueryConstraint;
1417
1418/**
1419 * Creates a {@link QueryConstraint} that modifies the result set to end before the
1420 * provided fields relative to the order of the query. The order of the field
1421 * values must match the order of the order by clauses of the query.
1422 *
1423 * @param fieldValues - The field values to end this query before, in order
1424 * of the query's order by.
1425 * @returns A {@link QueryConstraint} to pass to `query()`
1426 */
1427export declare function endBefore(...fieldValues: unknown[]): QueryConstraint;
1428
1429/**
1430 * @internal
1431 */
1432export declare function ensureFirestoreConfigured(firestore: Firestore): FirestoreClient;
1433
1434declare interface Entry<K, V> {
1435 key: K;
1436 value: V;
1437}
1438
1439/**
1440 * EventManager is responsible for mapping queries to query event emitters.
1441 * It handles "fan-out". -- Identical queries will re-use the same watch on the
1442 * backend.
1443 *
1444 * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be
1445 * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This
1446 * allows users to tree-shake the Watch logic.
1447 */
1448declare interface EventManager {
1449 onListen?: (query: Query_2) => Promise<ViewSnapshot>;
1450 onUnlisten?: (query: Query_2) => Promise<void>;
1451}
1452
1453/**
1454 * Locally writes `mutations` on the async queue.
1455 * @internal
1456 */
1457export declare function executeWrite(firestore: Firestore, mutations: Mutation[]): Promise<void>;
1458
1459declare 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';
1460
1461/**
1462 * An index definition for field indexes in Firestore.
1463 *
1464 * Every index is associated with a collection. The definition contains a list
1465 * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or
1466 * `CONTAINS` for ArrayContains/ArrayContainsAny queries).
1467 *
1468 * Unlike the backend, the SDK does not differentiate between collection or
1469 * collection group-scoped indices. Every index can be used for both single
1470 * collection and collection group queries.
1471 */
1472declare class FieldIndex {
1473 /**
1474 * The index ID. Returns -1 if the index ID is not available (e.g. the index
1475 * has not yet been persisted).
1476 */
1477 readonly indexId: number;
1478 /** The collection ID this index applies to. */
1479 readonly collectionGroup: string;
1480 /** The field segments for this index. */
1481 readonly fields: IndexSegment[];
1482 /** Shows how up-to-date the index is for the current user. */
1483 readonly indexState: IndexState_2;
1484 /** An ID for an index that has not yet been added to persistence. */
1485 static UNKNOWN_ID: number;
1486 constructor(
1487 /**
1488 * The index ID. Returns -1 if the index ID is not available (e.g. the index
1489 * has not yet been persisted).
1490 */
1491 indexId: number,
1492 /** The collection ID this index applies to. */
1493 collectionGroup: string,
1494 /** The field segments for this index. */
1495 fields: IndexSegment[],
1496 /** Shows how up-to-date the index is for the current user. */
1497 indexState: IndexState_2);
1498}
1499
1500/**
1501 * Provides a set of fields that can be used to partially patch a document.
1502 * FieldMask is used in conjunction with ObjectValue.
1503 * Examples:
1504 * foo - Overwrites foo entirely with the provided value. If foo is not
1505 * present in the companion ObjectValue, the field is deleted.
1506 * foo.bar - Overwrites only the field bar of the object foo.
1507 * If foo is not an object, foo is replaced with an object
1508 * containing foo
1509 */
1510declare class FieldMask {
1511 readonly fields: _FieldPath[];
1512 constructor(fields: _FieldPath[]);
1513 static empty(): FieldMask;
1514 /**
1515 * Returns a new FieldMask object that is the result of adding all the given
1516 * fields paths to this field mask.
1517 */
1518 unionWith(extraFields: _FieldPath[]): FieldMask;
1519 /**
1520 * Verifies that `fieldPath` is included by at least one field in this field
1521 * mask.
1522 *
1523 * This is an O(n) operation, where `n` is the size of the field mask.
1524 */
1525 covers(fieldPath: _FieldPath): boolean;
1526 isEqual(other: FieldMask): boolean;
1527}
1528
1529/**
1530 * A `FieldPath` refers to a field in a document. The path may consist of a
1531 * single field name (referring to a top-level field in the document), or a
1532 * list of field names (referring to a nested field in the document).
1533 *
1534 * Create a `FieldPath` by providing field names. If more than one field
1535 * name is provided, the path will point to a nested field in a document.
1536 */
1537export declare class FieldPath {
1538 /** Internal representation of a Firestore field path. */
1539 readonly _internalPath: _FieldPath;
1540 /**
1541 * Creates a `FieldPath` from the provided field names. If more than one field
1542 * name is provided, the path will point to a nested field in a document.
1543 *
1544 * @param fieldNames - A list of field names.
1545 */
1546 constructor(...fieldNames: string[]);
1547 /**
1548 * Returns true if this `FieldPath` is equal to the provided one.
1549 *
1550 * @param other - The `FieldPath` to compare against.
1551 * @returns true if this `FieldPath` is equal to the provided one.
1552 */
1553 isEqual(other: FieldPath): boolean;
1554}
1555
1556/**
1557 * A dot-separated path for navigating sub-objects within a document.
1558 * @internal
1559 */
1560export declare class _FieldPath extends BasePath<_FieldPath> {
1561 protected construct(segments: string[], offset?: number, length?: number): _FieldPath;
1562 /**
1563 * Returns true if the string could be used as a segment in a field path
1564 * without escaping.
1565 */
1566 private static isValidIdentifier;
1567 canonicalString(): string;
1568 toString(): string;
1569 /**
1570 * Returns true if this field references the key of a document.
1571 */
1572 isKeyField(): boolean;
1573 /**
1574 * The field designating the key of a document.
1575 */
1576 static keyField(): _FieldPath;
1577 /**
1578 * Parses a field string from the given server-formatted string.
1579 *
1580 * - Splitting the empty string is not allowed (for now at least).
1581 * - Empty segments within the string (e.g. if there are two consecutive
1582 * separators) are not allowed.
1583 *
1584 * TODO(b/37244157): we should make this more strict. Right now, it allows
1585 * non-identifier path components, even if they aren't escaped.
1586 */
1587 static fromServerFormat(path: string): _FieldPath;
1588 static emptyPath(): _FieldPath;
1589}
1590
1591/** A field path and the TransformOperation to perform upon it. */
1592declare class FieldTransform {
1593 readonly field: _FieldPath;
1594 readonly transform: TransformOperation;
1595 constructor(field: _FieldPath, transform: TransformOperation);
1596}
1597
1598declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME';
1599
1600/**
1601 * Sentinel values that can be used when writing document fields with `set()`
1602 * or `update()`.
1603 */
1604export declare abstract class FieldValue {
1605 _methodName: string;
1606 /**
1607 * @param _methodName - The public API endpoint that returns this class.
1608 * @hideconstructor
1609 */
1610 constructor(_methodName: string);
1611 /** Compares `FieldValue`s for equality. */
1612 abstract isEqual(other: FieldValue): boolean;
1613 abstract _toFieldTransform(context: ParseContext): FieldTransform | null;
1614}
1615
1616declare abstract class Filter {
1617 abstract matches(doc: Document_2): boolean;
1618}
1619
1620/**
1621 * The Cloud Firestore service interface.
1622 *
1623 * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
1624 */
1625export declare class Firestore extends Firestore_2 {
1626 /**
1627 * Whether it's a {@link Firestore} or Firestore Lite instance.
1628 */
1629 type: 'firestore-lite' | 'firestore';
1630 readonly _queue: AsyncQueue;
1631 readonly _persistenceKey: string;
1632 _firestoreClient: FirestoreClient | undefined;
1633 /** @hideconstructor */
1634 constructor(authCredentialsProvider: CredentialsProvider<User>, appCheckCredentialsProvider: CredentialsProvider<string>, databaseId: _DatabaseId, app?: FirebaseApp);
1635 _terminate(): Promise<void>;
1636}
1637
1638/**
1639 * The Cloud Firestore service interface.
1640 *
1641 * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
1642 */
1643declare class Firestore_2 implements FirestoreService {
1644 _authCredentials: CredentialsProvider<User>;
1645 _appCheckCredentials: CredentialsProvider<string>;
1646 readonly _databaseId: _DatabaseId;
1647 readonly _app?: FirebaseApp | undefined;
1648 /**
1649 * Whether it's a Firestore or Firestore Lite instance.
1650 */
1651 type: 'firestore-lite' | 'firestore';
1652 readonly _persistenceKey: string;
1653 private _settings;
1654 private _settingsFrozen;
1655 private _terminateTask?;
1656 /** @hideconstructor */
1657 constructor(_authCredentials: CredentialsProvider<User>, _appCheckCredentials: CredentialsProvider<string>, _databaseId: _DatabaseId, _app?: FirebaseApp | undefined);
1658 /**
1659 * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
1660 * instance.
1661 */
1662 get app(): FirebaseApp;
1663 get _initialized(): boolean;
1664 get _terminated(): boolean;
1665 _setSettings(settings: PrivateSettings): void;
1666 _getSettings(): FirestoreSettingsImpl;
1667 _freezeSettings(): FirestoreSettingsImpl;
1668 _delete(): Promise<void>;
1669 /** Returns a JSON-serializable representation of this `Firestore` instance. */
1670 toJSON(): object;
1671 /**
1672 * Terminates all components used by this client. Subclasses can override
1673 * this method to clean up their own dependencies, but must also call this
1674 * method.
1675 *
1676 * Only ever called once.
1677 */
1678 protected _terminate(): Promise<void>;
1679}
1680
1681/**
1682 * FirestoreClient is a top-level class that constructs and owns all of the
1683 * pieces of the client SDK architecture. It is responsible for creating the
1684 * async queue that is shared by all of the other components in the system.
1685 */
1686declare class FirestoreClient {
1687 private authCredentials;
1688 private appCheckCredentials;
1689 /**
1690 * Asynchronous queue responsible for all of our internal processing. When
1691 * we get incoming work from the user (via public API) or the network
1692 * (incoming GRPC messages), we should always schedule onto this queue.
1693 * This ensures all of our work is properly serialized (e.g. we don't
1694 * start processing a new operation while the previous one is waiting for
1695 * an async I/O to complete).
1696 */
1697 asyncQueue: AsyncQueue;
1698 private databaseInfo;
1699 private user;
1700 private readonly clientId;
1701 private authCredentialListener;
1702 private appCheckCredentialListener;
1703 offlineComponents?: OfflineComponentProvider;
1704 onlineComponents?: OnlineComponentProvider;
1705 constructor(authCredentials: CredentialsProvider<User>, appCheckCredentials: CredentialsProvider<string>,
1706 /**
1707 * Asynchronous queue responsible for all of our internal processing. When
1708 * we get incoming work from the user (via public API) or the network
1709 * (incoming GRPC messages), we should always schedule onto this queue.
1710 * This ensures all of our work is properly serialized (e.g. we don't
1711 * start processing a new operation while the previous one is waiting for
1712 * an async I/O to complete).
1713 */
1714 asyncQueue: AsyncQueue, databaseInfo: DatabaseInfo);
1715 getConfiguration(): Promise<ComponentConfiguration>;
1716 setCredentialChangeListener(listener: (user: User) => Promise<void>): void;
1717 setAppCheckTokenChangeListener(listener: (appCheckToken: string, user: User) => Promise<void>): void;
1718 /**
1719 * Checks that the client has not been terminated. Ensures that other methods on
1720 * this class cannot be called after the client is terminated.
1721 */
1722 verifyNotTerminated(): void;
1723 terminate(): Promise<void>;
1724}
1725
1726/**
1727 * Converter used by `withConverter()` to transform user objects of type `T`
1728 * into Firestore data.
1729 *
1730 * Using the converter allows you to specify generic type arguments when
1731 * storing and retrieving objects from Firestore.
1732 *
1733 * @example
1734 * ```typescript
1735 * class Post {
1736 * constructor(readonly title: string, readonly author: string) {}
1737 *
1738 * toString(): string {
1739 * return this.title + ', by ' + this.author;
1740 * }
1741 * }
1742 *
1743 * const postConverter = {
1744 * toFirestore(post: WithFieldValue<Post>): DocumentData {
1745 * return {title: post.title, author: post.author};
1746 * },
1747 * fromFirestore(
1748 * snapshot: QueryDocumentSnapshot,
1749 * options: SnapshotOptions
1750 * ): Post {
1751 * const data = snapshot.data(options)!;
1752 * return new Post(data.title, data.author);
1753 * }
1754 * };
1755 *
1756 * const postSnap = await firebase.firestore()
1757 * .collection('posts')
1758 * .withConverter(postConverter)
1759 * .doc().get();
1760 * const post = postSnap.data();
1761 * if (post !== undefined) {
1762 * post.title; // string
1763 * post.toString(); // Should be defined
1764 * post.someNonExistentProperty; // TS error
1765 * }
1766 * ```
1767 */
1768export declare interface FirestoreDataConverter<T> extends FirestoreDataConverter_2<T> {
1769 /**
1770 * Called by the Firestore SDK to convert a custom model object of type `T`
1771 * into a plain JavaScript object (suitable for writing directly to the
1772 * Firestore database). To use `set()` with `merge` and `mergeFields`,
1773 * `toFirestore()` must be defined with `PartialWithFieldValue<T>`.
1774 *
1775 * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as
1776 * {@link (deleteField:1)} to be used as property values.
1777 */
1778 toFirestore(modelObject: WithFieldValue<T>): DocumentData;
1779 /**
1780 * Called by the Firestore SDK to convert a custom model object of type `T`
1781 * into a plain JavaScript object (suitable for writing directly to the
1782 * Firestore database). Used with {@link (setDoc:1)}, {@link (WriteBatch.set:1)}
1783 * and {@link (Transaction.set:1)} with `merge:true` or `mergeFields`.
1784 *
1785 * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow
1786 * FieldValues such as {@link (arrayUnion:1)} to be used as property values.
1787 * It also supports nested `Partial` by allowing nested fields to be
1788 * omitted.
1789 */
1790 toFirestore(modelObject: PartialWithFieldValue<T>, options: SetOptions): DocumentData;
1791 /**
1792 * Called by the Firestore SDK to convert Firestore data into an object of
1793 * type T. You can access your data by calling: `snapshot.data(options)`.
1794 *
1795 * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata.
1796 * @param options - The `SnapshotOptions` from the initial call to `data()`.
1797 */
1798 fromFirestore(snapshot: QueryDocumentSnapshot<DocumentData>, options?: SnapshotOptions): T;
1799}
1800
1801/**
1802 * Converter used by `withConverter()` to transform user objects of type `T`
1803 * into Firestore data.
1804 *
1805 * Using the converter allows you to specify generic type arguments when
1806 * storing and retrieving objects from Firestore.
1807 *
1808 * @example
1809 * ```typescript
1810 * class Post {
1811 * constructor(readonly title: string, readonly author: string) {}
1812 *
1813 * toString(): string {
1814 * return this.title + ', by ' + this.author;
1815 * }
1816 * }
1817 *
1818 * const postConverter = {
1819 * toFirestore(post: WithFieldValue<Post>): DocumentData {
1820 * return {title: post.title, author: post.author};
1821 * },
1822 * fromFirestore(snapshot: QueryDocumentSnapshot): Post {
1823 * const data = snapshot.data(options)!;
1824 * return new Post(data.title, data.author);
1825 * }
1826 * };
1827 *
1828 * const postSnap = await firebase.firestore()
1829 * .collection('posts')
1830 * .withConverter(postConverter)
1831 * .doc().get();
1832 * const post = postSnap.data();
1833 * if (post !== undefined) {
1834 * post.title; // string
1835 * post.toString(); // Should be defined
1836 * post.someNonExistentProperty; // TS error
1837 * }
1838 * ```
1839 */
1840declare interface FirestoreDataConverter_2<T> {
1841 /**
1842 * Called by the Firestore SDK to convert a custom model object of type `T`
1843 * into a plain Javascript object (suitable for writing directly to the
1844 * Firestore database). Used with {@link @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#(WriteBatch.set:1)}
1845 * and {@link @firebase/firestore/lite#(Transaction.set:1)}.
1846 *
1847 * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as
1848 * {@link (deleteField:1)} to be used as property values.
1849 */
1850 toFirestore(modelObject: WithFieldValue<T>): DocumentData;
1851 /**
1852 * Called by the Firestore SDK to convert a custom model object of type `T`
1853 * into a plain Javascript object (suitable for writing directly to the
1854 * Firestore database). Used with {@link @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#(WriteBatch.set:1)}
1855 * and {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` or `mergeFields`.
1856 *
1857 * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow
1858 * FieldValues such as {@link (arrayUnion:1)} to be used as property values.
1859 * It also supports nested `Partial` by allowing nested fields to be
1860 * omitted.
1861 */
1862 toFirestore(modelObject: PartialWithFieldValue<T>, options: SetOptions): DocumentData;
1863 /**
1864 * Called by the Firestore SDK to convert Firestore data into an object of
1865 * type T. You can access your data by calling: `snapshot.data()`.
1866 *
1867 * @param snapshot - A `QueryDocumentSnapshot` containing your data and
1868 * metadata.
1869 */
1870 fromFirestore(snapshot: QueryDocumentSnapshot_2<DocumentData>): T;
1871}
1872
1873/** An error returned by a Firestore operation. */
1874export declare class FirestoreError extends FirebaseError {
1875 /**
1876 * The backend error code associated with this error.
1877 */
1878 readonly code: FirestoreErrorCode;
1879 /**
1880 * A custom error description.
1881 */
1882 readonly message: string;
1883 /** The stack of the error. */
1884 readonly stack?: string;
1885 /** @hideconstructor */
1886 constructor(
1887 /**
1888 * The backend error code associated with this error.
1889 */
1890 code: FirestoreErrorCode,
1891 /**
1892 * A custom error description.
1893 */
1894 message: string);
1895}
1896
1897/**
1898 * The set of Firestore status codes. The codes are the same at the ones
1899 * exposed by gRPC here:
1900 * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
1901 *
1902 * Possible values:
1903 * - 'cancelled': The operation was cancelled (typically by the caller).
1904 * - 'unknown': Unknown error or an error from a different error domain.
1905 * - 'invalid-argument': Client specified an invalid argument. Note that this
1906 * differs from 'failed-precondition'. 'invalid-argument' indicates
1907 * arguments that are problematic regardless of the state of the system
1908 * (e.g. an invalid field name).
1909 * - 'deadline-exceeded': Deadline expired before operation could complete.
1910 * For operations that change the state of the system, this error may be
1911 * returned even if the operation has completed successfully. For example,
1912 * a successful response from a server could have been delayed long enough
1913 * for the deadline to expire.
1914 * - 'not-found': Some requested document was not found.
1915 * - 'already-exists': Some document that we attempted to create already
1916 * exists.
1917 * - 'permission-denied': The caller does not have permission to execute the
1918 * specified operation.
1919 * - 'resource-exhausted': Some resource has been exhausted, perhaps a
1920 * per-user quota, or perhaps the entire file system is out of space.
1921 * - 'failed-precondition': Operation was rejected because the system is not
1922 * in a state required for the operation's execution.
1923 * - 'aborted': The operation was aborted, typically due to a concurrency
1924 * issue like transaction aborts, etc.
1925 * - 'out-of-range': Operation was attempted past the valid range.
1926 * - 'unimplemented': Operation is not implemented or not supported/enabled.
1927 * - 'internal': Internal errors. Means some invariants expected by
1928 * underlying system has been broken. If you see one of these errors,
1929 * something is very broken.
1930 * - 'unavailable': The service is currently unavailable. This is most likely
1931 * a transient condition and may be corrected by retrying with a backoff.
1932 * - 'data-loss': Unrecoverable data loss or corruption.
1933 * - 'unauthenticated': The request does not have valid authentication
1934 * credentials for the operation.
1935 */
1936export declare type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated';
1937
1938/**
1939 * An interface implemented by FirebaseFirestore that provides compatibility
1940 * with the usage in this file.
1941 *
1942 * This interface mainly exists to remove a cyclic dependency.
1943 */
1944declare interface FirestoreService extends _FirebaseService {
1945 _authCredentials: CredentialsProvider<User>;
1946 _appCheckCredentials: CredentialsProvider<string>;
1947 _persistenceKey: string;
1948 _databaseId: _DatabaseId;
1949 _terminated: boolean;
1950 _freezeSettings(): FirestoreSettingsImpl;
1951}
1952
1953/**
1954 * Specifies custom configurations for your Cloud Firestore instance.
1955 * You must set these before invoking any other methods.
1956 */
1957export declare interface FirestoreSettings extends FirestoreSettings_2 {
1958 /**
1959 * An approximate cache size threshold for the on-disk data. If the cache
1960 * grows beyond this size, Firestore will start removing data that hasn't been
1961 * recently used. The size is not a guarantee that the cache will stay below
1962 * that size, only that if the cache exceeds the given size, cleanup will be
1963 * attempted.
1964 *
1965 * The default value is 40 MB. The threshold must be set to at least 1 MB, and
1966 * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection.
1967 */
1968 cacheSizeBytes?: number;
1969 /**
1970 * Forces the SDK’s underlying network transport (WebChannel) to use
1971 * long-polling. Each response from the backend will be closed immediately
1972 * after the backend sends data (by default responses are kept open in
1973 * case the backend has more data to send). This avoids incompatibility
1974 * issues with certain proxies, antivirus software, etc. that incorrectly
1975 * buffer traffic indefinitely. Use of this option will cause some
1976 * performance degradation though.
1977 *
1978 * This setting cannot be used with `experimentalAutoDetectLongPolling` and
1979 * may be removed in a future release. If you find yourself using it to
1980 * work around a specific network reliability issue, please tell us about
1981 * it in https://github.com/firebase/firebase-js-sdk/issues/1674.
1982 */
1983 experimentalForceLongPolling?: boolean;
1984 /**
1985 * Configures the SDK's underlying transport (WebChannel) to automatically
1986 * detect if long-polling should be used. This is very similar to
1987 * `experimentalForceLongPolling`, but only uses long-polling if required.
1988 *
1989 * This setting will likely be enabled by default in future releases and
1990 * cannot be combined with `experimentalForceLongPolling`.
1991 */
1992 experimentalAutoDetectLongPolling?: boolean;
1993}
1994
1995/**
1996 * Specifies custom configurations for your Cloud Firestore instance.
1997 * You must set these before invoking any other methods.
1998 */
1999declare interface FirestoreSettings_2 {
2000 /** The hostname to connect to. */
2001 host?: string;
2002 /** Whether to use SSL when connecting. */
2003 ssl?: boolean;
2004 /**
2005 * Whether to skip nested properties that are set to `undefined` during
2006 * object serialization. If set to `true`, these properties are skipped
2007 * and not written to Firestore. If set to `false` or omitted, the SDK
2008 * throws an exception when it encounters properties of type `undefined`.
2009 */
2010 ignoreUndefinedProperties?: boolean;
2011}
2012
2013/**
2014 * A concrete type describing all the values that can be applied via a
2015 * user-supplied `FirestoreSettings` object. This is a separate type so that
2016 * defaults can be supplied and the value can be checked for equality.
2017 */
2018declare class FirestoreSettingsImpl {
2019 /** The hostname to connect to. */
2020 readonly host: string;
2021 /** Whether to use SSL when connecting. */
2022 readonly ssl: boolean;
2023 readonly cacheSizeBytes: number;
2024 readonly experimentalForceLongPolling: boolean;
2025 readonly experimentalAutoDetectLongPolling: boolean;
2026 readonly ignoreUndefinedProperties: boolean;
2027 readonly useFetchStreams: boolean;
2028 credentials?: any;
2029 constructor(settings: PrivateSettings);
2030 isEqual(other: FirestoreSettingsImpl): boolean;
2031}
2032
2033declare namespace firestoreV1ApiClientInterfaces {
2034 interface ArrayValue {
2035 values?: Value[];
2036 }
2037 interface BatchGetDocumentsRequest {
2038 database?: string;
2039 documents?: string[];
2040 mask?: DocumentMask;
2041 transaction?: string;
2042 newTransaction?: TransactionOptions;
2043 readTime?: string;
2044 }
2045 interface BatchGetDocumentsResponse {
2046 found?: Document;
2047 missing?: string;
2048 transaction?: string;
2049 readTime?: string;
2050 }
2051 interface BeginTransactionRequest {
2052 options?: TransactionOptions;
2053 }
2054 interface BeginTransactionResponse {
2055 transaction?: string;
2056 }
2057 interface CollectionSelector {
2058 collectionId?: string;
2059 allDescendants?: boolean;
2060 }
2061 interface CommitRequest {
2062 database?: string;
2063 writes?: Write[];
2064 transaction?: string;
2065 }
2066 interface CommitResponse {
2067 writeResults?: WriteResult[];
2068 commitTime?: string;
2069 }
2070 interface CompositeFilter {
2071 op?: CompositeFilterOp;
2072 filters?: Filter[];
2073 }
2074 interface Cursor {
2075 values?: Value[];
2076 before?: boolean;
2077 }
2078 interface Document {
2079 name?: string;
2080 fields?: ApiClientObjectMap<Value>;
2081 createTime?: Timestamp_2;
2082 updateTime?: Timestamp_2;
2083 }
2084 interface DocumentChange {
2085 document?: Document;
2086 targetIds?: number[];
2087 removedTargetIds?: number[];
2088 }
2089 interface DocumentDelete {
2090 document?: string;
2091 removedTargetIds?: number[];
2092 readTime?: Timestamp_2;
2093 }
2094 interface DocumentMask {
2095 fieldPaths?: string[];
2096 }
2097 interface DocumentRemove {
2098 document?: string;
2099 removedTargetIds?: number[];
2100 readTime?: string;
2101 }
2102 interface DocumentTransform {
2103 document?: string;
2104 fieldTransforms?: FieldTransform[];
2105 }
2106 interface DocumentsTarget {
2107 documents?: string[];
2108 }
2109 interface Empty {
2110 }
2111 interface ExistenceFilter {
2112 targetId?: number;
2113 count?: number;
2114 }
2115 interface FieldFilter {
2116 field?: FieldReference;
2117 op?: FieldFilterOp;
2118 value?: Value;
2119 }
2120 interface FieldReference {
2121 fieldPath?: string;
2122 }
2123 interface FieldTransform {
2124 fieldPath?: string;
2125 setToServerValue?: FieldTransformSetToServerValue;
2126 appendMissingElements?: ArrayValue;
2127 removeAllFromArray?: ArrayValue;
2128 increment?: Value;
2129 }
2130 interface Filter {
2131 compositeFilter?: CompositeFilter;
2132 fieldFilter?: FieldFilter;
2133 unaryFilter?: UnaryFilter;
2134 }
2135 interface Index {
2136 name?: string;
2137 collectionId?: string;
2138 fields?: IndexField[];
2139 state?: IndexState;
2140 }
2141 interface IndexField {
2142 fieldPath?: string;
2143 mode?: IndexFieldMode;
2144 }
2145 interface LatLng {
2146 latitude?: number;
2147 longitude?: number;
2148 }
2149 interface ListCollectionIdsRequest {
2150 pageSize?: number;
2151 pageToken?: string;
2152 }
2153 interface ListCollectionIdsResponse {
2154 collectionIds?: string[];
2155 nextPageToken?: string;
2156 }
2157 interface ListDocumentsResponse {
2158 documents?: Document[];
2159 nextPageToken?: string;
2160 }
2161 interface ListIndexesResponse {
2162 indexes?: Index[];
2163 nextPageToken?: string;
2164 }
2165 interface ListenRequest {
2166 addTarget?: Target;
2167 removeTarget?: number;
2168 labels?: ApiClientObjectMap<string>;
2169 }
2170 interface ListenResponse {
2171 targetChange?: TargetChange;
2172 documentChange?: DocumentChange;
2173 documentDelete?: DocumentDelete;
2174 documentRemove?: DocumentRemove;
2175 filter?: ExistenceFilter;
2176 }
2177 interface MapValue {
2178 fields?: ApiClientObjectMap<Value>;
2179 }
2180 interface Operation {
2181 name?: string;
2182 metadata?: ApiClientObjectMap<any>;
2183 done?: boolean;
2184 error?: Status;
2185 response?: ApiClientObjectMap<any>;
2186 }
2187 interface Order {
2188 field?: FieldReference;
2189 direction?: OrderDirection;
2190 }
2191 interface Precondition {
2192 exists?: boolean;
2193 updateTime?: Timestamp_2;
2194 }
2195 interface Projection {
2196 fields?: FieldReference[];
2197 }
2198 interface QueryTarget {
2199 parent?: string;
2200 structuredQuery?: StructuredQuery;
2201 }
2202 interface ReadOnly {
2203 readTime?: string;
2204 }
2205 interface ReadWrite {
2206 retryTransaction?: string;
2207 }
2208 interface RollbackRequest {
2209 transaction?: string;
2210 }
2211 interface RunQueryRequest {
2212 parent?: string;
2213 structuredQuery?: StructuredQuery;
2214 transaction?: string;
2215 newTransaction?: TransactionOptions;
2216 readTime?: string;
2217 }
2218 interface RunQueryResponse {
2219 transaction?: string;
2220 document?: Document;
2221 readTime?: string;
2222 skippedResults?: number;
2223 }
2224 interface RunAggregationQueryRequest {
2225 parent?: string;
2226 structuredAggregationQuery?: StructuredAggregationQuery;
2227 transaction?: string;
2228 newTransaction?: TransactionOptions;
2229 readTime?: string;
2230 }
2231 interface RunAggregationQueryResponse {
2232 result?: AggregationResult;
2233 transaction?: string;
2234 readTime?: string;
2235 }
2236 interface AggregationResult {
2237 aggregateFields?: ApiClientObjectMap<Value>;
2238 }
2239 interface StructuredAggregationQuery {
2240 structuredQuery?: StructuredQuery;
2241 aggregations?: Aggregation[];
2242 }
2243 interface Aggregation {
2244 count?: Count;
2245 alias?: string;
2246 }
2247 interface Count {
2248 upTo?: number;
2249 }
2250 interface Status {
2251 code?: number;
2252 message?: string;
2253 details?: Array<ApiClientObjectMap<any>>;
2254 }
2255 interface StructuredQuery {
2256 select?: Projection;
2257 from?: CollectionSelector[];
2258 where?: Filter;
2259 orderBy?: Order[];
2260 startAt?: Cursor;
2261 endAt?: Cursor;
2262 offset?: number;
2263 limit?: number | {
2264 value: number;
2265 };
2266 }
2267 interface Target {
2268 query?: QueryTarget;
2269 documents?: DocumentsTarget;
2270 resumeToken?: string | Uint8Array;
2271 readTime?: Timestamp_2;
2272 targetId?: number;
2273 once?: boolean;
2274 }
2275 interface TargetChange {
2276 targetChangeType?: TargetChangeTargetChangeType;
2277 targetIds?: number[];
2278 cause?: Status;
2279 resumeToken?: string | Uint8Array;
2280 readTime?: Timestamp_2;
2281 }
2282 interface TransactionOptions {
2283 readOnly?: ReadOnly;
2284 readWrite?: ReadWrite;
2285 }
2286 interface UnaryFilter {
2287 op?: UnaryFilterOp;
2288 field?: FieldReference;
2289 }
2290 interface Value {
2291 nullValue?: ValueNullValue;
2292 booleanValue?: boolean;
2293 integerValue?: string | number;
2294 doubleValue?: string | number;
2295 timestampValue?: Timestamp_2;
2296 stringValue?: string;
2297 bytesValue?: string | Uint8Array;
2298 referenceValue?: string;
2299 geoPointValue?: LatLng;
2300 arrayValue?: ArrayValue;
2301 mapValue?: MapValue;
2302 }
2303 interface Write {
2304 update?: Document;
2305 delete?: string;
2306 verify?: string;
2307 transform?: DocumentTransform;
2308 updateMask?: DocumentMask;
2309 updateTransforms?: FieldTransform[];
2310 currentDocument?: Precondition;
2311 }
2312 interface WriteRequest {
2313 streamId?: string;
2314 writes?: Write[];
2315 streamToken?: string | Uint8Array;
2316 labels?: ApiClientObjectMap<string>;
2317 }
2318 interface WriteResponse {
2319 streamId?: string;
2320 streamToken?: string | Uint8Array;
2321 writeResults?: WriteResult[];
2322 commitTime?: Timestamp_2;
2323 }
2324 interface WriteResult {
2325 updateTime?: Timestamp_2;
2326 transformResults?: Value[];
2327 }
2328}
2329
2330declare interface FirstPartyCredentialsSettings {
2331 ['type']: 'gapi';
2332 ['client']: unknown;
2333 ['sessionIndex']: string;
2334 ['iamToken']: string | null;
2335 ['authTokenFactory']: AuthTokenFactory | null;
2336}
2337
2338/**
2339 * @license
2340 * Copyright 2017 Google LLC
2341 *
2342 * Licensed under the Apache License, Version 2.0 (the "License");
2343 * you may not use this file except in compliance with the License.
2344 * You may obtain a copy of the License at
2345 *
2346 * http://www.apache.org/licenses/LICENSE-2.0
2347 *
2348 * Unless required by applicable law or agreed to in writing, software
2349 * distributed under the License is distributed on an "AS IS" BASIS,
2350 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2351 * See the License for the specific language governing permissions and
2352 * limitations under the License.
2353 */
2354declare type FulfilledHandler<T, R> = ((result: T) => R | PersistencePromise<R>) | null;
2355
2356/**
2357 * @license
2358 * Copyright 2017 Google LLC
2359 *
2360 * Licensed under the Apache License, Version 2.0 (the "License");
2361 * you may not use this file except in compliance with the License.
2362 * You may obtain a copy of the License at
2363 *
2364 * http://www.apache.org/licenses/LICENSE-2.0
2365 *
2366 * Unless required by applicable law or agreed to in writing, software
2367 * distributed under the License is distributed on an "AS IS" BASIS,
2368 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2369 * See the License for the specific language governing permissions and
2370 * limitations under the License.
2371 */
2372/**
2373 * An immutable object representing a geographic location in Firestore. The
2374 * location is represented as latitude/longitude pair.
2375 *
2376 * Latitude values are in the range of [-90, 90].
2377 * Longitude values are in the range of [-180, 180].
2378 */
2379export declare class GeoPoint {
2380 private _lat;
2381 private _long;
2382 /**
2383 * Creates a new immutable `GeoPoint` object with the provided latitude and
2384 * longitude values.
2385 * @param latitude - The latitude as number between -90 and 90.
2386 * @param longitude - The longitude as number between -180 and 180.
2387 */
2388 constructor(latitude: number, longitude: number);
2389 /**
2390 * The latitude of this `GeoPoint` instance.
2391 */
2392 get latitude(): number;
2393 /**
2394 * The longitude of this `GeoPoint` instance.
2395 */
2396 get longitude(): number;
2397 /**
2398 * Returns true if this `GeoPoint` is equal to the provided one.
2399 *
2400 * @param other - The `GeoPoint` to compare against.
2401 * @returns true if this `GeoPoint` is equal to the provided one.
2402 */
2403 isEqual(other: GeoPoint): boolean;
2404 /** Returns a JSON-serializable representation of this GeoPoint. */
2405 toJSON(): {
2406 latitude: number;
2407 longitude: number;
2408 };
2409 /**
2410 * Actually private to JS consumers of our API, so this function is prefixed
2411 * with an underscore.
2412 */
2413 _compareTo(other: GeoPoint): number;
2414}
2415
2416/**
2417 * Calculates the number of documents in the result set of the given query,
2418 * without actually downloading the documents.
2419 *
2420 * Using this function to count the documents is efficient because only the
2421 * final count, not the documents' data, is downloaded. This function can even
2422 * count the documents if the result set would be prohibitively large to
2423 * download entirely (e.g. thousands of documents).
2424 *
2425 * The result received from the server is presented, unaltered, without
2426 * considering any local state. That is, documents in the local cache are not
2427 * taken into consideration, neither are local modifications not yet
2428 * synchronized with the server. Previously-downloaded results, if any, are not
2429 * used: every request using this source necessarily involves a round trip to
2430 * the server.
2431 *
2432 * @param query - The query whose result set size to calculate.
2433 * @returns A Promise that will be resolved with the count; the count can be
2434 * retrieved from `snapshot.data().count`, where `snapshot` is the
2435 * `AggregateQuerySnapshot` to which the returned Promise resolves.
2436 */
2437export declare function getCountFromServer(query: Query<unknown>): Promise<AggregateQuerySnapshot<{
2438 count: AggregateField<number>;
2439}>>;
2440
2441/**
2442 * Reads the document referred to by this `DocumentReference`.
2443 *
2444 * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting
2445 * for data from the server, but it may return cached data or fail if you are
2446 * offline and the server cannot be reached. To specify this behavior, invoke
2447 * {@link getDocFromCache} or {@link getDocFromServer}.
2448 *
2449 * @param reference - The reference of the document to fetch.
2450 * @returns A Promise resolved with a `DocumentSnapshot` containing the
2451 * current document contents.
2452 */
2453export declare function getDoc<T>(reference: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
2454
2455/**
2456 * Reads the document referred to by this `DocumentReference` from cache.
2457 * Returns an error if the document is not currently cached.
2458 *
2459 * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
2460 * current document contents.
2461 */
2462export declare function getDocFromCache<T>(reference: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
2463
2464/**
2465 * Reads the document referred to by this `DocumentReference` from the server.
2466 * Returns an error if the network is not available.
2467 *
2468 * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
2469 * current document contents.
2470 */
2471export declare function getDocFromServer<T>(reference: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
2472
2473/**
2474 * Executes the query and returns the results as a `QuerySnapshot`.
2475 *
2476 * Note: `getDocs()` attempts to provide up-to-date data when possible by
2477 * waiting for data from the server, but it may return cached data or fail if
2478 * you are offline and the server cannot be reached. To specify this behavior,
2479 * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.
2480 *
2481 * @returns A `Promise` that will be resolved with the results of the query.
2482 */
2483export declare function getDocs<T>(query: Query<T>): Promise<QuerySnapshot<T>>;
2484
2485/**
2486 * Executes the query and returns the results as a `QuerySnapshot` from cache.
2487 * Returns an error if the document is not currently cached.
2488 *
2489 * @returns A `Promise` that will be resolved with the results of the query.
2490 */
2491export declare function getDocsFromCache<T>(query: Query<T>): Promise<QuerySnapshot<T>>;
2492
2493/**
2494 * Executes the query and returns the results as a `QuerySnapshot` from the
2495 * server. Returns an error if the network is not available.
2496 *
2497 * @returns A `Promise` that will be resolved with the results of the query.
2498 */
2499export declare function getDocsFromServer<T>(query: Query<T>): Promise<QuerySnapshot<T>>;
2500
2501/**
2502 * Returns the existing default {@link Firestore} instance that is associated with the
2503 * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new
2504 * instance with default settings.
2505 *
2506 * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}
2507 * instance is associated with.
2508 * @returns The {@link Firestore} instance of the provided app.
2509 */
2510export declare function getFirestore(app: FirebaseApp): Firestore;
2511
2512/**
2513 * Returns the existing {@link Firestore} instance that is associated with the
2514 * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new
2515 * instance with default settings.
2516 *
2517 * @param databaseId - The name of database.
2518 * @returns The {@link Firestore} instance of the provided app.
2519 * @internal
2520 */
2521export declare function getFirestore(databaseId: string): Firestore;
2522
2523/**
2524 * Returns the existing default {@link Firestore} instance that is associated with the
2525 * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new
2526 * instance with default settings.
2527 *
2528 * @returns The {@link Firestore} instance of the provided app.
2529 */
2530export declare function getFirestore(): Firestore;
2531
2532/**
2533 * Returns the existing default {@link Firestore} instance that is associated with the
2534 * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new
2535 * instance with default settings.
2536 *
2537 * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}
2538 * instance is associated with.
2539 * @param databaseId - The name of database.
2540 * @returns The {@link Firestore} instance of the provided app.
2541 * @internal
2542 */
2543export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore;
2544
2545/**
2546 * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
2547 * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
2548 * the given value.
2549 *
2550 * If either the operand or the current field value uses floating point
2551 * precision, all arithmetic follows IEEE 754 semantics. If both values are
2552 * integers, values outside of JavaScript's safe number range
2553 * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
2554 * precision loss. Furthermore, once processed by the Firestore backend, all
2555 * integer operations are capped between -2^63 and 2^63-1.
2556 *
2557 * If the current field value is not of type `number`, or if the field does not
2558 * yet exist, the transformation sets the field to the given value.
2559 *
2560 * @param n - The value to increment by.
2561 * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
2562 * `updateDoc()`
2563 */
2564export declare function increment(n: number): FieldValue;
2565
2566/**
2567 * The SDK definition of a Firestore index.
2568 * @beta
2569 */
2570export declare interface Index {
2571 /** The ID of the collection to index. */
2572 readonly collectionGroup: string;
2573 /** A list of fields to index. */
2574 readonly fields?: IndexField[];
2575 [key: string]: unknown;
2576}
2577
2578/**
2579 * A list of Firestore indexes to speed up local query execution.
2580 *
2581 * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format}
2582 * for a description of the format of the index definition.
2583 * @beta
2584 */
2585export declare interface IndexConfiguration {
2586 /** A list of all Firestore indexes. */
2587 readonly indexes?: Index[];
2588 [key: string]: unknown;
2589}
2590
2591/**
2592 * A single field element in an index configuration.
2593 * @beta
2594 */
2595export declare interface IndexField {
2596 /** The field path to index. */
2597 readonly fieldPath: string;
2598 /**
2599 * What type of array index to create. Set to `CONTAINS` for `array-contains`
2600 * and `array-contains-any` indexes.
2601 *
2602 * Only one of `arrayConfig` or `order` should be set;
2603 */
2604 readonly arrayConfig?: 'CONTAINS';
2605 /**
2606 * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for
2607 * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters.
2608 *
2609 * Only one of `arrayConfig` or `order` should be set.
2610 */
2611 readonly order?: 'ASCENDING' | 'DESCENDING';
2612 [key: string]: unknown;
2613}
2614
2615declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING';
2616
2617/** The type of the index, e.g. for which type of query it can be used. */
2618declare const enum IndexKind {
2619 /**
2620 * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.
2621 */
2622 ASCENDING = 0,
2623 /**
2624 * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.
2625 */
2626 DESCENDING = 1,
2627 /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */
2628 CONTAINS = 2
2629}
2630
2631/**
2632 * Represents a set of indexes that are used to execute queries efficiently.
2633 *
2634 * Currently the only index is a [collection id] =&gt; [parent path] index, used
2635 * to execute Collection Group queries.
2636 */
2637declare interface IndexManager {
2638 /**
2639 * Creates an index entry mapping the collectionId (last segment of the path)
2640 * to the parent path (either the containing document location or the empty
2641 * path for root-level collections). Index entries can be retrieved via
2642 * getCollectionParents().
2643 *
2644 * NOTE: Currently we don't remove index entries. If this ends up being an
2645 * issue we can devise some sort of GC strategy.
2646 */
2647 addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: _ResourcePath): PersistencePromise<void>;
2648 /**
2649 * Retrieves all parent locations containing the given collectionId, as a
2650 * list of paths (each path being either a document location or the empty
2651 * path for a root-level collection).
2652 */
2653 getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise<_ResourcePath[]>;
2654 /**
2655 * Adds a field path index.
2656 *
2657 * Values for this index are persisted via the index backfill, which runs
2658 * asynchronously in the background. Once the first values are written,
2659 * an index can be used to serve partial results for any matching queries.
2660 * Any unindexed portion of the database will continue to be served via
2661 * collection scons.
2662 */
2663 addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise<void>;
2664 /** Removes the given field index and deletes all index values. */
2665 deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise<void>;
2666 /**
2667 * Returns a list of field indexes that correspond to the specified collection
2668 * group.
2669 *
2670 * @param collectionGroup The collection group to get matching field indexes
2671 * for.
2672 * @return A collection of field indexes for the specified collection group.
2673 */
2674 getFieldIndexes(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise<FieldIndex[]>;
2675 /** Returns all configured field indexes. */
2676 getFieldIndexes(transaction: PersistenceTransaction): PersistencePromise<FieldIndex[]>;
2677 /**
2678 * Returns the type of index (if any) that can be used to serve the given
2679 * target.
2680 */
2681 getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise<IndexType>;
2682 /**
2683 * Returns the documents that match the given target based on the provided
2684 * index or `null` if the target does not have a matching index.
2685 */
2686 getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise<_DocumentKey[] | null>;
2687 /**
2688 * Returns the next collection group to update. Returns `null` if no group
2689 * exists.
2690 */
2691 getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise<string | null>;
2692 /**
2693 * Sets the collection group's latest read time.
2694 *
2695 * This method updates the index offset for all field indices for the
2696 * collection group and increments their sequence number. Subsequent calls to
2697 * `getNextCollectionGroupToUpdate()` will return a different collection group
2698 * (unless only one collection group is configured).
2699 */
2700 updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise<void>;
2701 /** Updates the index entries for the provided documents. */
2702 updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise<void>;
2703 /**
2704 * Iterates over all field indexes that are used to serve the given target,
2705 * and returns the minimum offset of them all.
2706 */
2707 getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise<IndexOffset>;
2708 /** Returns the minimum offset for the given collection group. */
2709 getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise<IndexOffset>;
2710}
2711
2712/**
2713 * Stores the latest read time, document and batch ID that were processed for an
2714 * index.
2715 */
2716declare class IndexOffset {
2717 /**
2718 * The latest read time version that has been indexed by Firestore for this
2719 * field index.
2720 */
2721 readonly readTime: SnapshotVersion;
2722 /**
2723 * The key of the last document that was indexed for this query. Use
2724 * `DocumentKey.empty()` if no document has been indexed.
2725 */
2726 readonly documentKey: _DocumentKey;
2727 readonly largestBatchId: number;
2728 constructor(
2729 /**
2730 * The latest read time version that has been indexed by Firestore for this
2731 * field index.
2732 */
2733 readTime: SnapshotVersion,
2734 /**
2735 * The key of the last document that was indexed for this query. Use
2736 * `DocumentKey.empty()` if no document has been indexed.
2737 */
2738 documentKey: _DocumentKey, largestBatchId: number);
2739 /** Returns an offset that sorts before all regular offsets. */
2740 static min(): IndexOffset;
2741 /** Returns an offset that sorts after all regular offsets. */
2742 static max(): IndexOffset;
2743}
2744
2745/** An index component consisting of field path and index type. */
2746declare class IndexSegment {
2747 /** The field path of the component. */
2748 readonly fieldPath: _FieldPath;
2749 /** The fields sorting order. */
2750 readonly kind: IndexKind;
2751 constructor(
2752 /** The field path of the component. */
2753 fieldPath: _FieldPath,
2754 /** The fields sorting order. */
2755 kind: IndexKind);
2756}
2757
2758declare type IndexState = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR';
2759
2760/**
2761 * Stores the "high water mark" that indicates how updated the Index is for the
2762 * current user.
2763 */
2764declare class IndexState_2 {
2765 /**
2766 * Indicates when the index was last updated (relative to other indexes).
2767 */
2768 readonly sequenceNumber: number;
2769 /** The the latest indexed read time, document and batch id. */
2770 readonly offset: IndexOffset;
2771 constructor(
2772 /**
2773 * Indicates when the index was last updated (relative to other indexes).
2774 */
2775 sequenceNumber: number,
2776 /** The the latest indexed read time, document and batch id. */
2777 offset: IndexOffset);
2778 /** The state of an index that has not yet been backfilled. */
2779 static empty(): IndexState_2;
2780}
2781
2782/** Represents the index state as it relates to a particular target. */
2783declare const enum IndexType {
2784 /** Indicates that no index could be found for serving the target. */
2785 NONE = 0,
2786 /**
2787 * Indicates that only a "partial index" could be found for serving the
2788 * target. A partial index is one which does not have a segment for every
2789 * filter/orderBy in the target.
2790 */
2791 PARTIAL = 1,
2792 /**
2793 * Indicates that a "full index" could be found for serving the target. A full
2794 * index is one which has a segment for every filter/orderBy in the target.
2795 */
2796 FULL = 2
2797}
2798
2799/**
2800 * Initializes a new instance of {@link Firestore} with the provided settings.
2801 * Can only be called before any other function, including
2802 * {@link (getFirestore:1)}. If the custom settings are empty, this function is
2803 * equivalent to calling {@link (getFirestore:1)}.
2804 *
2805 * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will
2806 * be associated.
2807 * @param settings - A settings object to configure the {@link Firestore} instance.
2808 * @param databaseId - The name of database.
2809 * @returns A newly initialized {@link Firestore} instance.
2810 */
2811export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings, databaseId?: string): Firestore;
2812
2813/**
2814 * True if and only if the Base64 conversion functions are available.
2815 * @internal
2816 */
2817export declare function _isBase64Available(): boolean;
2818
2819/**
2820 * Creates a {@link QueryConstraint} that only returns the first matching documents.
2821 *
2822 * @param limit - The maximum number of items to return.
2823 * @returns The created {@link Query}.
2824 */
2825export declare function limit(limit: number): QueryConstraint;
2826
2827/**
2828 * Creates a {@link QueryConstraint} that only returns the last matching documents.
2829 *
2830 * You must specify at least one `orderBy` clause for `limitToLast` queries,
2831 * otherwise an exception will be thrown during execution.
2832 *
2833 * @param limit - The maximum number of items to return.
2834 * @returns The created {@link Query}.
2835 */
2836export declare function limitToLast(limit: number): QueryConstraint;
2837
2838declare const enum LimitType {
2839 First = "F",
2840 Last = "L"
2841}
2842
2843/** LimitType enum. */
2844declare type LimitType_2 = 'FIRST' | 'LAST';
2845
2846declare type ListenSequenceNumber = number;
2847
2848declare class LLRBEmptyNode<K, V> {
2849 get key(): never;
2850 get value(): never;
2851 get color(): never;
2852 get left(): never;
2853 get right(): never;
2854 size: number;
2855 copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null, right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null): LLRBEmptyNode<K, V>;
2856 insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V>;
2857 remove(key: K, comparator: Comparator<K>): LLRBEmptyNode<K, V>;
2858 isEmpty(): boolean;
2859 inorderTraversal(action: (k: K, v: V) => boolean): boolean;
2860 reverseTraversal(action: (k: K, v: V) => boolean): boolean;
2861 minKey(): K | null;
2862 maxKey(): K | null;
2863 isRed(): boolean;
2864 checkMaxDepth(): boolean;
2865 protected check(): 0;
2866}
2867
2868declare class LLRBNode<K, V> {
2869 key: K;
2870 value: V;
2871 readonly color: boolean;
2872 readonly left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
2873 readonly right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
2874 readonly size: number;
2875 static EMPTY: LLRBEmptyNode<any, any>;
2876 static RED: boolean;
2877 static BLACK: boolean;
2878 constructor(key: K, value: V, color?: boolean, left?: LLRBNode<K, V> | LLRBEmptyNode<K, V>, right?: LLRBNode<K, V> | LLRBEmptyNode<K, V>);
2879 copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null, right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null): LLRBNode<K, V>;
2880 isEmpty(): boolean;
2881 inorderTraversal<T>(action: (k: K, v: V) => T): T;
2882 reverseTraversal<T>(action: (k: K, v: V) => T): T;
2883 private min;
2884 minKey(): K | null;
2885 maxKey(): K | null;
2886 insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V>;
2887 private removeMin;
2888 remove(key: K, comparator: Comparator<K>): LLRBNode<K, V> | LLRBEmptyNode<K, V>;
2889 isRed(): boolean;
2890 private fixUp;
2891 private moveRedLeft;
2892 private moveRedRight;
2893 private rotateLeft;
2894 private rotateRight;
2895 private colorFlip;
2896 checkMaxDepth(): boolean;
2897 protected check(): number;
2898}
2899
2900/**
2901 * Loads a Firestore bundle into the local cache.
2902 *
2903 * @param firestore - The {@link Firestore} instance to load bundles for.
2904 * @param bundleData - An object representing the bundle to be loaded. Valid
2905 * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.
2906 *
2907 * @returns A `LoadBundleTask` object, which notifies callers with progress
2908 * updates, and completion or error events. It can be used as a
2909 * `Promise<LoadBundleTaskProgress>`.
2910 */
2911export declare function loadBundle(firestore: Firestore, bundleData: ReadableStream<Uint8Array> | ArrayBuffer | string): LoadBundleTask;
2912
2913/**
2914 * Represents the task of loading a Firestore bundle. It provides progress of bundle
2915 * loading, as well as task completion and error events.
2916 *
2917 * The API is compatible with `Promise<LoadBundleTaskProgress>`.
2918 */
2919export declare class LoadBundleTask implements PromiseLike<LoadBundleTaskProgress> {
2920 private _progressObserver;
2921 private _taskCompletionResolver;
2922 private _lastProgress;
2923 /**
2924 * Registers functions to listen to bundle loading progress events.
2925 * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur
2926 * each time a Firestore document is loaded from the bundle.
2927 * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the
2928 * error, and there should be no more updates after this.
2929 * @param complete - Called when the loading task is complete.
2930 */
2931 onProgress(next?: (progress: LoadBundleTaskProgress) => unknown, error?: (err: Error) => unknown, complete?: () => void): void;
2932 /**
2933 * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.
2934 *
2935 * @param onRejected - Called when an error occurs during bundle loading.
2936 */
2937 catch<R>(onRejected: (a: Error) => R | PromiseLike<R>): Promise<R | LoadBundleTaskProgress>;
2938 /**
2939 * Implements the `Promise<LoadBundleTaskProgress>.then` interface.
2940 *
2941 * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.
2942 * The update will always have its `taskState` set to `"Success"`.
2943 * @param onRejected - Called when an error occurs during bundle loading.
2944 */
2945 then<T, R>(onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike<T>, onRejected?: (a: Error) => R | PromiseLike<R>): Promise<T | R>;
2946 /**
2947 * Notifies all observers that bundle loading has completed, with a provided
2948 * `LoadBundleTaskProgress` object.
2949 *
2950 * @private
2951 */
2952 _completeWith(progress: LoadBundleTaskProgress): void;
2953 /**
2954 * Notifies all observers that bundle loading has failed, with a provided
2955 * `Error` as the reason.
2956 *
2957 * @private
2958 */
2959 _failWith(error: FirestoreError): void;
2960 /**
2961 * Notifies a progress update of loading a bundle.
2962 * @param progress - The new progress.
2963 *
2964 * @private
2965 */
2966 _updateProgress(progress: LoadBundleTaskProgress): void;
2967}
2968
2969/**
2970 * Represents a progress update or a final state from loading bundles.
2971 */
2972export declare interface LoadBundleTaskProgress {
2973 /** How many documents have been loaded. */
2974 documentsLoaded: number;
2975 /** How many documents are in the bundle being loaded. */
2976 totalDocuments: number;
2977 /** How many bytes have been loaded. */
2978 bytesLoaded: number;
2979 /** How many bytes are in the bundle being loaded. */
2980 totalBytes: number;
2981 /** Current task state. */
2982 taskState: TaskState;
2983}
2984
2985/**
2986 * A readonly view of the local state of all documents we're tracking (i.e. we
2987 * have a cached version in remoteDocumentCache or local mutations for the
2988 * document). The view is computed by applying the mutations in the
2989 * MutationQueue to the RemoteDocumentCache.
2990 */
2991declare class LocalDocumentsView {
2992 readonly remoteDocumentCache: RemoteDocumentCache;
2993 readonly mutationQueue: MutationQueue;
2994 readonly documentOverlayCache: DocumentOverlayCache;
2995 readonly indexManager: IndexManager;
2996 constructor(remoteDocumentCache: RemoteDocumentCache, mutationQueue: MutationQueue, documentOverlayCache: DocumentOverlayCache, indexManager: IndexManager);
2997 /**
2998 * Get the local view of the document identified by `key`.
2999 *
3000 * @returns Local view of the document or null if we don't have any cached
3001 * state for it.
3002 */
3003 getDocument(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise<Document_2>;
3004 /**
3005 * Gets the local view of the documents identified by `keys`.
3006 *
3007 * If we don't have cached state for a document in `keys`, a NoDocument will
3008 * be stored for that key in the resulting set.
3009 */
3010 getDocuments(transaction: PersistenceTransaction, keys: DocumentKeySet): PersistencePromise<DocumentMap>;
3011 /**
3012 * Similar to `getDocuments`, but creates the local view from the given
3013 * `baseDocs` without retrieving documents from the local store.
3014 *
3015 * @param transaction - The transaction this operation is scoped to.
3016 * @param docs - The documents to apply local mutations to get the local views.
3017 * @param existenceStateChanged - The set of document keys whose existence state
3018 * is changed. This is useful to determine if some documents overlay needs
3019 * to be recalculated.
3020 */
3021 getLocalViewOfDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap, existenceStateChanged?: DocumentKeySet): PersistencePromise<DocumentMap>;
3022 /**
3023 * Gets the overlayed documents for the given document map, which will include
3024 * the local view of those documents and a `FieldMask` indicating which fields
3025 * are mutated locally, `null` if overlay is a Set or Delete mutation.
3026 */
3027 getOverlayedDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap): PersistencePromise<OverlayedDocumentMap>;
3028 /**
3029 * Fetches the overlays for {@code docs} and adds them to provided overlay map
3030 * if the map does not already contain an entry for the given document key.
3031 */
3032 private populateOverlays;
3033 /**
3034 * Computes the local view for the given documents.
3035 *
3036 * @param docs - The documents to compute views for. It also has the base
3037 * version of the documents.
3038 * @param overlays - The overlays that need to be applied to the given base
3039 * version of the documents.
3040 * @param existenceStateChanged - A set of documents whose existence states
3041 * might have changed. This is used to determine if we need to re-calculate
3042 * overlays from mutation queues.
3043 * @return A map represents the local documents view.
3044 */
3045 computeViews(transaction: PersistenceTransaction, docs: MutableDocumentMap, overlays: OverlayMap, existenceStateChanged: DocumentKeySet): PersistencePromise<OverlayedDocumentMap>;
3046 private recalculateAndSaveOverlays;
3047 /**
3048 * Recalculates overlays by reading the documents from remote document cache
3049 * first, and saves them after they are calculated.
3050 */
3051 recalculateAndSaveOverlaysForDocumentKeys(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise<DocumentKeyMap<FieldMask | null>>;
3052 /**
3053 * Performs a query against the local view of all documents.
3054 *
3055 * @param transaction - The persistence transaction.
3056 * @param query - The query to match documents against.
3057 * @param offset - Read time and key to start scanning by (exclusive).
3058 */
3059 getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset): PersistencePromise<DocumentMap>;
3060 /**
3061 * Given a collection group, returns the next documents that follow the provided offset, along
3062 * with an updated batch ID.
3063 *
3064 * <p>The documents returned by this method are ordered by remote version from the provided
3065 * offset. If there are no more remote documents after the provided offset, documents with
3066 * mutations in order of batch id from the offset are returned. Since all documents in a batch are
3067 * returned together, the total number of documents returned can exceed {@code count}.
3068 *
3069 * @param transaction
3070 * @param collectionGroup The collection group for the documents.
3071 * @param offset The offset to index into.
3072 * @param count The number of documents to return
3073 * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.
3074 */
3075 getNextDocuments(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, count: number): PersistencePromise<LocalWriteResult>;
3076 private getDocumentsMatchingDocumentQuery;
3077 private getDocumentsMatchingCollectionGroupQuery;
3078 private getDocumentsMatchingCollectionQuery;
3079 /** Returns a base document that can be used to apply `overlay`. */
3080 private getBaseDocument;
3081}
3082
3083declare interface LocalStore {
3084 collectGarbage(garbageCollector: LruGarbageCollector): Promise<LruResults>;
3085 /** Manages the list of active field and collection indices. */
3086 indexManager: IndexManager;
3087 /**
3088 * The "local" view of all documents (layering mutationQueue on top of
3089 * remoteDocumentCache).
3090 */
3091 localDocuments: LocalDocumentsView;
3092}
3093
3094/** The result of a write to the local store. */
3095declare interface LocalWriteResult {
3096 batchId: BatchId;
3097 changes: DocumentMap;
3098}
3099export { LogLevel }
3100
3101/**
3102 * @internal
3103 */
3104export declare function _logWarn(msg: string, ...obj: unknown[]): void;
3105
3106declare interface LruGarbageCollector {
3107 readonly params: LruParams;
3108 collect(txn: PersistenceTransaction, activeTargetIds: ActiveTargets): PersistencePromise<LruResults>;
3109 /** Given a percentile of target to collect, returns the number of targets to collect. */
3110 calculateTargetCount(txn: PersistenceTransaction, percentile: number): PersistencePromise<number>;
3111 /** Returns the nth sequence number, counting in order from the smallest. */
3112 nthSequenceNumber(txn: PersistenceTransaction, n: number): PersistencePromise<number>;
3113 /**
3114 * Removes documents that have a sequence number equal to or less than the
3115 * upper bound and are not otherwise pinned.
3116 */
3117 removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise<number>;
3118 getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;
3119 /**
3120 * Removes targets with a sequence number equal to or less than the given
3121 * upper bound, and removes document associations with those targets.
3122 */
3123 removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise<number>;
3124}
3125
3126declare class LruParams {
3127 readonly cacheSizeCollectionThreshold: number;
3128 readonly percentileToCollect: number;
3129 readonly maximumSequenceNumbersToCollect: number;
3130 private static readonly DEFAULT_COLLECTION_PERCENTILE;
3131 private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT;
3132 static withCacheSize(cacheSize: number): LruParams;
3133 static readonly DEFAULT: LruParams;
3134 static readonly DISABLED: LruParams;
3135 constructor(cacheSizeCollectionThreshold: number, percentileToCollect: number, maximumSequenceNumbersToCollect: number);
3136}
3137
3138/**
3139 * Describes the results of a garbage collection run. `didRun` will be set to
3140 * `false` if collection was skipped (either it is disabled or the cache size
3141 * has not hit the threshold). If collection ran, the other fields will be
3142 * filled in with the details of the results.
3143 */
3144declare interface LruResults {
3145 readonly didRun: boolean;
3146 readonly sequenceNumbersCollected: number;
3147 readonly targetsRemoved: number;
3148 readonly documentsRemoved: number;
3149}
3150
3151declare type MapValue = firestoreV1ApiClientInterfaces.MapValue;
3152
3153/**
3154 * Represents a document in Firestore with a key, version, data and whether it
3155 * has local mutations applied to it.
3156 *
3157 * Documents can transition between states via `convertToFoundDocument()`,
3158 * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
3159 * not transition to one of these states even after all mutations have been
3160 * applied, `isValidDocument()` returns false and the document should be removed
3161 * from all views.
3162 */
3163declare class MutableDocument implements Document_2 {
3164 readonly key: _DocumentKey;
3165 private documentType;
3166 version: SnapshotVersion;
3167 readTime: SnapshotVersion;
3168 data: ObjectValue;
3169 private documentState;
3170 private constructor();
3171 /**
3172 * Creates a document with no known version or data, but which can serve as
3173 * base document for mutations.
3174 */
3175 static newInvalidDocument(documentKey: _DocumentKey): MutableDocument;
3176 /**
3177 * Creates a new document that is known to exist with the given data at the
3178 * given version.
3179 */
3180 static newFoundDocument(documentKey: _DocumentKey, version: SnapshotVersion, value: ObjectValue): MutableDocument;
3181 /** Creates a new document that is known to not exist at the given version. */
3182 static newNoDocument(documentKey: _DocumentKey, version: SnapshotVersion): MutableDocument;
3183 /**
3184 * Creates a new document that is known to exist at the given version but
3185 * whose data is not known (e.g. a document that was updated without a known
3186 * base document).
3187 */
3188 static newUnknownDocument(documentKey: _DocumentKey, version: SnapshotVersion): MutableDocument;
3189 /**
3190 * Changes the document type to indicate that it exists and that its version
3191 * and data are known.
3192 */
3193 convertToFoundDocument(version: SnapshotVersion, value: ObjectValue): MutableDocument;
3194 /**
3195 * Changes the document type to indicate that it doesn't exist at the given
3196 * version.
3197 */
3198 convertToNoDocument(version: SnapshotVersion): MutableDocument;
3199 /**
3200 * Changes the document type to indicate that it exists at a given version but
3201 * that its data is not known (e.g. a document that was updated without a known
3202 * base document).
3203 */
3204 convertToUnknownDocument(version: SnapshotVersion): MutableDocument;
3205 setHasCommittedMutations(): MutableDocument;
3206 setHasLocalMutations(): MutableDocument;
3207 setReadTime(readTime: SnapshotVersion): MutableDocument;
3208 get hasLocalMutations(): boolean;
3209 get hasCommittedMutations(): boolean;
3210 get hasPendingWrites(): boolean;
3211 isValidDocument(): boolean;
3212 isFoundDocument(): boolean;
3213 isNoDocument(): boolean;
3214 isUnknownDocument(): boolean;
3215 isEqual(other: Document_2 | null | undefined): boolean;
3216 mutableCopy(): MutableDocument;
3217 toString(): string;
3218}
3219
3220/** Miscellaneous collection types / constants. */
3221declare type MutableDocumentMap = SortedMap<_DocumentKey, MutableDocument>;
3222
3223/**
3224 * A mutation describes a self-contained change to a document. Mutations can
3225 * create, replace, delete, and update subsets of documents.
3226 *
3227 * Mutations not only act on the value of the document but also its version.
3228 *
3229 * For local mutations (mutations that haven't been committed yet), we preserve
3230 * the existing version for Set and Patch mutations. For Delete mutations, we
3231 * reset the version to 0.
3232 *
3233 * Here's the expected transition table.
3234 *
3235 * MUTATION APPLIED TO RESULTS IN
3236 *
3237 * SetMutation Document(v3) Document(v3)
3238 * SetMutation NoDocument(v3) Document(v0)
3239 * SetMutation InvalidDocument(v0) Document(v0)
3240 * PatchMutation Document(v3) Document(v3)
3241 * PatchMutation NoDocument(v3) NoDocument(v3)
3242 * PatchMutation InvalidDocument(v0) UnknownDocument(v3)
3243 * DeleteMutation Document(v3) NoDocument(v0)
3244 * DeleteMutation NoDocument(v3) NoDocument(v0)
3245 * DeleteMutation InvalidDocument(v0) NoDocument(v0)
3246 *
3247 * For acknowledged mutations, we use the updateTime of the WriteResponse as
3248 * the resulting version for Set and Patch mutations. As deletes have no
3249 * explicit update time, we use the commitTime of the WriteResponse for
3250 * Delete mutations.
3251 *
3252 * If a mutation is acknowledged by the backend but fails the precondition check
3253 * locally, we transition to an `UnknownDocument` and rely on Watch to send us
3254 * the updated version.
3255 *
3256 * Field transforms are used only with Patch and Set Mutations. We use the
3257 * `updateTransforms` message to store transforms, rather than the `transforms`s
3258 * messages.
3259 *
3260 * ## Subclassing Notes
3261 *
3262 * Every type of mutation needs to implement its own applyToRemoteDocument() and
3263 * applyToLocalView() to implement the actual behavior of applying the mutation
3264 * to some source document (see `setMutationApplyToRemoteDocument()` for an
3265 * example).
3266 */
3267declare abstract class Mutation {
3268 abstract readonly type: MutationType;
3269 abstract readonly key: _DocumentKey;
3270 abstract readonly precondition: Precondition;
3271 abstract readonly fieldTransforms: FieldTransform[];
3272 /**
3273 * Returns a `FieldMask` representing the fields that will be changed by
3274 * applying this mutation. Returns `null` if the mutation will overwrite the
3275 * entire document.
3276 */
3277 abstract getFieldMask(): FieldMask | null;
3278}
3279
3280/**
3281 * A batch of mutations that will be sent as one unit to the backend.
3282 */
3283declare class MutationBatch {
3284 batchId: BatchId;
3285 localWriteTime: Timestamp;
3286 baseMutations: Mutation[];
3287 mutations: Mutation[];
3288 /**
3289 * @param batchId - The unique ID of this mutation batch.
3290 * @param localWriteTime - The original write time of this mutation.
3291 * @param baseMutations - Mutations that are used to populate the base
3292 * values when this mutation is applied locally. This can be used to locally
3293 * overwrite values that are persisted in the remote document cache. Base
3294 * mutations are never sent to the backend.
3295 * @param mutations - The user-provided mutations in this mutation batch.
3296 * User-provided mutations are applied both locally and remotely on the
3297 * backend.
3298 */
3299 constructor(batchId: BatchId, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]);
3300 /**
3301 * Applies all the mutations in this MutationBatch to the specified document
3302 * to compute the state of the remote document
3303 *
3304 * @param document - The document to apply mutations to.
3305 * @param batchResult - The result of applying the MutationBatch to the
3306 * backend.
3307 */
3308 applyToRemoteDocument(document: MutableDocument, batchResult: MutationBatchResult): void;
3309 /**
3310 * Computes the local view of a document given all the mutations in this
3311 * batch.
3312 *
3313 * @param document - The document to apply mutations to.
3314 * @param mutatedFields - Fields that have been updated before applying this mutation batch.
3315 * @returns A `FieldMask` representing all the fields that are mutated.
3316 */
3317 applyToLocalView(document: MutableDocument, mutatedFields: FieldMask | null): FieldMask | null;
3318 /**
3319 * Computes the local view for all provided documents given the mutations in
3320 * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to
3321 * replace all the mutation applications.
3322 */
3323 applyToLocalDocumentSet(documentMap: OverlayedDocumentMap, documentsWithoutRemoteVersion: DocumentKeySet): MutationMap;
3324 keys(): DocumentKeySet;
3325 isEqual(other: MutationBatch): boolean;
3326}
3327
3328/** The result of applying a mutation batch to the backend. */
3329declare class MutationBatchResult {
3330 readonly batch: MutationBatch;
3331 readonly commitVersion: SnapshotVersion;
3332 readonly mutationResults: MutationResult[];
3333 /**
3334 * A pre-computed mapping from each mutated document to the resulting
3335 * version.
3336 */
3337 readonly docVersions: DocumentVersionMap;
3338 private constructor();
3339 /**
3340 * Creates a new MutationBatchResult for the given batch and results. There
3341 * must be one result for each mutation in the batch. This static factory
3342 * caches a document=&gt;version mapping (docVersions).
3343 */
3344 static from(batch: MutationBatch, commitVersion: SnapshotVersion, results: MutationResult[]): MutationBatchResult;
3345}
3346
3347declare type MutationMap = DocumentKeyMap<Mutation>;
3348
3349/** A queue of mutations to apply to the remote store. */
3350declare interface MutationQueue {
3351 /** Returns true if this queue contains no mutation batches. */
3352 checkEmpty(transaction: PersistenceTransaction): PersistencePromise<boolean>;
3353 /**
3354 * Creates a new mutation batch and adds it to this mutation queue.
3355 *
3356 * @param transaction - The transaction this operation is scoped to.
3357 * @param localWriteTime - The original write time of this mutation.
3358 * @param baseMutations - Mutations that are used to populate the base values
3359 * when this mutation is applied locally. These mutations are used to locally
3360 * overwrite values that are persisted in the remote document cache.
3361 * @param mutations - The user-provided mutations in this mutation batch.
3362 */
3363 addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise<MutationBatch>;
3364 /**
3365 * Loads the mutation batch with the given batchId.
3366 */
3367 lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise<MutationBatch | null>;
3368 /**
3369 * Gets the first unacknowledged mutation batch after the passed in batchId
3370 * in the mutation queue or null if empty.
3371 *
3372 * @param batchId - The batch to search after, or BATCHID_UNKNOWN for the
3373 * first mutation in the queue.
3374 *
3375 * @returns the next mutation or null if there wasn't one.
3376 */
3377 getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise<MutationBatch | null>;
3378 /**
3379 * Gets the largest (latest) batch id in mutation queue for the current user
3380 * that is pending server response, returns `BATCHID_UNKNOWN` if the queue is
3381 * empty.
3382 *
3383 * @returns the largest batch id in the mutation queue that is not
3384 * acknowledged.
3385 */
3386 getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise<BatchId>;
3387 /** Gets all mutation batches in the mutation queue. */
3388 getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise<MutationBatch[]>;
3389 /**
3390 * Finds all mutation batches that could possibly affect the given
3391 * document key. Not all mutations in a batch will necessarily affect the
3392 * document key, so when looping through the batch you'll need to check that
3393 * the mutation itself matches the key.
3394 *
3395 * Batches are guaranteed to be in sorted order.
3396 *
3397 * Note that because of this requirement implementations are free to return
3398 * mutation batches that don't contain the document key at all if it's
3399 * convenient.
3400 */
3401 getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise<MutationBatch[]>;
3402 /**
3403 * Finds all mutation batches that could possibly affect the given set of
3404 * document keys. Not all mutations in a batch will necessarily affect each
3405 * key, so when looping through the batch you'll need to check that the
3406 * mutation itself matches the key.
3407 *
3408 * Batches are guaranteed to be in sorted order.
3409 *
3410 * Note that because of this requirement implementations are free to return
3411 * mutation batches that don't contain any of the document keys at all if it's
3412 * convenient.
3413 */
3414 getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap<_DocumentKey, unknown>): PersistencePromise<MutationBatch[]>;
3415 /**
3416 * Finds all mutation batches that could affect the results for the given
3417 * query. Not all mutations in a batch will necessarily affect the query, so
3418 * when looping through the batch you'll need to check that the mutation
3419 * itself matches the query.
3420 *
3421 * Batches are guaranteed to be in sorted order.
3422 *
3423 * Note that because of this requirement implementations are free to return
3424 * mutation batches that don't match the query at all if it's convenient.
3425 *
3426 * NOTE: A PatchMutation does not need to include all fields in the query
3427 * filter criteria in order to be a match (but any fields it does contain do
3428 * need to match).
3429 */
3430 getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query_2): PersistencePromise<MutationBatch[]>;
3431 /**
3432 * Removes the given mutation batch from the queue. This is useful in two
3433 * circumstances:
3434 *
3435 * + Removing an applied mutation from the head of the queue
3436 * + Removing a rejected mutation from anywhere in the queue
3437 *
3438 * Multi-Tab Note: This operation should only be called by the primary client.
3439 */
3440 removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise<void>;
3441 /**
3442 * Performs a consistency check, examining the mutation queue for any
3443 * leaks, if possible.
3444 */
3445 performConsistencyCheck(transaction: PersistenceTransaction): PersistencePromise<void>;
3446}
3447
3448/** The result of successfully applying a mutation to the backend. */
3449declare class MutationResult {
3450 /**
3451 * The version at which the mutation was committed:
3452 *
3453 * - For most operations, this is the updateTime in the WriteResult.
3454 * - For deletes, the commitTime of the WriteResponse (because deletes are
3455 * not stored and have no updateTime).
3456 *
3457 * Note that these versions can be different: No-op writes will not change
3458 * the updateTime even though the commitTime advances.
3459 */
3460 readonly version: SnapshotVersion;
3461 /**
3462 * The resulting fields returned from the backend after a mutation
3463 * containing field transforms has been committed. Contains one FieldValue
3464 * for each FieldTransform that was in the mutation.
3465 *
3466 * Will be empty if the mutation did not contain any field transforms.
3467 */
3468 readonly transformResults: Array<Value | null>;
3469 constructor(
3470 /**
3471 * The version at which the mutation was committed:
3472 *
3473 * - For most operations, this is the updateTime in the WriteResult.
3474 * - For deletes, the commitTime of the WriteResponse (because deletes are
3475 * not stored and have no updateTime).
3476 *
3477 * Note that these versions can be different: No-op writes will not change
3478 * the updateTime even though the commitTime advances.
3479 */
3480 version: SnapshotVersion,
3481 /**
3482 * The resulting fields returned from the backend after a mutation
3483 * containing field transforms has been committed. Contains one FieldValue
3484 * for each FieldTransform that was in the mutation.
3485 *
3486 * Will be empty if the mutation did not contain any field transforms.
3487 */
3488 transformResults: Array<Value | null>);
3489}
3490
3491declare const enum MutationType {
3492 Set = 0,
3493 Patch = 1,
3494 Delete = 2,
3495 Verify = 3
3496}
3497
3498/**
3499 * Represents a Query saved by the SDK in its local storage.
3500 */
3501declare interface NamedQuery {
3502 /** The name of the query. */
3503 readonly name: string;
3504 /** The underlying query associated with `name`. */
3505 readonly query: Query_2;
3506 /** The time at which the results for this query were read. */
3507 readonly readTime: SnapshotVersion;
3508}
3509
3510/**
3511 * Reads a Firestore {@link Query} from local cache, identified by the given
3512 * name.
3513 *
3514 * The named queries are packaged into bundles on the server side (along
3515 * with resulting documents), and loaded to local cache using `loadBundle`. Once
3516 * in local cache, use this method to extract a {@link Query} by name.
3517 *
3518 * @param firestore - The {@link Firestore} instance to read the query from.
3519 * @param name - The name of the query.
3520 * @returns A `Promise` that is resolved with the Query or `null`.
3521 */
3522export declare function namedQuery(firestore: Firestore, name: string): Promise<Query | null>;
3523
3524/** Properties of a NamedQuery. */
3525declare interface NamedQuery_2 {
3526 /** NamedQuery name */
3527 name?: string | null;
3528 /** NamedQuery bundledQuery */
3529 bundledQuery?: BundledQuery | null;
3530 /** NamedQuery readTime */
3531 readTime?: Timestamp_2 | null;
3532}
3533
3534/**
3535 * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1,
3536 * 'bar.qux': T2}). Intersect them together to make a single map containing
3537 * all possible keys that are all marked as optional
3538 */
3539export declare type NestedUpdateFields<T extends Record<string, unknown>> = UnionToIntersection<{
3540 [K in keyof T & string]: ChildUpdateFields<K, T[K]>;
3541}[keyof T & string]>;
3542
3543/**
3544 * @license
3545 * Copyright 2017 Google LLC
3546 *
3547 * Licensed under the Apache License, Version 2.0 (the "License");
3548 * you may not use this file except in compliance with the License.
3549 * You may obtain a copy of the License at
3550 *
3551 * http://www.apache.org/licenses/LICENSE-2.0
3552 *
3553 * Unless required by applicable law or agreed to in writing, software
3554 * distributed under the License is distributed on an "AS IS" BASIS,
3555 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3556 * See the License for the specific language governing permissions and
3557 * limitations under the License.
3558 */
3559/**
3560 * A map implementation that uses objects as keys. Objects must have an
3561 * associated equals function and must be immutable. Entries in the map are
3562 * stored together with the key being produced from the mapKeyFn. This map
3563 * automatically handles collisions of keys.
3564 */
3565declare class ObjectMap<KeyType, ValueType> {
3566 private mapKeyFn;
3567 private equalsFn;
3568 /**
3569 * The inner map for a key/value pair. Due to the possibility of collisions we
3570 * keep a list of entries that we do a linear search through to find an actual
3571 * match. Note that collisions should be rare, so we still expect near
3572 * constant time lookups in practice.
3573 */
3574 private inner;
3575 /** The number of entries stored in the map */
3576 private innerSize;
3577 constructor(mapKeyFn: (key: KeyType) => string, equalsFn: (l: KeyType, r: KeyType) => boolean);
3578 /** Get a value for this key, or undefined if it does not exist. */
3579 get(key: KeyType): ValueType | undefined;
3580 has(key: KeyType): boolean;
3581 /** Put this key and value in the map. */
3582 set(key: KeyType, value: ValueType): void;
3583 /**
3584 * Remove this key from the map. Returns a boolean if anything was deleted.
3585 */
3586 delete(key: KeyType): boolean;
3587 forEach(fn: (key: KeyType, val: ValueType) => void): void;
3588 isEmpty(): boolean;
3589 size(): number;
3590}
3591
3592/**
3593 * An ObjectValue represents a MapValue in the Firestore Proto and offers the
3594 * ability to add and remove fields (via the ObjectValueBuilder).
3595 */
3596declare class ObjectValue {
3597 readonly value: {
3598 mapValue: MapValue;
3599 };
3600 constructor(value: {
3601 mapValue: MapValue;
3602 });
3603 static empty(): ObjectValue;
3604 /**
3605 * Returns the value at the given path or null.
3606 *
3607 * @param path - the path to search
3608 * @returns The value at the path or null if the path is not set.
3609 */
3610 field(path: _FieldPath): Value | null;
3611 /**
3612 * Sets the field to the provided value.
3613 *
3614 * @param path - The field path to set.
3615 * @param value - The value to set.
3616 */
3617 set(path: _FieldPath, value: Value): void;
3618 /**
3619 * Sets the provided fields to the provided values.
3620 *
3621 * @param data - A map of fields to values (or null for deletes).
3622 */
3623 setAll(data: Map<_FieldPath, Value | null>): void;
3624 /**
3625 * Removes the field at the specified path. If there is no field at the
3626 * specified path, nothing is changed.
3627 *
3628 * @param path - The field path to remove.
3629 */
3630 delete(path: _FieldPath): void;
3631 isEqual(other: ObjectValue): boolean;
3632 /**
3633 * Returns the map that contains the leaf element of `path`. If the parent
3634 * entry does not yet exist, or if it is not a map, a new map will be created.
3635 */
3636 private getFieldsMap;
3637 /**
3638 * Modifies `fieldsMap` by adding, replacing or deleting the specified
3639 * entries.
3640 */
3641 private applyChanges;
3642 clone(): ObjectValue;
3643}
3644
3645/**
3646 * Initializes and wires components that are needed to interface with the local
3647 * cache. Implementations override `initialize()` to provide all components.
3648 */
3649declare interface OfflineComponentProvider {
3650 persistence: Persistence;
3651 sharedClientState: SharedClientState;
3652 localStore: LocalStore;
3653 gcScheduler: Scheduler | null;
3654 indexBackfillerScheduler: Scheduler | null;
3655 synchronizeTabs: boolean;
3656 initialize(cfg: ComponentConfiguration): Promise<void>;
3657 terminate(): Promise<void>;
3658}
3659
3660/**
3661 * Initializes and wires the components that are needed to interface with the
3662 * network.
3663 */
3664declare class OnlineComponentProvider {
3665 protected localStore: LocalStore;
3666 protected sharedClientState: SharedClientState;
3667 datastore: Datastore;
3668 eventManager: EventManager;
3669 remoteStore: RemoteStore;
3670 syncEngine: SyncEngine;
3671 initialize(offlineComponentProvider: OfflineComponentProvider, cfg: ComponentConfiguration): Promise<void>;
3672 createEventManager(cfg: ComponentConfiguration): EventManager;
3673 createDatastore(cfg: ComponentConfiguration): Datastore;
3674 createRemoteStore(cfg: ComponentConfiguration): RemoteStore;
3675 createSyncEngine(cfg: ComponentConfiguration, startAsPrimary: boolean): SyncEngine;
3676 terminate(): Promise<void>;
3677}
3678
3679/**
3680 * Describes the online state of the Firestore client. Note that this does not
3681 * indicate whether or not the remote store is trying to connect or not. This is
3682 * primarily used by the View / EventManager code to change their behavior while
3683 * offline (e.g. get() calls shouldn't wait for data from the server and
3684 * snapshot events should set metadata.isFromCache=true).
3685 *
3686 * The string values should not be changed since they are persisted in
3687 * WebStorage.
3688 */
3689declare const enum OnlineState {
3690 /**
3691 * The Firestore client is in an unknown online state. This means the client
3692 * is either not actively trying to establish a connection or it is currently
3693 * trying to establish a connection, but it has not succeeded or failed yet.
3694 * Higher-level components should not operate in offline mode.
3695 */
3696 Unknown = "Unknown",
3697 /**
3698 * The client is connected and the connections are healthy. This state is
3699 * reached after a successful connection and there has been at least one
3700 * successful message received from the backends.
3701 */
3702 Online = "Online",
3703 /**
3704 * The client is either trying to establish a connection but failing, or it
3705 * has been explicitly marked offline via a call to disableNetwork().
3706 * Higher-level components should operate in offline mode.
3707 */
3708 Offline = "Offline"
3709}
3710
3711/**
3712 * Attaches a listener for `DocumentSnapshot` events. You may either pass
3713 * individual `onNext` and `onError` callbacks or pass a single observer
3714 * object with `next` and `error` callbacks.
3715 *
3716 * NOTE: Although an `onCompletion` callback can be provided, it will
3717 * never be called because the snapshot stream is never-ending.
3718 *
3719 * @param reference - A reference to the document to listen to.
3720 * @param observer - A single object containing `next` and `error` callbacks.
3721 * @returns An unsubscribe function that can be called to cancel
3722 * the snapshot listener.
3723 */
3724export declare function onSnapshot<T>(reference: DocumentReference<T>, observer: {
3725 next?: (snapshot: DocumentSnapshot<T>) => void;
3726 error?: (error: FirestoreError) => void;
3727 complete?: () => void;
3728}): Unsubscribe;
3729
3730/**
3731 * Attaches a listener for `DocumentSnapshot` events. You may either pass
3732 * individual `onNext` and `onError` callbacks or pass a single observer
3733 * object with `next` and `error` callbacks.
3734 *
3735 * NOTE: Although an `onCompletion` callback can be provided, it will
3736 * never be called because the snapshot stream is never-ending.
3737 *
3738 * @param reference - A reference to the document to listen to.
3739 * @param options - Options controlling the listen behavior.
3740 * @param observer - A single object containing `next` and `error` callbacks.
3741 * @returns An unsubscribe function that can be called to cancel
3742 * the snapshot listener.
3743 */
3744export declare function onSnapshot<T>(reference: DocumentReference<T>, options: SnapshotListenOptions, observer: {
3745 next?: (snapshot: DocumentSnapshot<T>) => void;
3746 error?: (error: FirestoreError) => void;
3747 complete?: () => void;
3748}): Unsubscribe;
3749
3750/**
3751 * Attaches a listener for `DocumentSnapshot` events. You may either pass
3752 * individual `onNext` and `onError` callbacks or pass a single observer
3753 * object with `next` and `error` callbacks.
3754 *
3755 * NOTE: Although an `onCompletion` callback can be provided, it will
3756 * never be called because the snapshot stream is never-ending.
3757 *
3758 * @param reference - A reference to the document to listen to.
3759 * @param onNext - A callback to be called every time a new `DocumentSnapshot`
3760 * is available.
3761 * @param onError - A callback to be called if the listen fails or is
3762 * cancelled. No further callbacks will occur.
3763 * @param onCompletion - Can be provided, but will not be called since streams are
3764 * never ending.
3765 * @returns An unsubscribe function that can be called to cancel
3766 * the snapshot listener.
3767 */
3768export declare function onSnapshot<T>(reference: DocumentReference<T>, onNext: (snapshot: DocumentSnapshot<T>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;
3769
3770/**
3771 * Attaches a listener for `DocumentSnapshot` events. You may either pass
3772 * individual `onNext` and `onError` callbacks or pass a single observer
3773 * object with `next` and `error` callbacks.
3774 *
3775 * NOTE: Although an `onCompletion` callback can be provided, it will
3776 * never be called because the snapshot stream is never-ending.
3777 *
3778 * @param reference - A reference to the document to listen to.
3779 * @param options - Options controlling the listen behavior.
3780 * @param onNext - A callback to be called every time a new `DocumentSnapshot`
3781 * is available.
3782 * @param onError - A callback to be called if the listen fails or is
3783 * cancelled. No further callbacks will occur.
3784 * @param onCompletion - Can be provided, but will not be called since streams are
3785 * never ending.
3786 * @returns An unsubscribe function that can be called to cancel
3787 * the snapshot listener.
3788 */
3789export declare function onSnapshot<T>(reference: DocumentReference<T>, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot<T>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;
3790
3791/**
3792 * Attaches a listener for `QuerySnapshot` events. You may either pass
3793 * individual `onNext` and `onError` callbacks or pass a single observer
3794 * object with `next` and `error` callbacks. The listener can be cancelled by
3795 * calling the function that is returned when `onSnapshot` is called.
3796 *
3797 * NOTE: Although an `onCompletion` callback can be provided, it will
3798 * never be called because the snapshot stream is never-ending.
3799 *
3800 * @param query - The query to listen to.
3801 * @param observer - A single object containing `next` and `error` callbacks.
3802 * @returns An unsubscribe function that can be called to cancel
3803 * the snapshot listener.
3804 */
3805export declare function onSnapshot<T>(query: Query<T>, observer: {
3806 next?: (snapshot: QuerySnapshot<T>) => void;
3807 error?: (error: FirestoreError) => void;
3808 complete?: () => void;
3809}): Unsubscribe;
3810
3811/**
3812 * Attaches a listener for `QuerySnapshot` events. You may either pass
3813 * individual `onNext` and `onError` callbacks or pass a single observer
3814 * object with `next` and `error` callbacks. The listener can be cancelled by
3815 * calling the function that is returned when `onSnapshot` is called.
3816 *
3817 * NOTE: Although an `onCompletion` callback can be provided, it will
3818 * never be called because the snapshot stream is never-ending.
3819 *
3820 * @param query - The query to listen to.
3821 * @param options - Options controlling the listen behavior.
3822 * @param observer - A single object containing `next` and `error` callbacks.
3823 * @returns An unsubscribe function that can be called to cancel
3824 * the snapshot listener.
3825 */
3826export declare function onSnapshot<T>(query: Query<T>, options: SnapshotListenOptions, observer: {
3827 next?: (snapshot: QuerySnapshot<T>) => void;
3828 error?: (error: FirestoreError) => void;
3829 complete?: () => void;
3830}): Unsubscribe;
3831
3832/**
3833 * Attaches a listener for `QuerySnapshot` events. You may either pass
3834 * individual `onNext` and `onError` callbacks or pass a single observer
3835 * object with `next` and `error` callbacks. The listener can be cancelled by
3836 * calling the function that is returned when `onSnapshot` is called.
3837 *
3838 * NOTE: Although an `onCompletion` callback can be provided, it will
3839 * never be called because the snapshot stream is never-ending.
3840 *
3841 * @param query - The query to listen to.
3842 * @param onNext - A callback to be called every time a new `QuerySnapshot`
3843 * is available.
3844 * @param onCompletion - Can be provided, but will not be called since streams are
3845 * never ending.
3846 * @param onError - A callback to be called if the listen fails or is
3847 * cancelled. No further callbacks will occur.
3848 * @returns An unsubscribe function that can be called to cancel
3849 * the snapshot listener.
3850 */
3851export declare function onSnapshot<T>(query: Query<T>, onNext: (snapshot: QuerySnapshot<T>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;
3852
3853/**
3854 * Attaches a listener for `QuerySnapshot` events. You may either pass
3855 * individual `onNext` and `onError` callbacks or pass a single observer
3856 * object with `next` and `error` callbacks. The listener can be cancelled by
3857 * calling the function that is returned when `onSnapshot` is called.
3858 *
3859 * NOTE: Although an `onCompletion` callback can be provided, it will
3860 * never be called because the snapshot stream is never-ending.
3861 *
3862 * @param query - The query to listen to.
3863 * @param options - Options controlling the listen behavior.
3864 * @param onNext - A callback to be called every time a new `QuerySnapshot`
3865 * is available.
3866 * @param onCompletion - Can be provided, but will not be called since streams are
3867 * never ending.
3868 * @param onError - A callback to be called if the listen fails or is
3869 * cancelled. No further callbacks will occur.
3870 * @returns An unsubscribe function that can be called to cancel
3871 * the snapshot listener.
3872 */
3873export declare function onSnapshot<T>(query: Query<T>, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot<T>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;
3874
3875/**
3876 * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync
3877 * event indicates that all listeners affected by a given change have fired,
3878 * even if a single server-generated change affects multiple listeners.
3879 *
3880 * NOTE: The snapshots-in-sync event only indicates that listeners are in sync
3881 * with each other, but does not relate to whether those snapshots are in sync
3882 * with the server. Use SnapshotMetadata in the individual listeners to
3883 * determine if a snapshot is from the cache or the server.
3884 *
3885 * @param firestore - The instance of Firestore for synchronizing snapshots.
3886 * @param observer - A single object containing `next` and `error` callbacks.
3887 * @returns An unsubscribe function that can be called to cancel the snapshot
3888 * listener.
3889 */
3890export declare function onSnapshotsInSync(firestore: Firestore, observer: {
3891 next?: (value: void) => void;
3892 error?: (error: FirestoreError) => void;
3893 complete?: () => void;
3894}): Unsubscribe;
3895
3896/**
3897 * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync
3898 * event indicates that all listeners affected by a given change have fired,
3899 * even if a single server-generated change affects multiple listeners.
3900 *
3901 * NOTE: The snapshots-in-sync event only indicates that listeners are in sync
3902 * with each other, but does not relate to whether those snapshots are in sync
3903 * with the server. Use `SnapshotMetadata` in the individual listeners to
3904 * determine if a snapshot is from the cache or the server.
3905 *
3906 * @param firestore - The `Firestore` instance for synchronizing snapshots.
3907 * @param onSync - A callback to be called every time all snapshot listeners are
3908 * in sync with each other.
3909 * @returns An unsubscribe function that can be called to cancel the snapshot
3910 * listener.
3911 */
3912export declare function onSnapshotsInSync(firestore: Firestore, onSync: () => void): Unsubscribe;
3913
3914/**
3915 * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
3916 */
3917declare class OrderBy {
3918 readonly field: _FieldPath;
3919 readonly dir: Direction;
3920 constructor(field: _FieldPath, dir?: Direction);
3921}
3922
3923/**
3924 * Creates a {@link QueryConstraint} that sorts the query result by the
3925 * specified field, optionally in descending order instead of ascending.
3926 *
3927 * @param fieldPath - The field to sort by.
3928 * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
3929 * not specified, order will be ascending.
3930 * @returns The created {@link Query}.
3931 */
3932export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryConstraint;
3933
3934/**
3935 * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'
3936 * (descending or ascending).
3937 */
3938export declare type OrderByDirection = 'desc' | 'asc';
3939
3940declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING';
3941
3942/**
3943 * Representation of an overlay computed by Firestore.
3944 *
3945 * Holds information about a mutation and the largest batch id in Firestore when
3946 * the mutation was created.
3947 */
3948declare class Overlay {
3949 readonly largestBatchId: number;
3950 readonly mutation: Mutation;
3951 constructor(largestBatchId: number, mutation: Mutation);
3952 getKey(): _DocumentKey;
3953 isEqual(other: Overlay | null): boolean;
3954 toString(): string;
3955}
3956
3957/**
3958 * Represents a local view (overlay) of a document, and the fields that are
3959 * locally mutated.
3960 */
3961declare class OverlayedDocument {
3962 readonly overlayedDocument: Document_2;
3963 /**
3964 * The fields that are locally mutated by patch mutations. If the overlayed
3965 * document is from set or delete mutations, this returns null.
3966 */
3967 readonly mutatedFields: FieldMask | null;
3968 constructor(overlayedDocument: Document_2,
3969 /**
3970 * The fields that are locally mutated by patch mutations. If the overlayed
3971 * document is from set or delete mutations, this returns null.
3972 */
3973 mutatedFields: FieldMask | null);
3974}
3975
3976declare type OverlayedDocumentMap = DocumentKeyMap<OverlayedDocument>;
3977
3978declare type OverlayMap = DocumentKeyMap<Overlay>;
3979
3980declare interface ParseContext {
3981 readonly databaseId: _DatabaseId;
3982 readonly ignoreUndefinedProperties: boolean;
3983}
3984
3985/** The result of parsing document data (e.g. for a setData call). */
3986declare class ParsedSetData {
3987 readonly data: ObjectValue;
3988 readonly fieldMask: FieldMask | null;
3989 readonly fieldTransforms: FieldTransform[];
3990 constructor(data: ObjectValue, fieldMask: FieldMask | null, fieldTransforms: FieldTransform[]);
3991 toMutation(key: _DocumentKey, precondition: Precondition): Mutation;
3992}
3993
3994/** The result of parsing "update" data (i.e. for an updateData call). */
3995declare class ParsedUpdateData {
3996 readonly data: ObjectValue;
3997 readonly fieldMask: FieldMask;
3998 readonly fieldTransforms: FieldTransform[];
3999 constructor(data: ObjectValue, fieldMask: FieldMask, fieldTransforms: FieldTransform[]);
4000 toMutation(key: _DocumentKey, precondition: Precondition): Mutation;
4001}
4002
4003/**
4004 * Similar to Typescript's `Partial<T>`, but allows nested fields to be
4005 * omitted and FieldValues to be passed in as property values.
4006 */
4007export declare type PartialWithFieldValue<T> = Partial<T> | (T extends Primitive ? T : T extends {} ? {
4008 [K in keyof T]?: PartialWithFieldValue<T[K]> | FieldValue;
4009} : never);
4010
4011/**
4012 * Persistence is the lowest-level shared interface to persistent storage in
4013 * Firestore.
4014 *
4015 * Persistence is used to create MutationQueue and RemoteDocumentCache
4016 * instances backed by persistence (which might be in-memory or LevelDB).
4017 *
4018 * Persistence also exposes an API to create and run PersistenceTransactions
4019 * against persistence. All read / write operations must be wrapped in a
4020 * transaction. Implementations of PersistenceTransaction / Persistence only
4021 * need to guarantee that writes made against the transaction are not made to
4022 * durable storage until the transaction resolves its PersistencePromise.
4023 * Since memory-only storage components do not alter durable storage, they are
4024 * free to ignore the transaction.
4025 *
4026 * This contract is enough to allow the LocalStore be be written
4027 * independently of whether or not the stored state actually is durably
4028 * persisted. If persistent storage is enabled, writes are grouped together to
4029 * avoid inconsistent state that could cause crashes.
4030 *
4031 * Concretely, when persistent storage is enabled, the persistent versions of
4032 * MutationQueue, RemoteDocumentCache, and others (the mutators) will
4033 * defer their writes into a transaction. Once the local store has completed
4034 * one logical operation, it commits the transaction.
4035 *
4036 * When persistent storage is disabled, the non-persistent versions of the
4037 * mutators ignore the transaction. This short-cut is allowed because
4038 * memory-only storage leaves no state so it cannot be inconsistent.
4039 *
4040 * This simplifies the implementations of the mutators and allows memory-only
4041 * implementations to supplement the persistent ones without requiring any
4042 * special dual-store implementation of Persistence. The cost is that the
4043 * LocalStore needs to be slightly careful about the order of its reads and
4044 * writes in order to avoid relying on being able to read back uncommitted
4045 * writes.
4046 */
4047declare interface Persistence {
4048 /**
4049 * Whether or not this persistence instance has been started.
4050 */
4051 readonly started: boolean;
4052 readonly referenceDelegate: ReferenceDelegate;
4053 /** Starts persistence. */
4054 start(): Promise<void>;
4055 /**
4056 * Releases any resources held during eager shutdown.
4057 */
4058 shutdown(): Promise<void>;
4059 /**
4060 * Registers a listener that gets called when the database receives a
4061 * version change event indicating that it has deleted.
4062 *
4063 * PORTING NOTE: This is only used for Web multi-tab.
4064 */
4065 setDatabaseDeletedListener(databaseDeletedListener: () => Promise<void>): void;
4066 /**
4067 * Adjusts the current network state in the client's metadata, potentially
4068 * affecting the primary lease.
4069 *
4070 * PORTING NOTE: This is only used for Web multi-tab.
4071 */
4072 setNetworkEnabled(networkEnabled: boolean): void;
4073 /**
4074 * Returns a MutationQueue representing the persisted mutations for the
4075 * given user.
4076 *
4077 * Note: The implementation is free to return the same instance every time
4078 * this is called for a given user. In particular, the memory-backed
4079 * implementation does this to emulate the persisted implementation to the
4080 * extent possible (e.g. in the case of uid switching from
4081 * sally=&gt;jack=&gt;sally, sally's mutation queue will be preserved).
4082 */
4083 getMutationQueue(user: User, indexManager: IndexManager): MutationQueue;
4084 /**
4085 * Returns a TargetCache representing the persisted cache of targets.
4086 *
4087 * Note: The implementation is free to return the same instance every time
4088 * this is called. In particular, the memory-backed implementation does this
4089 * to emulate the persisted implementation to the extent possible.
4090 */
4091 getTargetCache(): TargetCache;
4092 /**
4093 * Returns a RemoteDocumentCache representing the persisted cache of remote
4094 * documents.
4095 *
4096 * Note: The implementation is free to return the same instance every time
4097 * this is called. In particular, the memory-backed implementation does this
4098 * to emulate the persisted implementation to the extent possible.
4099 */
4100 getRemoteDocumentCache(): RemoteDocumentCache;
4101 /**
4102 * Returns a BundleCache representing the persisted cache of loaded bundles.
4103 *
4104 * Note: The implementation is free to return the same instance every time
4105 * this is called. In particular, the memory-backed implementation does this
4106 * to emulate the persisted implementation to the extent possible.
4107 */
4108 getBundleCache(): BundleCache;
4109 /**
4110 * Returns an IndexManager instance that manages our persisted query indexes.
4111 *
4112 * Note: The implementation is free to return the same instance every time
4113 * this is called. In particular, the memory-backed implementation does this
4114 * to emulate the persisted implementation to the extent possible.
4115 */
4116 getIndexManager(user: User): IndexManager;
4117 /**
4118 * Returns a DocumentOverlayCache representing the documents that are mutated
4119 * locally.
4120 */
4121 getDocumentOverlayCache(user: User): DocumentOverlayCache;
4122 /**
4123 * Performs an operation inside a persistence transaction. Any reads or writes
4124 * against persistence must be performed within a transaction. Writes will be
4125 * committed atomically once the transaction completes.
4126 *
4127 * Persistence operations are asynchronous and therefore the provided
4128 * transactionOperation must return a PersistencePromise. When it is resolved,
4129 * the transaction will be committed and the Promise returned by this method
4130 * will resolve.
4131 *
4132 * @param action - A description of the action performed by this transaction,
4133 * used for logging.
4134 * @param mode - The underlying mode of the IndexedDb transaction. Can be
4135 * 'readonly', 'readwrite' or 'readwrite-primary'. Transactions marked
4136 * 'readwrite-primary' can only be executed by the primary client. In this
4137 * mode, the transactionOperation will not be run if the primary lease cannot
4138 * be acquired and the returned promise will be rejected with a
4139 * FAILED_PRECONDITION error.
4140 * @param transactionOperation - The operation to run inside a transaction.
4141 * @returns A `Promise` that is resolved once the transaction completes.
4142 */
4143 runTransaction<T>(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise<T>): Promise<T>;
4144}
4145
4146/**
4147 * PersistencePromise is essentially a re-implementation of Promise except
4148 * it has a .next() method instead of .then() and .next() and .catch() callbacks
4149 * are executed synchronously when a PersistencePromise resolves rather than
4150 * asynchronously (Promise implementations use setImmediate() or similar).
4151 *
4152 * This is necessary to interoperate with IndexedDB which will automatically
4153 * commit transactions if control is returned to the event loop without
4154 * synchronously initiating another operation on the transaction.
4155 *
4156 * NOTE: .then() and .catch() only allow a single consumer, unlike normal
4157 * Promises.
4158 */
4159declare class PersistencePromise<T> {
4160 private nextCallback;
4161 private catchCallback;
4162 private result;
4163 private error;
4164 private isDone;
4165 private callbackAttached;
4166 constructor(callback: (resolve: Resolver<T>, reject: Rejector) => void);
4167 catch<R>(fn: (error: Error) => R | PersistencePromise<R>): PersistencePromise<R>;
4168 next<R>(nextFn?: FulfilledHandler<T, R>, catchFn?: RejectedHandler<R>): PersistencePromise<R>;
4169 toPromise(): Promise<T>;
4170 private wrapUserFunction;
4171 private wrapSuccess;
4172 private wrapFailure;
4173 static resolve(): PersistencePromise<void>;
4174 static resolve<R>(result: R): PersistencePromise<R>;
4175 static reject<R>(error: Error): PersistencePromise<R>;
4176 static waitFor(all: {
4177 forEach: (cb: (el: PersistencePromise<any>) => void) => void;
4178 }): PersistencePromise<void>;
4179 /**
4180 * Given an array of predicate functions that asynchronously evaluate to a
4181 * boolean, implements a short-circuiting `or` between the results. Predicates
4182 * will be evaluated until one of them returns `true`, then stop. The final
4183 * result will be whether any of them returned `true`.
4184 */
4185 static or(predicates: Array<() => PersistencePromise<boolean>>): PersistencePromise<boolean>;
4186 /**
4187 * Given an iterable, call the given function on each element in the
4188 * collection and wait for all of the resulting concurrent PersistencePromises
4189 * to resolve.
4190 */
4191 static forEach<R, S>(collection: {
4192 forEach: (cb: (r: R, s: S) => void) => void;
4193 }, f: ((r: R, s: S) => PersistencePromise<void>) | ((r: R) => PersistencePromise<void>)): PersistencePromise<void>;
4194 static forEach<R>(collection: {
4195 forEach: (cb: (r: R) => void) => void;
4196 }, f: (r: R) => PersistencePromise<void>): PersistencePromise<void>;
4197 /**
4198 * Concurrently map all array elements through asynchronous function.
4199 */
4200 static mapArray<T, U>(array: T[], f: (t: T) => PersistencePromise<U>): PersistencePromise<U[]>;
4201 /**
4202 * An alternative to recursive PersistencePromise calls, that avoids
4203 * potential memory problems from unbounded chains of promises.
4204 *
4205 * The `action` will be called repeatedly while `condition` is true.
4206 */
4207 static doWhile(condition: () => boolean, action: () => PersistencePromise<void>): PersistencePromise<void>;
4208}
4209
4210/**
4211 * Settings that can be passed to `enableIndexedDbPersistence()` to configure
4212 * Firestore persistence.
4213 */
4214export declare interface PersistenceSettings {
4215 /**
4216 * Whether to force enable persistence for the client. This cannot be used
4217 * with multi-tab synchronization and is primarily intended for use with Web
4218 * Workers. Setting this to `true` will enable persistence, but cause other
4219 * tabs using persistence to fail.
4220 */
4221 forceOwnership?: boolean;
4222}
4223
4224/**
4225 * A base class representing a persistence transaction, encapsulating both the
4226 * transaction's sequence numbers as well as a list of onCommitted listeners.
4227 *
4228 * When you call Persistence.runTransaction(), it will create a transaction and
4229 * pass it to your callback. You then pass it to any method that operates
4230 * on persistence.
4231 */
4232declare abstract class PersistenceTransaction {
4233 private readonly onCommittedListeners;
4234 abstract readonly currentSequenceNumber: ListenSequenceNumber;
4235 addOnCommittedListener(listener: () => void): void;
4236 raiseOnCommittedEvent(): void;
4237}
4238
4239/** The different modes supported by `Persistence.runTransaction()`. */
4240declare type PersistenceTransactionMode = 'readonly' | 'readwrite' | 'readwrite-primary';
4241
4242/**
4243 * Encodes a precondition for a mutation. This follows the model that the
4244 * backend accepts with the special case of an explicit "empty" precondition
4245 * (meaning no precondition).
4246 */
4247declare class Precondition {
4248 readonly updateTime?: SnapshotVersion | undefined;
4249 readonly exists?: boolean | undefined;
4250 private constructor();
4251 /** Creates a new empty Precondition. */
4252 static none(): Precondition;
4253 /** Creates a new Precondition with an exists flag. */
4254 static exists(exists: boolean): Precondition;
4255 /** Creates a new Precondition based on a version a document exists at. */
4256 static updateTime(version: SnapshotVersion): Precondition;
4257 /** Returns whether this Precondition is empty. */
4258 get isNone(): boolean;
4259 isEqual(other: Precondition): boolean;
4260}
4261
4262/**
4263 * These types primarily exist to support the `UpdateData`,
4264 * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed
4265 * directly by the end developer.
4266 */
4267/** Primitive types. */
4268export declare type Primitive = string | number | boolean | undefined | null;
4269
4270/** Undocumented, private additional settings not exposed in our public API. */
4271declare interface PrivateSettings extends FirestoreSettings_2 {
4272 credentials?: CredentialsSettings;
4273 cacheSizeBytes?: number;
4274 experimentalForceLongPolling?: boolean;
4275 experimentalAutoDetectLongPolling?: boolean;
4276 useFetchStreams?: boolean;
4277}
4278
4279declare interface ProviderCredentialsSettings {
4280 ['type']: 'provider';
4281 ['client']: CredentialsProvider<User>;
4282}
4283
4284/**
4285 * A `Query` refers to a query which you can read or listen to. You can also
4286 * construct refined `Query` objects by adding filters and ordering.
4287 */
4288export declare class Query<T = DocumentData> {
4289 /**
4290 * If provided, the `FirestoreDataConverter` associated with this instance.
4291 */
4292 readonly converter: FirestoreDataConverter_2<T> | null;
4293 readonly _query: Query_2;
4294 /** The type of this Firestore reference. */
4295 readonly type: 'query' | 'collection';
4296 /**
4297 * The `Firestore` instance for the Firestore database (useful for performing
4298 * transactions, etc.).
4299 */
4300 readonly firestore: Firestore_2;
4301 /** @hideconstructor protected */
4302 constructor(firestore: Firestore_2,
4303 /**
4304 * If provided, the `FirestoreDataConverter` associated with this instance.
4305 */
4306 converter: FirestoreDataConverter_2<T> | null, _query: Query_2);
4307 /**
4308 * Removes the current converter.
4309 *
4310 * @param converter - `null` removes the current converter.
4311 * @returns A `Query<DocumentData>` that does not use a converter.
4312 */
4313 withConverter(converter: null): Query<DocumentData>;
4314 /**
4315 * Applies a custom data converter to this query, allowing you to use your own
4316 * custom model objects with Firestore. When you call {@link getDocs} with
4317 * the returned query, the provided converter will convert between Firestore
4318 * data and your custom type `U`.
4319 *
4320 * @param converter - Converts objects to and from Firestore.
4321 * @returns A `Query<U>` that uses the provided converter.
4322 */
4323 withConverter<U>(converter: FirestoreDataConverter_2<U>): Query<U>;
4324}
4325
4326/**
4327 * Creates a new immutable instance of {@link Query} that is extended to also include
4328 * additional query constraints.
4329 *
4330 * @param query - The {@link Query} instance to use as a base for the new constraints.
4331 * @param queryConstraints - The list of {@link QueryConstraint}s to apply.
4332 * @throws if any of the provided query constraints cannot be combined with the
4333 * existing or new constraints.
4334 */
4335export declare function query<T>(query: Query<T>, ...queryConstraints: QueryConstraint[]): Query<T>;
4336
4337/**
4338 * The Query interface defines all external properties of a query.
4339 *
4340 * QueryImpl implements this interface to provide memoization for `queryOrderBy`
4341 * and `queryToTarget`.
4342 */
4343declare interface Query_2 {
4344 readonly path: _ResourcePath;
4345 readonly collectionGroup: string | null;
4346 readonly explicitOrderBy: OrderBy[];
4347 readonly filters: Filter[];
4348 readonly limit: number | null;
4349 readonly limitType: LimitType;
4350 readonly startAt: Bound | null;
4351 readonly endAt: Bound | null;
4352}
4353
4354/**
4355 * A `QueryConstraint` is used to narrow the set of documents returned by a
4356 * Firestore query. `QueryConstraint`s are created by invoking {@link where},
4357 * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link
4358 * endBefore:1}, {@link (endAt:1)}, {@link limit} or {@link limitToLast} and
4359 * can then be passed to {@link query} to create a new query instance that
4360 * also contains this `QueryConstraint`.
4361 */
4362export declare abstract class QueryConstraint {
4363 /** The type of this query constraints */
4364 abstract readonly type: QueryConstraintType;
4365 /**
4366 * Takes the provided {@link Query} and returns a copy of the {@link Query} with this
4367 * {@link QueryConstraint} applied.
4368 */
4369 abstract _apply<T>(query: Query<T>): Query<T>;
4370}
4371
4372/** Describes the different query constraints available in this SDK. */
4373export declare type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore';
4374
4375/**
4376 * A `QueryDocumentSnapshot` contains data read from a document in your
4377 * Firestore database as part of a query. The document is guaranteed to exist
4378 * and its data can be extracted with `.data()` or `.get(<field>)` to get a
4379 * specific field.
4380 *
4381 * A `QueryDocumentSnapshot` offers the same API surface as a
4382 * `DocumentSnapshot`. Since query results contain only existing documents, the
4383 * `exists` property will always be true and `data()` will never return
4384 * 'undefined'.
4385 */
4386export declare class QueryDocumentSnapshot<T = DocumentData> extends DocumentSnapshot<T> {
4387 /**
4388 * Retrieves all fields in the document as an `Object`.
4389 *
4390 * By default, `serverTimestamp()` values that have not yet been
4391 * set to their final value will be returned as `null`. You can override
4392 * this by passing an options object.
4393 *
4394 * @override
4395 * @param options - An options object to configure how data is retrieved from
4396 * the snapshot (for example the desired behavior for server timestamps that
4397 * have not yet been set to their final value).
4398 * @returns An `Object` containing all fields in the document.
4399 */
4400 data(options?: SnapshotOptions): T;
4401}
4402
4403/**
4404 * A `QueryDocumentSnapshot` contains data read from a document in your
4405 * Firestore database as part of a query. The document is guaranteed to exist
4406 * and its data can be extracted with `.data()` or `.get(<field>)` to get a
4407 * specific field.
4408 *
4409 * A `QueryDocumentSnapshot` offers the same API surface as a
4410 * `DocumentSnapshot`. Since query results contain only existing documents, the
4411 * `exists` property will always be true and `data()` will never return
4412 * 'undefined'.
4413 */
4414declare class QueryDocumentSnapshot_2<T = DocumentData> extends DocumentSnapshot_2<T> {
4415 /**
4416 * Retrieves all fields in the document as an `Object`.
4417 *
4418 * @override
4419 * @returns An `Object` containing all fields in the document.
4420 */
4421 data(): T;
4422}
4423
4424/**
4425 * Returns true if the provided queries point to the same collection and apply
4426 * the same constraints.
4427 *
4428 * @param left - A `Query` to compare.
4429 * @param right - A `Query` to compare.
4430 * @returns true if the references point to the same location in the same
4431 * Firestore database.
4432 */
4433export declare function queryEqual<T>(left: Query<T>, right: Query<T>): boolean;
4434
4435/**
4436 * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
4437 * representing the results of a query. The documents can be accessed as an
4438 * array via the `docs` property or enumerated using the `forEach` method. The
4439 * number of documents can be determined via the `empty` and `size`
4440 * properties.
4441 */
4442export declare class QuerySnapshot<T = DocumentData> {
4443 readonly _firestore: Firestore;
4444 readonly _userDataWriter: AbstractUserDataWriter;
4445 readonly _snapshot: ViewSnapshot;
4446 /**
4447 * Metadata about this snapshot, concerning its source and if it has local
4448 * modifications.
4449 */
4450 readonly metadata: SnapshotMetadata;
4451 /**
4452 * The query on which you called `get` or `onSnapshot` in order to get this
4453 * `QuerySnapshot`.
4454 */
4455 readonly query: Query<T>;
4456 private _cachedChanges?;
4457 private _cachedChangesIncludeMetadataChanges?;
4458 /** @hideconstructor */
4459 constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, query: Query<T>, _snapshot: ViewSnapshot);
4460 /** An array of all the documents in the `QuerySnapshot`. */
4461 get docs(): Array<QueryDocumentSnapshot<T>>;
4462 /** The number of documents in the `QuerySnapshot`. */
4463 get size(): number;
4464 /** True if there are no documents in the `QuerySnapshot`. */
4465 get empty(): boolean;
4466 /**
4467 * Enumerates all of the documents in the `QuerySnapshot`.
4468 *
4469 * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
4470 * each document in the snapshot.
4471 * @param thisArg - The `this` binding for the callback.
4472 */
4473 forEach(callback: (result: QueryDocumentSnapshot<T>) => void, thisArg?: unknown): void;
4474 /**
4475 * Returns an array of the documents changes since the last snapshot. If this
4476 * is the first snapshot, all documents will be in the list as 'added'
4477 * changes.
4478 *
4479 * @param options - `SnapshotListenOptions` that control whether metadata-only
4480 * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
4481 * snapshot events.
4482 */
4483 docChanges(options?: SnapshotListenOptions): Array<DocumentChange<T>>;
4484}
4485
4486/** The different states of a watch target. */
4487declare type QueryTargetState = 'not-current' | 'current' | 'rejected';
4488
4489/**
4490 * Returns true if the provided references are equal.
4491 *
4492 * @param left - A reference to compare.
4493 * @param right - A reference to compare.
4494 * @returns true if the references point to the same location in the same
4495 * Firestore database.
4496 */
4497export declare function refEqual<T>(left: DocumentReference<T> | CollectionReference<T>, right: DocumentReference<T> | CollectionReference<T>): boolean;
4498
4499/**
4500 * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This
4501 * includes being added to a target, being removed from a target, being subject to mutation, and
4502 * being mutated by the user.
4503 *
4504 * Different implementations may do different things with each of these events. Not every
4505 * implementation needs to do something with every lifecycle hook.
4506 *
4507 * PORTING NOTE: since sequence numbers are attached to transactions in this
4508 * client, the ReferenceDelegate does not need to deal in transactional
4509 * semantics (onTransactionStarted/Committed()), nor does it need to track and
4510 * generate sequence numbers (getCurrentSequenceNumber()).
4511 */
4512declare interface ReferenceDelegate {
4513 /** Notify the delegate that the given document was added to a target. */
4514 addReference(txn: PersistenceTransaction, targetId: TargetId, doc: _DocumentKey): PersistencePromise<void>;
4515 /** Notify the delegate that the given document was removed from a target. */
4516 removeReference(txn: PersistenceTransaction, targetId: TargetId, doc: _DocumentKey): PersistencePromise<void>;
4517 /**
4518 * Notify the delegate that a target was removed. The delegate may, but is not obligated to,
4519 * actually delete the target and associated data.
4520 */
4521 removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise<void>;
4522 /**
4523 * Notify the delegate that a document may no longer be part of any views or
4524 * have any mutations associated.
4525 */
4526 markPotentiallyOrphaned(txn: PersistenceTransaction, doc: _DocumentKey): PersistencePromise<void>;
4527 /** Notify the delegate that a limbo document was updated. */
4528 updateLimboDocument(txn: PersistenceTransaction, doc: _DocumentKey): PersistencePromise<void>;
4529}
4530
4531declare type RejectedHandler<R> = ((reason: Error) => R | PersistencePromise<R>) | null;
4532
4533declare type Rejector = (error: Error) => void;
4534
4535/**
4536 * Represents cached documents received from the remote backend.
4537 *
4538 * The cache is keyed by DocumentKey and entries in the cache are
4539 * MutableDocuments, meaning we can cache both actual documents as well as
4540 * documents that are known to not exist.
4541 */
4542declare interface RemoteDocumentCache {
4543 /** Sets the index manager to use for managing the collectionGroup index. */
4544 setIndexManager(indexManager: IndexManager): void;
4545 /**
4546 * Looks up an entry in the cache.
4547 *
4548 * @param documentKey - The key of the entry to look up.*
4549 * @returns The cached document entry. Returns an invalid document if the
4550 * document is not cached.
4551 */
4552 getEntry(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise<MutableDocument>;
4553 /**
4554 * Looks up a set of entries in the cache.
4555 *
4556 * @param documentKeys - The keys of the entries to look up.
4557 * @returns The cached document entries indexed by key. If an entry is not
4558 * cached, the corresponding key will be mapped to an invalid document.
4559 */
4560 getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise<MutableDocumentMap>;
4561 /**
4562 * Returns the documents from the provided collection.
4563 *
4564 * @param collection - The collection to read.
4565 * @param offset - The offset to start the scan at (exclusive).
4566 * @returns The set of matching documents.
4567 */
4568 getAllFromCollection(transaction: PersistenceTransaction, collection: _ResourcePath, offset: IndexOffset): PersistencePromise<MutableDocumentMap>;
4569 /**
4570 * Looks up the next `limit` documents for a collection group based on the
4571 * provided offset. The ordering is based on the document's read time and key.
4572 *
4573 * @param collectionGroup - The collection group to scan.
4574 * @param offset - The offset to start the scan at (exclusive).
4575 * @param limit - The maximum number of results to return.
4576 * @returns The set of matching documents.
4577 */
4578 getAllFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, limit: number): PersistencePromise<MutableDocumentMap>;
4579 /**
4580 * Provides access to add or update the contents of the cache. The buffer
4581 * handles proper size accounting for the change.
4582 *
4583 * Multi-Tab Note: This should only be called by the primary client.
4584 *
4585 * @param options - Specify `trackRemovals` to create sentinel entries for
4586 * removed documents, which allows removals to be tracked by
4587 * `getNewDocumentChanges()`.
4588 */
4589 newChangeBuffer(options?: {
4590 trackRemovals: boolean;
4591 }): RemoteDocumentChangeBuffer;
4592 /**
4593 * Get an estimate of the size of the document cache. Note that for eager
4594 * garbage collection, we don't track sizes so this will return 0.
4595 */
4596 getSize(transaction: PersistenceTransaction): PersistencePromise<number>;
4597}
4598
4599/**
4600 * An in-memory buffer of entries to be written to a RemoteDocumentCache.
4601 * It can be used to batch up a set of changes to be written to the cache, but
4602 * additionally supports reading entries back with the `getEntry()` method,
4603 * falling back to the underlying RemoteDocumentCache if no entry is
4604 * buffered.
4605 *
4606 * Entries added to the cache *must* be read first. This is to facilitate
4607 * calculating the size delta of the pending changes.
4608 *
4609 * PORTING NOTE: This class was implemented then removed from other platforms.
4610 * If byte-counting ends up being needed on the other platforms, consider
4611 * porting this class as part of that implementation work.
4612 */
4613declare abstract class RemoteDocumentChangeBuffer {
4614 protected changes: ObjectMap<_DocumentKey, MutableDocument>;
4615 private changesApplied;
4616 protected abstract getFromCache(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise<MutableDocument>;
4617 protected abstract getAllFromCache(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise<MutableDocumentMap>;
4618 protected abstract applyChanges(transaction: PersistenceTransaction): PersistencePromise<void>;
4619 /**
4620 * Buffers a `RemoteDocumentCache.addEntry()` call.
4621 *
4622 * You can only modify documents that have already been retrieved via
4623 * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
4624 */
4625 addEntry(document: MutableDocument): void;
4626 /**
4627 * Buffers a `RemoteDocumentCache.removeEntry()` call.
4628 *
4629 * You can only remove documents that have already been retrieved via
4630 * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
4631 */
4632 removeEntry(key: _DocumentKey, readTime: SnapshotVersion): void;
4633 /**
4634 * Looks up an entry in the cache. The buffered changes will first be checked,
4635 * and if no buffered change applies, this will forward to
4636 * `RemoteDocumentCache.getEntry()`.
4637 *
4638 * @param transaction - The transaction in which to perform any persistence
4639 * operations.
4640 * @param documentKey - The key of the entry to look up.
4641 * @returns The cached document or an invalid document if we have nothing
4642 * cached.
4643 */
4644 getEntry(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise<MutableDocument>;
4645 /**
4646 * Looks up several entries in the cache, forwarding to
4647 * `RemoteDocumentCache.getEntry()`.
4648 *
4649 * @param transaction - The transaction in which to perform any persistence
4650 * operations.
4651 * @param documentKeys - The keys of the entries to look up.
4652 * @returns A map of cached documents, indexed by key. If an entry cannot be
4653 * found, the corresponding key will be mapped to an invalid document.
4654 */
4655 getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise<MutableDocumentMap>;
4656 /**
4657 * Applies buffered changes to the underlying RemoteDocumentCache, using
4658 * the provided transaction.
4659 */
4660 apply(transaction: PersistenceTransaction): PersistencePromise<void>;
4661 /** Helper to assert this.changes is not null */
4662 protected assertNotApplied(): void;
4663}
4664
4665/**
4666 * An event from the RemoteStore. It is split into targetChanges (changes to the
4667 * state or the set of documents in our watched targets) and documentUpdates
4668 * (changes to the actual documents).
4669 */
4670declare class RemoteEvent {
4671 /**
4672 * The snapshot version this event brings us up to, or MIN if not set.
4673 */
4674 readonly snapshotVersion: SnapshotVersion;
4675 /**
4676 * A map from target to changes to the target. See TargetChange.
4677 */
4678 readonly targetChanges: Map<TargetId, TargetChange>;
4679 /**
4680 * A set of targets that is known to be inconsistent. Listens for these
4681 * targets should be re-established without resume tokens.
4682 */
4683 readonly targetMismatches: SortedSet<TargetId>;
4684 /**
4685 * A set of which documents have changed or been deleted, along with the
4686 * doc's new values (if not deleted).
4687 */
4688 readonly documentUpdates: MutableDocumentMap;
4689 /**
4690 * A set of which document updates are due only to limbo resolution targets.
4691 */
4692 readonly resolvedLimboDocuments: DocumentKeySet;
4693 constructor(
4694 /**
4695 * The snapshot version this event brings us up to, or MIN if not set.
4696 */
4697 snapshotVersion: SnapshotVersion,
4698 /**
4699 * A map from target to changes to the target. See TargetChange.
4700 */
4701 targetChanges: Map<TargetId, TargetChange>,
4702 /**
4703 * A set of targets that is known to be inconsistent. Listens for these
4704 * targets should be re-established without resume tokens.
4705 */
4706 targetMismatches: SortedSet<TargetId>,
4707 /**
4708 * A set of which documents have changed or been deleted, along with the
4709 * doc's new values (if not deleted).
4710 */
4711 documentUpdates: MutableDocumentMap,
4712 /**
4713 * A set of which document updates are due only to limbo resolution targets.
4714 */
4715 resolvedLimboDocuments: DocumentKeySet);
4716 /**
4717 * HACK: Views require RemoteEvents in order to determine whether the view is
4718 * CURRENT, but secondary tabs don't receive remote events. So this method is
4719 * used to create a synthesized RemoteEvent that can be used to apply a
4720 * CURRENT status change to a View, for queries executed in a different tab.
4721 */
4722 static createSynthesizedRemoteEventForCurrentChange(targetId: TargetId, current: boolean, resumeToken: _ByteString): RemoteEvent;
4723}
4724
4725/**
4726 * RemoteStore - An interface to remotely stored data, basically providing a
4727 * wrapper around the Datastore that is more reliable for the rest of the
4728 * system.
4729 *
4730 * RemoteStore is responsible for maintaining the connection to the server.
4731 * - maintaining a list of active listens.
4732 * - reconnecting when the connection is dropped.
4733 * - resuming all the active listens on reconnect.
4734 *
4735 * RemoteStore handles all incoming events from the Datastore.
4736 * - listening to the watch stream and repackaging the events as RemoteEvents
4737 * - notifying SyncEngine of any changes to the active listens.
4738 *
4739 * RemoteStore takes writes from other components and handles them reliably.
4740 * - pulling pending mutations from LocalStore and sending them to Datastore.
4741 * - retrying mutations that failed because of network problems.
4742 * - acking mutations to the SyncEngine once they are accepted or rejected.
4743 */
4744declare interface RemoteStore {
4745 /**
4746 * SyncEngine to notify of watch and write events. This must be set
4747 * immediately after construction.
4748 */
4749 remoteSyncer: RemoteSyncer;
4750}
4751
4752/**
4753 * An interface that describes the actions the RemoteStore needs to perform on
4754 * a cooperating synchronization engine.
4755 */
4756declare interface RemoteSyncer {
4757 /**
4758 * Applies one remote event to the sync engine, notifying any views of the
4759 * changes, and releasing any pending mutation batches that would become
4760 * visible because of the snapshot version the remote event contains.
4761 */
4762 applyRemoteEvent?(remoteEvent: RemoteEvent): Promise<void>;
4763 /**
4764 * Rejects the listen for the given targetID. This can be triggered by the
4765 * backend for any active target.
4766 *
4767 * @param targetId - The targetID corresponds to one previously initiated by
4768 * the user as part of TargetData passed to listen() on RemoteStore.
4769 * @param error - A description of the condition that has forced the rejection.
4770 * Nearly always this will be an indication that the user is no longer
4771 * authorized to see the data matching the target.
4772 */
4773 rejectListen?(targetId: TargetId, error: FirestoreError): Promise<void>;
4774 /**
4775 * Applies the result of a successful write of a mutation batch to the sync
4776 * engine, emitting snapshots in any views that the mutation applies to, and
4777 * removing the batch from the mutation queue.
4778 */
4779 applySuccessfulWrite?(result: MutationBatchResult): Promise<void>;
4780 /**
4781 * Rejects the batch, removing the batch from the mutation queue, recomputing
4782 * the local view of any documents affected by the batch and then, emitting
4783 * snapshots with the reverted value.
4784 */
4785 rejectFailedWrite?(batchId: BatchId, error: FirestoreError): Promise<void>;
4786 /**
4787 * Returns the set of remote document keys for the given target ID. This list
4788 * includes the documents that were assigned to the target when we received
4789 * the last snapshot.
4790 */
4791 getRemoteKeysForTarget?(targetId: TargetId): DocumentKeySet;
4792 /**
4793 * Updates all local state to match the pending mutations for the given user.
4794 * May be called repeatedly for the same user.
4795 */
4796 handleCredentialChange?(user: User): Promise<void>;
4797}
4798
4799declare type Resolver<T> = (value?: T) => void;
4800
4801/**
4802 * A slash-separated path for navigating resources (documents and collections)
4803 * within Firestore.
4804 *
4805 * @internal
4806 */
4807export declare class _ResourcePath extends BasePath<_ResourcePath> {
4808 protected construct(segments: string[], offset?: number, length?: number): _ResourcePath;
4809 canonicalString(): string;
4810 toString(): string;
4811 /**
4812 * Creates a resource path from the given slash-delimited string. If multiple
4813 * arguments are provided, all components are combined. Leading and trailing
4814 * slashes from all components are ignored.
4815 */
4816 static fromString(...pathComponents: string[]): _ResourcePath;
4817 static emptyPath(): _ResourcePath;
4818}
4819
4820/**
4821 * Executes the given `updateFunction` and then attempts to commit the changes
4822 * applied within the transaction. If any document read within the transaction
4823 * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
4824 * commit after 5 attempts, the transaction fails.
4825 *
4826 * The maximum number of writes allowed in a single transaction is 500.
4827 *
4828 * @param firestore - A reference to the Firestore database to run this
4829 * transaction against.
4830 * @param updateFunction - The function to execute within the transaction
4831 * context.
4832 * @param options - An options object to configure maximum number of attempts to
4833 * commit.
4834 * @returns If the transaction completed successfully or was explicitly aborted
4835 * (the `updateFunction` returned a failed promise), the promise returned by the
4836 * `updateFunction `is returned here. Otherwise, if the transaction failed, a
4837 * rejected promise with the corresponding failure error is returned.
4838 */
4839export declare function runTransaction<T>(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise<T>, options?: TransactionOptions): Promise<T>;
4840
4841/**
4842 * Interface to schedule periodic tasks within SDK.
4843 */
4844declare interface Scheduler {
4845 readonly started: boolean;
4846 start(): void;
4847 stop(): void;
4848}
4849
4850/**
4851 * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
4852 * include a server-generated timestamp in the written data.
4853 */
4854export declare function serverTimestamp(): FieldValue;
4855
4856declare type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';
4857
4858/**
4859 * Writes to the document referred to by this `DocumentReference`. If the
4860 * document does not yet exist, it will be created.
4861 *
4862 * @param reference - A reference to the document to write.
4863 * @param data - A map of the fields and values for the document.
4864 * @returns A `Promise` resolved once the data has been successfully written
4865 * to the backend (note that it won't resolve while you're offline).
4866 */
4867export declare function setDoc<T>(reference: DocumentReference<T>, data: WithFieldValue<T>): Promise<void>;
4868
4869/**
4870 * Writes to the document referred to by the specified `DocumentReference`. If
4871 * the document does not yet exist, it will be created. If you provide `merge`
4872 * or `mergeFields`, the provided data can be merged into an existing document.
4873 *
4874 * @param reference - A reference to the document to write.
4875 * @param data - A map of the fields and values for the document.
4876 * @param options - An object to configure the set behavior.
4877 * @returns A Promise resolved once the data has been successfully written
4878 * to the backend (note that it won't resolve while you're offline).
4879 */
4880export declare function setDoc<T>(reference: DocumentReference<T>, data: PartialWithFieldValue<T>, options: SetOptions): Promise<void>;
4881
4882/**
4883 * Configures indexing for local query execution. Any previous index
4884 * configuration is overridden. The `Promise` resolves once the index
4885 * configuration has been persisted.
4886 *
4887 * The index entries themselves are created asynchronously. You can continue to
4888 * use queries that require indexing even if the indices are not yet available.
4889 * Query execution will automatically start using the index once the index
4890 * entries have been written.
4891 *
4892 * Indexes are only supported with IndexedDb persistence. Invoke either
4893 * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()`
4894 * before setting an index configuration. If IndexedDb is not enabled, any
4895 * index configuration is ignored.
4896 *
4897 * @param firestore - The {@link Firestore} instance to configure indexes for.
4898 * @param configuration -The index definition.
4899 * @throws FirestoreError if the JSON format is invalid.
4900 * @returns A `Promise` that resolves once all indices are successfully
4901 * configured.
4902 * @beta
4903 */
4904export declare function setIndexConfiguration(firestore: Firestore, configuration: IndexConfiguration): Promise<void>;
4905
4906/**
4907 * Configures indexing for local query execution. Any previous index
4908 * configuration is overridden. The `Promise` resolves once the index
4909 * configuration has been persisted.
4910 *
4911 * The index entries themselves are created asynchronously. You can continue to
4912 * use queries that require indexing even if the indices are not yet available.
4913 * Query execution will automatically start using the index once the index
4914 * entries have been written.
4915 *
4916 * Indexes are only supported with IndexedDb persistence. Invoke either
4917 * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()`
4918 * before setting an index configuration. If IndexedDb is not enabled, any
4919 * index configuration is ignored.
4920 *
4921 * The method accepts the JSON format exported by the Firebase CLI (`firebase
4922 * firestore:indexes`). If the JSON format is invalid, this method throws an
4923 * error.
4924 *
4925 * @param firestore - The {@link Firestore} instance to configure indexes for.
4926 * @param json -The JSON format exported by the Firebase CLI.
4927 * @throws FirestoreError if the JSON format is invalid.
4928 * @returns A `Promise` that resolves once all indices are successfully
4929 * configured.
4930 * @beta
4931 */
4932export declare function setIndexConfiguration(firestore: Firestore, json: string): Promise<void>;
4933
4934/**
4935 * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
4936 *
4937 * @param logLevel - The verbosity you set for activity and error logging. Can
4938 * be any of the following values:
4939 *
4940 * <ul>
4941 * <li>`debug` for the most verbose logging level, primarily for
4942 * debugging.</li>
4943 * <li>`error` to log errors only.</li>
4944 * <li><code>`silent` to turn off logging.</li>
4945 * </ul>
4946 */
4947export declare function setLogLevel(logLevel: LogLevel): void;
4948
4949/**
4950 * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link
4951 * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be
4952 * configured to perform granular merges instead of overwriting the target
4953 * documents in their entirety by providing a `SetOptions` with `merge: true`.
4954 *
4955 * @param merge - Changes the behavior of a `setDoc()` call to only replace the
4956 * values specified in its data argument. Fields omitted from the `setDoc()`
4957 * call remain untouched. If your input sets any field to an empty map, all
4958 * nested fields are overwritten.
4959 * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace
4960 * the specified field paths. Any field path that is not specified is ignored
4961 * and remains untouched. If your input sets any field to an empty map, all
4962 * nested fields are overwritten.
4963 */
4964export declare type SetOptions = {
4965 readonly merge?: boolean;
4966} | {
4967 readonly mergeFields?: Array<string | FieldPath>;
4968};
4969
4970/**
4971 * A `SharedClientState` keeps track of the global state of the mutations
4972 * and query targets for all active clients with the same persistence key (i.e.
4973 * project ID and FirebaseApp name). It relays local changes to other clients
4974 * and updates its local state as new state is observed.
4975 *
4976 * `SharedClientState` is primarily used for synchronization in Multi-Tab
4977 * environments. Each tab is responsible for registering its active query
4978 * targets and mutations. `SharedClientState` will then notify the listener
4979 * assigned to `.syncEngine` for updates to mutations and queries that
4980 * originated in other clients.
4981 *
4982 * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be
4983 * assigned before calling `start()`.
4984 */
4985declare interface SharedClientState {
4986 onlineStateHandler: ((onlineState: OnlineState) => void) | null;
4987 sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null;
4988 /** Registers the Mutation Batch ID of a newly pending mutation. */
4989 addPendingMutation(batchId: BatchId): void;
4990 /**
4991 * Records that a pending mutation has been acknowledged or rejected.
4992 * Called by the primary client to notify secondary clients of mutation
4993 * results as they come back from the backend.
4994 */
4995 updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void;
4996 /**
4997 * Associates a new Query Target ID with the local Firestore client. Returns
4998 * the new query state for the query (which can be 'current' if the query is
4999 * already associated with another tab).
5000 *
5001 * If the target id is already associated with local client, the method simply
5002 * returns its `QueryTargetState`.
5003 */
5004 addLocalQueryTarget(targetId: TargetId): QueryTargetState;
5005 /** Removes the Query Target ID association from the local client. */
5006 removeLocalQueryTarget(targetId: TargetId): void;
5007 /** Checks whether the target is associated with the local client. */
5008 isLocalQueryTarget(targetId: TargetId): boolean;
5009 /**
5010 * Processes an update to a query target.
5011 *
5012 * Called by the primary client to notify secondary clients of document
5013 * changes or state transitions that affect the provided query target.
5014 */
5015 updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void;
5016 /**
5017 * Removes the target's metadata entry.
5018 *
5019 * Called by the primary client when all clients stopped listening to a query
5020 * target.
5021 */
5022 clearQueryState(targetId: TargetId): void;
5023 /**
5024 * Gets the active Query Targets IDs for all active clients.
5025 *
5026 * The implementation for this may require O(n) runtime, where 'n' is the size
5027 * of the result set.
5028 */
5029 getAllActiveQueryTargets(): SortedSet<TargetId>;
5030 /**
5031 * Checks whether the provided target ID is currently being listened to by
5032 * any of the active clients.
5033 *
5034 * The implementation may require O(n*log m) runtime, where 'n' is the number
5035 * of clients and 'm' the number of targets.
5036 */
5037 isActiveQueryTarget(targetId: TargetId): boolean;
5038 /**
5039 * Starts the SharedClientState, reads existing client data and registers
5040 * listeners for updates to new and existing clients.
5041 */
5042 start(): Promise<void>;
5043 /** Shuts down the `SharedClientState` and its listeners. */
5044 shutdown(): void;
5045 /**
5046 * Changes the active user and removes all existing user-specific data. The
5047 * user change does not call back into SyncEngine (for example, no mutations
5048 * will be marked as removed).
5049 */
5050 handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void;
5051 /** Changes the shared online state of all clients. */
5052 setOnlineState(onlineState: OnlineState): void;
5053 writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;
5054 /**
5055 * Notifies other clients when remote documents have changed due to loading
5056 * a bundle.
5057 *
5058 * @param collectionGroups The collection groups affected by this bundle.
5059 */
5060 notifyBundleLoaded(collectionGroups: Set<string>): void;
5061}
5062
5063/**
5064 * Returns true if the provided snapshots are equal.
5065 *
5066 * @param left - A snapshot to compare.
5067 * @param right - A snapshot to compare.
5068 * @returns true if the snapshots are equal.
5069 */
5070export declare function snapshotEqual<T>(left: DocumentSnapshot<T> | QuerySnapshot<T>, right: DocumentSnapshot<T> | QuerySnapshot<T>): boolean;
5071
5072/**
5073 * An options object that can be passed to {@link (onSnapshot:1)} and {@link
5074 * QuerySnapshot.docChanges} to control which types of changes to include in the
5075 * result set.
5076 */
5077export declare interface SnapshotListenOptions {
5078 /**
5079 * Include a change even if only the metadata of the query or of a document
5080 * changed. Default is false.
5081 */
5082 readonly includeMetadataChanges?: boolean;
5083}
5084
5085/**
5086 * Metadata about a snapshot, describing the state of the snapshot.
5087 */
5088export declare class SnapshotMetadata {
5089 /**
5090 * True if the snapshot contains the result of local writes (for example
5091 * `set()` or `update()` calls) that have not yet been committed to the
5092 * backend. If your listener has opted into metadata updates (via
5093 * `SnapshotListenOptions`) you will receive another snapshot with
5094 * `hasPendingWrites` equal to false once the writes have been committed to
5095 * the backend.
5096 */
5097 readonly hasPendingWrites: boolean;
5098 /**
5099 * True if the snapshot was created from cached data rather than guaranteed
5100 * up-to-date server data. If your listener has opted into metadata updates
5101 * (via `SnapshotListenOptions`) you will receive another snapshot with
5102 * `fromCache` set to false once the client has received up-to-date data from
5103 * the backend.
5104 */
5105 readonly fromCache: boolean;
5106 /** @hideconstructor */
5107 constructor(hasPendingWrites: boolean, fromCache: boolean);
5108 /**
5109 * Returns true if this `SnapshotMetadata` is equal to the provided one.
5110 *
5111 * @param other - The `SnapshotMetadata` to compare against.
5112 * @returns true if this `SnapshotMetadata` is equal to the provided one.
5113 */
5114 isEqual(other: SnapshotMetadata): boolean;
5115}
5116
5117/**
5118 * Options that configure how data is retrieved from a `DocumentSnapshot` (for
5119 * example the desired behavior for server timestamps that have not yet been set
5120 * to their final value).
5121 */
5122export declare interface SnapshotOptions {
5123 /**
5124 * If set, controls the return value for server timestamps that have not yet
5125 * been set to their final value.
5126 *
5127 * By specifying 'estimate', pending server timestamps return an estimate
5128 * based on the local clock. This estimate will differ from the final value
5129 * and cause these values to change once the server result becomes available.
5130 *
5131 * By specifying 'previous', pending timestamps will be ignored and return
5132 * their previous value instead.
5133 *
5134 * If omitted or set to 'none', `null` will be returned by default until the
5135 * server value becomes available.
5136 */
5137 readonly serverTimestamps?: 'estimate' | 'previous' | 'none';
5138}
5139
5140/**
5141 * A version of a document in Firestore. This corresponds to the version
5142 * timestamp, such as update_time or read_time.
5143 */
5144declare class SnapshotVersion {
5145 private timestamp;
5146 static fromTimestamp(value: Timestamp): SnapshotVersion;
5147 static min(): SnapshotVersion;
5148 static max(): SnapshotVersion;
5149 private constructor();
5150 compareTo(other: SnapshotVersion): number;
5151 isEqual(other: SnapshotVersion): boolean;
5152 /** Returns a number representation of the version for use in spec tests. */
5153 toMicroseconds(): number;
5154 toString(): string;
5155 toTimestamp(): Timestamp;
5156}
5157
5158declare class SortedMap<K, V> {
5159 comparator: Comparator<K>;
5160 root: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
5161 constructor(comparator: Comparator<K>, root?: LLRBNode<K, V> | LLRBEmptyNode<K, V>);
5162 insert(key: K, value: V): SortedMap<K, V>;
5163 remove(key: K): SortedMap<K, V>;
5164 get(key: K): V | null;
5165 indexOf(key: K): number;
5166 isEmpty(): boolean;
5167 get size(): number;
5168 minKey(): K | null;
5169 maxKey(): K | null;
5170 inorderTraversal<T>(action: (k: K, v: V) => T): T;
5171 forEach(fn: (k: K, v: V) => void): void;
5172 toString(): string;
5173 reverseTraversal<T>(action: (k: K, v: V) => T): T;
5174 getIterator(): SortedMapIterator<K, V>;
5175 getIteratorFrom(key: K): SortedMapIterator<K, V>;
5176 getReverseIterator(): SortedMapIterator<K, V>;
5177 getReverseIteratorFrom(key: K): SortedMapIterator<K, V>;
5178}
5179
5180declare class SortedMapIterator<K, V> {
5181 private isReverse;
5182 private nodeStack;
5183 constructor(node: LLRBNode<K, V> | LLRBEmptyNode<K, V>, startKey: K | null, comparator: Comparator<K>, isReverse: boolean);
5184 getNext(): Entry<K, V>;
5185 hasNext(): boolean;
5186 peek(): Entry<K, V> | null;
5187}
5188
5189/**
5190 * SortedSet is an immutable (copy-on-write) collection that holds elements
5191 * in order specified by the provided comparator.
5192 *
5193 * NOTE: if provided comparator returns 0 for two elements, we consider them to
5194 * be equal!
5195 */
5196declare class SortedSet<T> {
5197 private comparator;
5198 private data;
5199 constructor(comparator: (left: T, right: T) => number);
5200 has(elem: T): boolean;
5201 first(): T | null;
5202 last(): T | null;
5203 get size(): number;
5204 indexOf(elem: T): number;
5205 /** Iterates elements in order defined by "comparator" */
5206 forEach(cb: (elem: T) => void): void;
5207 /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
5208 forEachInRange(range: [T, T], cb: (elem: T) => void): void;
5209 /**
5210 * Iterates over `elem`s such that: start &lt;= elem until false is returned.
5211 */
5212 forEachWhile(cb: (elem: T) => boolean, start?: T): void;
5213 /** Finds the least element greater than or equal to `elem`. */
5214 firstAfterOrEqual(elem: T): T | null;
5215 getIterator(): SortedSetIterator<T>;
5216 getIteratorFrom(key: T): SortedSetIterator<T>;
5217 /** Inserts or updates an element */
5218 add(elem: T): SortedSet<T>;
5219 /** Deletes an element */
5220 delete(elem: T): SortedSet<T>;
5221 isEmpty(): boolean;
5222 unionWith(other: SortedSet<T>): SortedSet<T>;
5223 isEqual(other: SortedSet<T>): boolean;
5224 toArray(): T[];
5225 toString(): string;
5226 private copy;
5227}
5228
5229declare class SortedSetIterator<T> {
5230 private iter;
5231 constructor(iter: SortedMapIterator<T, boolean>);
5232 getNext(): T;
5233 hasNext(): boolean;
5234}
5235
5236/**
5237 * Creates a {@link QueryConstraint} that modifies the result set to start after the
5238 * provided document (exclusive). The starting position is relative to the order
5239 * of the query. The document must contain all of the fields provided in the
5240 * orderBy of the query.
5241 *
5242 * @param snapshot - The snapshot of the document to start after.
5243 * @returns A {@link QueryConstraint} to pass to `query()`
5244 */
5245export declare function startAfter(snapshot: DocumentSnapshot_2<unknown>): QueryConstraint;
5246
5247/**
5248 * Creates a {@link QueryConstraint} that modifies the result set to start after the
5249 * provided fields relative to the order of the query. The order of the field
5250 * values must match the order of the order by clauses of the query.
5251 *
5252 * @param fieldValues - The field values to start this query after, in order
5253 * of the query's order by.
5254 * @returns A {@link QueryConstraint} to pass to `query()`
5255 */
5256export declare function startAfter(...fieldValues: unknown[]): QueryConstraint;
5257
5258/**
5259 * Creates a {@link QueryConstraint} that modifies the result set to start at the
5260 * provided document (inclusive). The starting position is relative to the order
5261 * of the query. The document must contain all of the fields provided in the
5262 * `orderBy` of this query.
5263 *
5264 * @param snapshot - The snapshot of the document to start at.
5265 * @returns A {@link QueryConstraint} to pass to `query()`.
5266 */
5267export declare function startAt(snapshot: DocumentSnapshot_2<unknown>): QueryConstraint;
5268
5269/**
5270 * Creates a {@link QueryConstraint} that modifies the result set to start at the
5271 * provided fields relative to the order of the query. The order of the field
5272 * values must match the order of the order by clauses of the query.
5273 *
5274 * @param fieldValues - The field values to start this query at, in order
5275 * of the query's order by.
5276 * @returns A {@link QueryConstraint} to pass to `query()`.
5277 */
5278export declare function startAt(...fieldValues: unknown[]): QueryConstraint;
5279
5280declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery;
5281
5282/**
5283 * @license
5284 * Copyright 2017 Google LLC
5285 *
5286 * Licensed under the Apache License, Version 2.0 (the "License");
5287 * you may not use this file except in compliance with the License.
5288 * You may obtain a copy of the License at
5289 *
5290 * http://www.apache.org/licenses/LICENSE-2.0
5291 *
5292 * Unless required by applicable law or agreed to in writing, software
5293 * distributed under the License is distributed on an "AS IS" BASIS,
5294 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5295 * See the License for the specific language governing permissions and
5296 * limitations under the License.
5297 */
5298/**
5299 * SyncEngine is the central controller in the client SDK architecture. It is
5300 * the glue code between the EventManager, LocalStore, and RemoteStore. Some of
5301 * SyncEngine's responsibilities include:
5302 * 1. Coordinating client requests and remote events between the EventManager
5303 * and the local and remote data stores.
5304 * 2. Managing a View object for each query, providing the unified view between
5305 * the local and remote data stores.
5306 * 3. Notifying the RemoteStore when the LocalStore has new mutations in its
5307 * queue that need sending to the backend.
5308 *
5309 * The SyncEngines methods should only ever be called by methods running in the
5310 * global async queue.
5311 *
5312 * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe()
5313 * function. Instead, it directly depends on EventManager's tree-shakeable API
5314 * (via `ensureWatchStream()`).
5315 */
5316declare interface SyncEngine {
5317 isPrimaryClient: boolean;
5318}
5319
5320/**
5321 * A Target represents the WatchTarget representation of a Query, which is used
5322 * by the LocalStore and the RemoteStore to keep track of and to execute
5323 * backend queries. While a Query can represent multiple Targets, each Targets
5324 * maps to a single WatchTarget in RemoteStore and a single TargetData entry
5325 * in persistence.
5326 */
5327declare interface Target {
5328 readonly path: _ResourcePath;
5329 readonly collectionGroup: string | null;
5330 readonly orderBy: OrderBy[];
5331 readonly filters: Filter[];
5332 readonly limit: number | null;
5333 readonly startAt: Bound | null;
5334 readonly endAt: Bound | null;
5335}
5336
5337/**
5338 * Represents cached targets received from the remote backend.
5339 *
5340 * The cache is keyed by `Target` and entries in the cache are `TargetData`
5341 * instances.
5342 */
5343declare interface TargetCache {
5344 /**
5345 * A global snapshot version representing the last consistent snapshot we
5346 * received from the backend. This is monotonically increasing and any
5347 * snapshots received from the backend prior to this version (e.g. for targets
5348 * resumed with a resume_token) should be suppressed (buffered) until the
5349 * backend has caught up to this snapshot version again. This prevents our
5350 * cache from ever going backwards in time.
5351 *
5352 * This is updated whenever our we get a TargetChange with a read_time and
5353 * empty target_ids.
5354 */
5355 getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise<SnapshotVersion>;
5356 /**
5357 * @returns The highest sequence number observed, including any that might be
5358 * persisted on-disk.
5359 */
5360 getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise<ListenSequenceNumber>;
5361 /**
5362 * Call provided function with each `TargetData` that we have cached.
5363 */
5364 forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise<void>;
5365 /**
5366 * Set the highest listen sequence number and optionally updates the
5367 * snapshot version of the last consistent snapshot received from the backend
5368 * (see getLastRemoteSnapshotVersion() for more details).
5369 *
5370 * @param highestListenSequenceNumber - The new maximum listen sequence number.
5371 * @param lastRemoteSnapshotVersion - The new snapshot version. Optional.
5372 */
5373 setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise<void>;
5374 /**
5375 * Adds an entry in the cache.
5376 *
5377 * The cache key is extracted from `targetData.target`. The key must not already
5378 * exist in the cache.
5379 *
5380 * @param targetData - A TargetData instance to put in the cache.
5381 */
5382 addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise<void>;
5383 /**
5384 * Updates an entry in the cache.
5385 *
5386 * The cache key is extracted from `targetData.target`. The entry must already
5387 * exist in the cache, and it will be replaced.
5388 * @param targetData - The TargetData to be replaced into the cache.
5389 */
5390 updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise<void>;
5391 /**
5392 * Removes the cached entry for the given target data. It is an error to remove
5393 * a target data that does not exist.
5394 *
5395 * Multi-Tab Note: This operation should only be called by the primary client.
5396 */
5397 removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise<void>;
5398 /**
5399 * The number of targets currently in the cache.
5400 */
5401 getTargetCount(transaction: PersistenceTransaction): PersistencePromise<number>;
5402 /**
5403 * Looks up a TargetData entry by target.
5404 *
5405 * @param target - The query target corresponding to the entry to look up.
5406 * @returns The cached TargetData entry, or null if the cache has no entry for
5407 * the target.
5408 */
5409 getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise<TargetData | null>;
5410 /**
5411 * Adds the given document keys to cached query results of the given target
5412 * ID.
5413 *
5414 * Multi-Tab Note: This operation should only be called by the primary client.
5415 */
5416 addMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise<void>;
5417 /**
5418 * Removes the given document keys from the cached query results of the
5419 * given target ID.
5420 *
5421 * Multi-Tab Note: This operation should only be called by the primary client.
5422 */
5423 removeMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise<void>;
5424 /**
5425 * Removes all the keys in the query results of the given target ID.
5426 *
5427 * Multi-Tab Note: This operation should only be called by the primary client.
5428 */
5429 removeMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise<void>;
5430 /**
5431 * Returns the document keys that match the provided target ID.
5432 */
5433 getMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise<DocumentKeySet>;
5434 /**
5435 * Returns a new target ID that is higher than any query in the cache. If
5436 * there are no queries in the cache, returns the first valid target ID.
5437 * Allocated target IDs are persisted and `allocateTargetId()` will never
5438 * return the same ID twice.
5439 */
5440 allocateTargetId(transaction: PersistenceTransaction): PersistencePromise<TargetId>;
5441 containsKey(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise<boolean>;
5442}
5443
5444/**
5445 * A TargetChange specifies the set of changes for a specific target as part of
5446 * a RemoteEvent. These changes track which documents are added, modified or
5447 * removed, as well as the target's resume token and whether the target is
5448 * marked CURRENT.
5449 * The actual changes *to* documents are not part of the TargetChange since
5450 * documents may be part of multiple targets.
5451 */
5452declare class TargetChange {
5453 /**
5454 * An opaque, server-assigned token that allows watching a query to be resumed
5455 * after disconnecting without retransmitting all the data that matches the
5456 * query. The resume token essentially identifies a point in time from which
5457 * the server should resume sending results.
5458 */
5459 readonly resumeToken: _ByteString;
5460 /**
5461 * The "current" (synced) status of this target. Note that "current"
5462 * has special meaning in the RPC protocol that implies that a target is
5463 * both up-to-date and consistent with the rest of the watch stream.
5464 */
5465 readonly current: boolean;
5466 /**
5467 * The set of documents that were newly assigned to this target as part of
5468 * this remote event.
5469 */
5470 readonly addedDocuments: DocumentKeySet;
5471 /**
5472 * The set of documents that were already assigned to this target but received
5473 * an update during this remote event.
5474 */
5475 readonly modifiedDocuments: DocumentKeySet;
5476 /**
5477 * The set of documents that were removed from this target as part of this
5478 * remote event.
5479 */
5480 readonly removedDocuments: DocumentKeySet;
5481 constructor(
5482 /**
5483 * An opaque, server-assigned token that allows watching a query to be resumed
5484 * after disconnecting without retransmitting all the data that matches the
5485 * query. The resume token essentially identifies a point in time from which
5486 * the server should resume sending results.
5487 */
5488 resumeToken: _ByteString,
5489 /**
5490 * The "current" (synced) status of this target. Note that "current"
5491 * has special meaning in the RPC protocol that implies that a target is
5492 * both up-to-date and consistent with the rest of the watch stream.
5493 */
5494 current: boolean,
5495 /**
5496 * The set of documents that were newly assigned to this target as part of
5497 * this remote event.
5498 */
5499 addedDocuments: DocumentKeySet,
5500 /**
5501 * The set of documents that were already assigned to this target but received
5502 * an update during this remote event.
5503 */
5504 modifiedDocuments: DocumentKeySet,
5505 /**
5506 * The set of documents that were removed from this target as part of this
5507 * remote event.
5508 */
5509 removedDocuments: DocumentKeySet);
5510 /**
5511 * This method is used to create a synthesized TargetChanges that can be used to
5512 * apply a CURRENT status change to a View (for queries executed in a different
5513 * tab) or for new queries (to raise snapshots with correct CURRENT status).
5514 */
5515 static createSynthesizedTargetChangeForCurrentChange(targetId: TargetId, current: boolean, resumeToken: _ByteString): TargetChange;
5516}
5517
5518declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET';
5519
5520/**
5521 * An immutable set of metadata that the local store tracks for each target.
5522 */
5523declare class TargetData {
5524 /** The target being listened to. */
5525 readonly target: Target;
5526 /**
5527 * The target ID to which the target corresponds; Assigned by the
5528 * LocalStore for user listens and by the SyncEngine for limbo watches.
5529 */
5530 readonly targetId: TargetId;
5531 /** The purpose of the target. */
5532 readonly purpose: TargetPurpose;
5533 /**
5534 * The sequence number of the last transaction during which this target data
5535 * was modified.
5536 */
5537 readonly sequenceNumber: ListenSequenceNumber;
5538 /** The latest snapshot version seen for this target. */
5539 readonly snapshotVersion: SnapshotVersion;
5540 /**
5541 * The maximum snapshot version at which the associated view
5542 * contained no limbo documents.
5543 */
5544 readonly lastLimboFreeSnapshotVersion: SnapshotVersion;
5545 /**
5546 * An opaque, server-assigned token that allows watching a target to be
5547 * resumed after disconnecting without retransmitting all the data that
5548 * matches the target. The resume token essentially identifies a point in
5549 * time from which the server should resume sending results.
5550 */
5551 readonly resumeToken: _ByteString;
5552 constructor(
5553 /** The target being listened to. */
5554 target: Target,
5555 /**
5556 * The target ID to which the target corresponds; Assigned by the
5557 * LocalStore for user listens and by the SyncEngine for limbo watches.
5558 */
5559 targetId: TargetId,
5560 /** The purpose of the target. */
5561 purpose: TargetPurpose,
5562 /**
5563 * The sequence number of the last transaction during which this target data
5564 * was modified.
5565 */
5566 sequenceNumber: ListenSequenceNumber,
5567 /** The latest snapshot version seen for this target. */
5568 snapshotVersion?: SnapshotVersion,
5569 /**
5570 * The maximum snapshot version at which the associated view
5571 * contained no limbo documents.
5572 */
5573 lastLimboFreeSnapshotVersion?: SnapshotVersion,
5574 /**
5575 * An opaque, server-assigned token that allows watching a target to be
5576 * resumed after disconnecting without retransmitting all the data that
5577 * matches the target. The resume token essentially identifies a point in
5578 * time from which the server should resume sending results.
5579 */
5580 resumeToken?: _ByteString);
5581 /** Creates a new target data instance with an updated sequence number. */
5582 withSequenceNumber(sequenceNumber: number): TargetData;
5583 /**
5584 * Creates a new target data instance with an updated resume token and
5585 * snapshot version.
5586 */
5587 withResumeToken(resumeToken: _ByteString, snapshotVersion: SnapshotVersion): TargetData;
5588 /**
5589 * Creates a new target data instance with an updated last limbo free
5590 * snapshot version number.
5591 */
5592 withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion: SnapshotVersion): TargetData;
5593}
5594
5595/**
5596 * A locally-assigned ID used to refer to a target being watched via the
5597 * Watch service.
5598 */
5599declare type TargetId = number;
5600
5601/** An enumeration of the different purposes we have for targets. */
5602declare const enum TargetPurpose {
5603 /** A regular, normal query target. */
5604 Listen = 0,
5605 /**
5606 * The query target was used to refill a query after an existence filter mismatch.
5607 */
5608 ExistenceFilterMismatch = 1,
5609 /** The query target was used to resolve a limbo document. */
5610 LimboResolution = 2
5611}
5612
5613/**
5614 * Represents the state of bundle loading tasks.
5615 *
5616 * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will
5617 * be no more updates after they are reported.
5618 */
5619export declare type TaskState = 'Error' | 'Running' | 'Success';
5620
5621/**
5622 * Terminates the provided {@link Firestore} instance.
5623 *
5624 * After calling `terminate()` only the `clearIndexedDbPersistence()` function
5625 * may be used. Any other function will throw a `FirestoreError`.
5626 *
5627 * To restart after termination, create a new instance of FirebaseFirestore with
5628 * {@link (getFirestore:1)}.
5629 *
5630 * Termination does not cancel any pending writes, and any promises that are
5631 * awaiting a response from the server will not be resolved. If you have
5632 * persistence enabled, the next time you start this instance, it will resume
5633 * sending these writes to the server.
5634 *
5635 * Note: Under normal circumstances, calling `terminate()` is not required. This
5636 * function is useful only when you want to force this instance to release all
5637 * of its resources or in combination with `clearIndexedDbPersistence()` to
5638 * ensure that all local state is destroyed between test runs.
5639 *
5640 * @returns A `Promise` that is resolved when the instance has been successfully
5641 * terminated.
5642 */
5643export declare function terminate(firestore: Firestore): Promise<void>;
5644
5645/**
5646 * Wellknown "timer" IDs used when scheduling delayed operations on the
5647 * AsyncQueue. These IDs can then be used from tests to check for the presence
5648 * of operations or to run them early.
5649 *
5650 * The string values are used when encoding these timer IDs in JSON spec tests.
5651 */
5652declare const enum TimerId {
5653 /** All can be used with runDelayedOperationsEarly() to run all timers. */
5654 All = "all",
5655 /**
5656 * The following 5 timers are used in persistent_stream.ts for the listen and
5657 * write streams. The "Idle" timer is used to close the stream due to
5658 * inactivity. The "ConnectionBackoff" timer is used to restart a stream once
5659 * the appropriate backoff delay has elapsed. The health check is used to mark
5660 * a stream healthy if it has not received an error during its initial setup.
5661 */
5662 ListenStreamIdle = "listen_stream_idle",
5663 ListenStreamConnectionBackoff = "listen_stream_connection_backoff",
5664 WriteStreamIdle = "write_stream_idle",
5665 WriteStreamConnectionBackoff = "write_stream_connection_backoff",
5666 HealthCheckTimeout = "health_check_timeout",
5667 /**
5668 * A timer used in online_state_tracker.ts to transition from
5669 * OnlineState.Unknown to Offline after a set timeout, rather than waiting
5670 * indefinitely for success or failure.
5671 */
5672 OnlineStateTimeout = "online_state_timeout",
5673 /**
5674 * A timer used to update the client metadata in IndexedDb, which is used
5675 * to determine the primary leaseholder.
5676 */
5677 ClientMetadataRefresh = "client_metadata_refresh",
5678 /** A timer used to periodically attempt LRU Garbage collection */
5679 LruGarbageCollection = "lru_garbage_collection",
5680 /**
5681 * A timer used to retry transactions. Since there can be multiple concurrent
5682 * transactions, multiple of these may be in the queue at a given time.
5683 */
5684 TransactionRetry = "transaction_retry",
5685 /**
5686 * A timer used to retry operations scheduled via retryable AsyncQueue
5687 * operations.
5688 */
5689 AsyncQueueRetry = "async_queue_retry",
5690 /**
5691 * A timer used to periodically attempt index backfill.
5692 */
5693 IndexBackfill = "index_backfill"
5694}
5695
5696/**
5697 * @license
5698 * Copyright 2017 Google LLC
5699 *
5700 * Licensed under the Apache License, Version 2.0 (the "License");
5701 * you may not use this file except in compliance with the License.
5702 * You may obtain a copy of the License at
5703 *
5704 * http://www.apache.org/licenses/LICENSE-2.0
5705 *
5706 * Unless required by applicable law or agreed to in writing, software
5707 * distributed under the License is distributed on an "AS IS" BASIS,
5708 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5709 * See the License for the specific language governing permissions and
5710 * limitations under the License.
5711 */
5712/**
5713 * A `Timestamp` represents a point in time independent of any time zone or
5714 * calendar, represented as seconds and fractions of seconds at nanosecond
5715 * resolution in UTC Epoch time.
5716 *
5717 * It is encoded using the Proleptic Gregorian Calendar which extends the
5718 * Gregorian calendar backwards to year one. It is encoded assuming all minutes
5719 * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
5720 * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
5721 * 9999-12-31T23:59:59.999999999Z.
5722 *
5723 * For examples and further specifications, refer to the
5724 * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
5725 */
5726export declare class Timestamp {
5727 /**
5728 * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
5729 */
5730 readonly seconds: number;
5731 /**
5732 * The fractions of a second at nanosecond resolution.*
5733 */
5734 readonly nanoseconds: number;
5735 /**
5736 * Creates a new timestamp with the current date, with millisecond precision.
5737 *
5738 * @returns a new timestamp representing the current date.
5739 */
5740 static now(): Timestamp;
5741 /**
5742 * Creates a new timestamp from the given date.
5743 *
5744 * @param date - The date to initialize the `Timestamp` from.
5745 * @returns A new `Timestamp` representing the same point in time as the given
5746 * date.
5747 */
5748 static fromDate(date: Date): Timestamp;
5749 /**
5750 * Creates a new timestamp from the given number of milliseconds.
5751 *
5752 * @param milliseconds - Number of milliseconds since Unix epoch
5753 * 1970-01-01T00:00:00Z.
5754 * @returns A new `Timestamp` representing the same point in time as the given
5755 * number of milliseconds.
5756 */
5757 static fromMillis(milliseconds: number): Timestamp;
5758 /**
5759 * Creates a new timestamp.
5760 *
5761 * @param seconds - The number of seconds of UTC time since Unix epoch
5762 * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
5763 * 9999-12-31T23:59:59Z inclusive.
5764 * @param nanoseconds - The non-negative fractions of a second at nanosecond
5765 * resolution. Negative second values with fractions must still have
5766 * non-negative nanoseconds values that count forward in time. Must be
5767 * from 0 to 999,999,999 inclusive.
5768 */
5769 constructor(
5770 /**
5771 * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
5772 */
5773 seconds: number,
5774 /**
5775 * The fractions of a second at nanosecond resolution.*
5776 */
5777 nanoseconds: number);
5778 /**
5779 * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
5780 * causes a loss of precision since `Date` objects only support millisecond
5781 * precision.
5782 *
5783 * @returns JavaScript `Date` object representing the same point in time as
5784 * this `Timestamp`, with millisecond precision.
5785 */
5786 toDate(): Date;
5787 /**
5788 * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
5789 * epoch). This operation causes a loss of precision.
5790 *
5791 * @returns The point in time corresponding to this timestamp, represented as
5792 * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
5793 */
5794 toMillis(): number;
5795 _compareTo(other: Timestamp): number;
5796 /**
5797 * Returns true if this `Timestamp` is equal to the provided one.
5798 *
5799 * @param other - The `Timestamp` to compare against.
5800 * @returns true if this `Timestamp` is equal to the provided one.
5801 */
5802 isEqual(other: Timestamp): boolean;
5803 /** Returns a textual representation of this `Timestamp`. */
5804 toString(): string;
5805 /** Returns a JSON-serializable representation of this `Timestamp`. */
5806 toJSON(): {
5807 seconds: number;
5808 nanoseconds: number;
5809 };
5810 /**
5811 * Converts this object to a primitive string, which allows `Timestamp` objects
5812 * to be compared using the `>`, `<=`, `>=` and `>` operators.
5813 */
5814 valueOf(): string;
5815}
5816
5817declare type Timestamp_2 = string | {
5818 seconds?: string | number;
5819 nanos?: number;
5820};
5821
5822declare interface Token {
5823 /** Type of token. */
5824 type: TokenType;
5825 /**
5826 * The user with which the token is associated (used for persisting user
5827 * state on disk, etc.).
5828 * This will be null for Tokens of the type 'AppCheck'.
5829 */
5830 user?: User;
5831 /** Header values to set for this token */
5832 headers: Map<string, string>;
5833}
5834
5835declare type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';
5836
5837/**
5838 * A reference to a transaction.
5839 *
5840 * The `Transaction` object passed to a transaction's `updateFunction` provides
5841 * the methods to read and write data within the transaction context. See
5842 * {@link runTransaction}.
5843 */
5844export declare class Transaction extends Transaction_2 {
5845 protected readonly _firestore: Firestore;
5846 /** @hideconstructor */
5847 constructor(_firestore: Firestore, _transaction: Transaction_3);
5848 /**
5849 * Reads the document referenced by the provided {@link DocumentReference}.
5850 *
5851 * @param documentRef - A reference to the document to be read.
5852 * @returns A `DocumentSnapshot` with the read data.
5853 */
5854 get<T>(documentRef: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
5855}
5856
5857/**
5858 * A reference to a transaction.
5859 *
5860 * The `Transaction` object passed to a transaction's `updateFunction` provides
5861 * the methods to read and write data within the transaction context. See
5862 * {@link runTransaction}.
5863 */
5864declare class Transaction_2 {
5865 protected readonly _firestore: Firestore_2;
5866 private readonly _transaction;
5867 private readonly _dataReader;
5868 /** @hideconstructor */
5869 constructor(_firestore: Firestore_2, _transaction: Transaction_3);
5870 /**
5871 * Reads the document referenced by the provided {@link DocumentReference}.
5872 *
5873 * @param documentRef - A reference to the document to be read.
5874 * @returns A `DocumentSnapshot` with the read data.
5875 */
5876 get<T>(documentRef: DocumentReference<T>): Promise<DocumentSnapshot_2<T>>;
5877 /**
5878 * Writes to the document referred to by the provided {@link
5879 * DocumentReference}. If the document does not exist yet, it will be created.
5880 *
5881 * @param documentRef - A reference to the document to be set.
5882 * @param data - An object of the fields and values for the document.
5883 * @throws Error - If the provided input is not a valid Firestore document.
5884 * @returns This `Transaction` instance. Used for chaining method calls.
5885 */
5886 set<T>(documentRef: DocumentReference<T>, data: WithFieldValue<T>): this;
5887 /**
5888 * Writes to the document referred to by the provided {@link
5889 * DocumentReference}. If the document does not exist yet, it will be created.
5890 * If you provide `merge` or `mergeFields`, the provided data can be merged
5891 * into an existing document.
5892 *
5893 * @param documentRef - A reference to the document to be set.
5894 * @param data - An object of the fields and values for the document.
5895 * @param options - An object to configure the set behavior.
5896 * @throws Error - If the provided input is not a valid Firestore document.
5897 * @returns This `Transaction` instance. Used for chaining method calls.
5898 */
5899 set<T>(documentRef: DocumentReference<T>, data: PartialWithFieldValue<T>, options: SetOptions): this;
5900 /**
5901 * Updates fields in the document referred to by the provided {@link
5902 * DocumentReference}. The update will fail if applied to a document that does
5903 * not exist.
5904 *
5905 * @param documentRef - A reference to the document to be updated.
5906 * @param data - An object containing the fields and values with which to
5907 * update the document. Fields can contain dots to reference nested fields
5908 * within the document.
5909 * @throws Error - If the provided input is not valid Firestore data.
5910 * @returns This `Transaction` instance. Used for chaining method calls.
5911 */
5912 update<T>(documentRef: DocumentReference<T>, data: UpdateData<T>): this;
5913 /**
5914 * Updates fields in the document referred to by the provided {@link
5915 * DocumentReference}. The update will fail if applied to a document that does
5916 * not exist.
5917 *
5918 * Nested fields can be updated by providing dot-separated field path
5919 * strings or by providing `FieldPath` objects.
5920 *
5921 * @param documentRef - A reference to the document to be updated.
5922 * @param field - The first field to update.
5923 * @param value - The first value.
5924 * @param moreFieldsAndValues - Additional key/value pairs.
5925 * @throws Error - If the provided input is not valid Firestore data.
5926 * @returns This `Transaction` instance. Used for chaining method calls.
5927 */
5928 update(documentRef: DocumentReference<unknown>, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this;
5929 /**
5930 * Deletes the document referred to by the provided {@link DocumentReference}.
5931 *
5932 * @param documentRef - A reference to the document to be deleted.
5933 * @returns This `Transaction` instance. Used for chaining method calls.
5934 */
5935 delete(documentRef: DocumentReference<unknown>): this;
5936}
5937
5938/**
5939 * Internal transaction object responsible for accumulating the mutations to
5940 * perform and the base versions for any documents read.
5941 */
5942declare class Transaction_3 {
5943 private datastore;
5944 private readVersions;
5945 private mutations;
5946 private committed;
5947 /**
5948 * A deferred usage error that occurred previously in this transaction that
5949 * will cause the transaction to fail once it actually commits.
5950 */
5951 private lastWriteError;
5952 /**
5953 * Set of documents that have been written in the transaction.
5954 *
5955 * When there's more than one write to the same key in a transaction, any
5956 * writes after the first are handled differently.
5957 */
5958 private writtenDocs;
5959 constructor(datastore: Datastore);
5960 lookup(keys: _DocumentKey[]): Promise<Document_2[]>;
5961 set(key: _DocumentKey, data: ParsedSetData): void;
5962 update(key: _DocumentKey, data: ParsedUpdateData): void;
5963 delete(key: _DocumentKey): void;
5964 commit(): Promise<void>;
5965 private recordVersion;
5966 /**
5967 * Returns the version of this document when it was read in this transaction,
5968 * as a precondition, or no precondition if it was not read.
5969 */
5970 private precondition;
5971 /**
5972 * Returns the precondition for a document if the operation is an update.
5973 */
5974 private preconditionForUpdate;
5975 private write;
5976 private ensureCommitNotCalled;
5977}
5978
5979/**
5980 * @license
5981 * Copyright 2022 Google LLC
5982 *
5983 * Licensed under the Apache License, Version 2.0 (the "License");
5984 * you may not use this file except in compliance with the License.
5985 * You may obtain a copy of the License at
5986 *
5987 * http://www.apache.org/licenses/LICENSE-2.0
5988 *
5989 * Unless required by applicable law or agreed to in writing, software
5990 * distributed under the License is distributed on an "AS IS" BASIS,
5991 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5992 * See the License for the specific language governing permissions and
5993 * limitations under the License.
5994 */
5995/**
5996 * Options to customize transaction behavior.
5997 */
5998export declare interface TransactionOptions {
5999 /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */
6000 readonly maxAttempts?: number;
6001}
6002
6003/** Used to represent a field transform on a mutation. */
6004declare class TransformOperation {
6005 private _;
6006}
6007
6008declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL';
6009
6010/**
6011 * Given a union type `U = T1 | T2 | ...`, returns an intersected type
6012 * `(T1 & T2 & ...)`.
6013 *
6014 * Uses distributive conditional types and inference from conditional types.
6015 * This works because multiple candidates for the same type variable in
6016 * contra-variant positions causes an intersection type to be inferred.
6017 * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types
6018 * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type
6019 */
6020export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
6021
6022/**
6023 * A function returned by `onSnapshot()` that removes the listener when invoked.
6024 */
6025export declare interface Unsubscribe {
6026 /** Removes the listener when invoked. */
6027 (): void;
6028}
6029
6030/**
6031 * An untyped Firestore Data Converter interface that is shared between the
6032 * lite, firestore-exp and classic SDK.
6033 */
6034declare interface UntypedFirestoreDataConverter<T> {
6035 toFirestore(modelObject: WithFieldValue<T>): DocumentData_2;
6036 toFirestore(modelObject: PartialWithFieldValue<T>, options: SetOptions_2): DocumentData_2;
6037 fromFirestore(snapshot: unknown, options?: unknown): T;
6038}
6039
6040/**
6041 * Update data (for use with {@link (updateDoc:1)}) that consists of field paths
6042 * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots
6043 * reference nested fields within the document. FieldValues can be passed in
6044 * as property values.
6045 */
6046export declare type UpdateData<T> = T extends Primitive ? T : T extends {} ? {
6047 [K in keyof T]?: UpdateData<T[K]> | FieldValue;
6048} & NestedUpdateFields<T> : Partial<T>;
6049
6050/**
6051 * Updates fields in the document referred to by the specified
6052 * `DocumentReference`. The update will fail if applied to a document that does
6053 * not exist.
6054 *
6055 * @param reference - A reference to the document to update.
6056 * @param data - An object containing the fields and values with which to
6057 * update the document. Fields can contain dots to reference nested fields
6058 * within the document.
6059 * @returns A `Promise` resolved once the data has been successfully written
6060 * to the backend (note that it won't resolve while you're offline).
6061 */
6062export declare function updateDoc<T>(reference: DocumentReference<T>, data: UpdateData<T>): Promise<void>;
6063
6064/**
6065 * Updates fields in the document referred to by the specified
6066 * `DocumentReference` The update will fail if applied to a document that does
6067 * not exist.
6068 *
6069 * Nested fields can be updated by providing dot-separated field path
6070 * strings or by providing `FieldPath` objects.
6071 *
6072 * @param reference - A reference to the document to update.
6073 * @param field - The first field to update.
6074 * @param value - The first value.
6075 * @param moreFieldsAndValues - Additional key value pairs.
6076 * @returns A `Promise` resolved once the data has been successfully written
6077 * to the backend (note that it won't resolve while you're offline).
6078 */
6079export declare function updateDoc(reference: DocumentReference<unknown>, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise<void>;
6080
6081/**
6082 * @license
6083 * Copyright 2017 Google LLC
6084 *
6085 * Licensed under the Apache License, Version 2.0 (the "License");
6086 * you may not use this file except in compliance with the License.
6087 * You may obtain a copy of the License at
6088 *
6089 * http://www.apache.org/licenses/LICENSE-2.0
6090 *
6091 * Unless required by applicable law or agreed to in writing, software
6092 * distributed under the License is distributed on an "AS IS" BASIS,
6093 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6094 * See the License for the specific language governing permissions and
6095 * limitations under the License.
6096 */
6097/**
6098 * Simple wrapper around a nullable UID. Mostly exists to make code more
6099 * readable.
6100 */
6101declare class User {
6102 readonly uid: string | null;
6103 /** A user with a null UID. */
6104 static readonly UNAUTHENTICATED: User;
6105 static readonly GOOGLE_CREDENTIALS: User;
6106 static readonly FIRST_PARTY: User;
6107 static readonly MOCK_USER: User;
6108 constructor(uid: string | null);
6109 isAuthenticated(): boolean;
6110 /**
6111 * Returns a key representing this user, suitable for inclusion in a
6112 * dictionary.
6113 */
6114 toKey(): string;
6115 isEqual(otherUser: User): boolean;
6116}
6117
6118/**
6119 * Validates that two boolean options are not set at the same time.
6120 * @internal
6121 */
6122export declare function _validateIsNotUsedTogether(optionName1: string, argument1: boolean | undefined, optionName2: string, argument2: boolean | undefined): void;
6123
6124declare type Value = firestoreV1ApiClientInterfaces.Value;
6125
6126declare type ValueNullValue = 'NULL_VALUE';
6127
6128declare class ViewSnapshot {
6129 readonly query: Query_2;
6130 readonly docs: DocumentSet;
6131 readonly oldDocs: DocumentSet;
6132 readonly docChanges: DocumentViewChange[];
6133 readonly mutatedKeys: DocumentKeySet;
6134 readonly fromCache: boolean;
6135 readonly syncStateChanged: boolean;
6136 readonly excludesMetadataChanges: boolean;
6137 readonly hasCachedResults: boolean;
6138 constructor(query: Query_2, docs: DocumentSet, oldDocs: DocumentSet, docChanges: DocumentViewChange[], mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, excludesMetadataChanges: boolean, hasCachedResults: boolean);
6139 /** Returns a view snapshot as if all documents in the snapshot were added. */
6140 static fromInitialDocuments(query: Query_2, documents: DocumentSet, mutatedKeys: DocumentKeySet, fromCache: boolean, hasCachedResults: boolean): ViewSnapshot;
6141 get hasPendingWrites(): boolean;
6142 isEqual(other: ViewSnapshot): boolean;
6143}
6144
6145/**
6146 * Waits until all currently pending writes for the active user have been
6147 * acknowledged by the backend.
6148 *
6149 * The returned promise resolves immediately if there are no outstanding writes.
6150 * Otherwise, the promise waits for all previously issued writes (including
6151 * those written in a previous app session), but it does not wait for writes
6152 * that were added after the function is called. If you want to wait for
6153 * additional writes, call `waitForPendingWrites()` again.
6154 *
6155 * Any outstanding `waitForPendingWrites()` promises are rejected during user
6156 * changes.
6157 *
6158 * @returns A `Promise` which resolves when all currently pending writes have been
6159 * acknowledged by the backend.
6160 */
6161export declare function waitForPendingWrites(firestore: Firestore): Promise<void>;
6162
6163/**
6164 * Creates a {@link QueryConstraint} that enforces that documents must contain the
6165 * specified field and that the value should satisfy the relation constraint
6166 * provided.
6167 *
6168 * @param fieldPath - The path to compare
6169 * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
6170 * "&lt;=", "!=").
6171 * @param value - The value for comparison
6172 * @returns The created {@link Query}.
6173 */
6174export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryConstraint;
6175
6176/**
6177 * Filter conditions in a {@link where} clause are specified using the
6178 * strings '&lt;', '&lt;=', '==', '!=', '&gt;=', '&gt;', 'array-contains', 'in',
6179 * 'array-contains-any', and 'not-in'.
6180 */
6181export declare type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in';
6182
6183/**
6184 * Allows FieldValues to be passed in as a property value while maintaining
6185 * type safety.
6186 */
6187export declare type WithFieldValue<T> = T | (T extends Primitive ? T : T extends {} ? {
6188 [K in keyof T]: WithFieldValue<T[K]> | FieldValue;
6189} : never);
6190
6191/**
6192 * A write batch, used to perform multiple writes as a single atomic unit.
6193 *
6194 * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
6195 * provides methods for adding writes to the write batch. None of the writes
6196 * will be committed (or visible locally) until {@link WriteBatch.commit} is
6197 * called.
6198 */
6199export declare class WriteBatch {
6200 private readonly _firestore;
6201 private readonly _commitHandler;
6202 private readonly _dataReader;
6203 private _mutations;
6204 private _committed;
6205 /** @hideconstructor */
6206 constructor(_firestore: Firestore_2, _commitHandler: (m: Mutation[]) => Promise<void>);
6207 /**
6208 * Writes to the document referred to by the provided {@link
6209 * DocumentReference}. If the document does not exist yet, it will be created.
6210 *
6211 * @param documentRef - A reference to the document to be set.
6212 * @param data - An object of the fields and values for the document.
6213 * @returns This `WriteBatch` instance. Used for chaining method calls.
6214 */
6215 set<T>(documentRef: DocumentReference<T>, data: WithFieldValue<T>): WriteBatch;
6216 /**
6217 * Writes to the document referred to by the provided {@link
6218 * DocumentReference}. If the document does not exist yet, it will be created.
6219 * If you provide `merge` or `mergeFields`, the provided data can be merged
6220 * into an existing document.
6221 *
6222 * @param documentRef - A reference to the document to be set.
6223 * @param data - An object of the fields and values for the document.
6224 * @param options - An object to configure the set behavior.
6225 * @throws Error - If the provided input is not a valid Firestore document.
6226 * @returns This `WriteBatch` instance. Used for chaining method calls.
6227 */
6228 set<T>(documentRef: DocumentReference<T>, data: PartialWithFieldValue<T>, options: SetOptions): WriteBatch;
6229 /**
6230 * Updates fields in the document referred to by the provided {@link
6231 * DocumentReference}. The update will fail if applied to a document that does
6232 * not exist.
6233 *
6234 * @param documentRef - A reference to the document to be updated.
6235 * @param data - An object containing the fields and values with which to
6236 * update the document. Fields can contain dots to reference nested fields
6237 * within the document.
6238 * @throws Error - If the provided input is not valid Firestore data.
6239 * @returns This `WriteBatch` instance. Used for chaining method calls.
6240 */
6241 update<T>(documentRef: DocumentReference<T>, data: UpdateData<T>): WriteBatch;
6242 /**
6243 * Updates fields in the document referred to by this {@link
6244 * DocumentReference}. The update will fail if applied to a document that does
6245 * not exist.
6246 *
6247 * Nested fields can be update by providing dot-separated field path strings
6248 * or by providing `FieldPath` objects.
6249 *
6250 * @param documentRef - A reference to the document to be updated.
6251 * @param field - The first field to update.
6252 * @param value - The first value.
6253 * @param moreFieldsAndValues - Additional key value pairs.
6254 * @throws Error - If the provided input is not valid Firestore data.
6255 * @returns This `WriteBatch` instance. Used for chaining method calls.
6256 */
6257 update(documentRef: DocumentReference<unknown>, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch;
6258 /**
6259 * Deletes the document referred to by the provided {@link DocumentReference}.
6260 *
6261 * @param documentRef - A reference to the document to be deleted.
6262 * @returns This `WriteBatch` instance. Used for chaining method calls.
6263 */
6264 delete(documentRef: DocumentReference<unknown>): WriteBatch;
6265 /**
6266 * Commits all of the writes in this write batch as a single atomic unit.
6267 *
6268 * The result of these writes will only be reflected in document reads that
6269 * occur after the returned promise resolves. If the client is offline, the
6270 * write fails. If you would like to see local modifications or buffer writes
6271 * until the client is online, use the full Firestore SDK.
6272 *
6273 * @returns A `Promise` resolved once all of the writes in the batch have been
6274 * successfully written to the backend as an atomic unit (note that it won't
6275 * resolve while you're offline).
6276 */
6277 commit(): Promise<void>;
6278 private _verifyNotCommitted;
6279}
6280
6281/**
6282 * Creates a write batch, used for performing multiple writes as a single
6283 * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}
6284 * is 500.
6285 *
6286 * Unlike transactions, write batches are persisted offline and therefore are
6287 * preferable when you don't need to condition your writes on read data.
6288 *
6289 * @returns A {@link WriteBatch} that can be used to atomically execute multiple
6290 * writes.
6291 */
6292export declare function writeBatch(firestore: Firestore): WriteBatch;
6293
6294export { }