@firebase/firestore
Version:
The Cloud Firestore component of the Firebase JS SDK.
1,365 lines (1,328 loc) • 398 kB
TypeScript
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
interface VersionService {
library: string;
version: string;
}
interface PlatformLoggerService {
getPlatformInfoString(): string;
}
interface HeartbeatService {
/**
* Called to report a heartbeat. The function will generate
* a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it
* to IndexedDB.
* Note that we only store one heartbeat per day. So if a heartbeat for today is
* already logged, subsequent calls to this function in the same day will be ignored.
*/
triggerHeartbeat(): Promise<void>;
/**
* Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.
* It also clears all heartbeats from memory as well as in IndexedDB.
*/
getHeartbeatsHeader(): Promise<string>;
}
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A {@link @firebase/app#FirebaseApp} holds the initialization information for a collection of
* services.
*
* Do not call this constructor directly. Instead, use
* {@link (initializeApp:1) | initializeApp()} to create an app.
*
* @public
*/
interface FirebaseApp {
/**
* The (read-only) name for this app.
*
* The default app's name is `"[DEFAULT]"`.
*
* @example
* ```javascript
* // The default app's name is "[DEFAULT]"
* const app = initializeApp(defaultAppConfig);
* console.log(app.name); // "[DEFAULT]"
* ```
*
* @example
* ```javascript
* // A named app's name is what you provide to initializeApp()
* const otherApp = initializeApp(otherAppConfig, "other");
* console.log(otherApp.name); // "other"
* ```
*/
readonly name: string;
/**
* The (read-only) configuration options for this app. These are the original
* parameters given in {@link (initializeApp:1) | initializeApp()}.
*
* @example
* ```javascript
* const app = initializeApp(config);
* console.log(app.options.databaseURL === config.databaseURL); // true
* ```
*/
readonly options: FirebaseOptions;
/**
* The settable config flag for GDPR opt-in/opt-out
*/
automaticDataCollectionEnabled: boolean;
}
/**
* @public
*
* Firebase configuration object. Contains a set of parameters required by
* services in order to successfully communicate with Firebase server APIs
* and to associate client data with your Firebase project and
* Firebase application. Typically this object is populated by the Firebase
* console at project setup. See also:
* {@link https://firebase.google.com/docs/web/setup#config-object | Learn about the Firebase config object}.
*/
interface FirebaseOptions {
/**
* An encrypted string used when calling certain APIs that don't need to
* access private user data
* (example value: `AIzaSyDOCAbC123dEf456GhI789jKl012-MnO`).
*/
apiKey?: string;
/**
* Auth domain for the project ID.
*/
authDomain?: string;
/**
* Default Realtime Database URL.
*/
databaseURL?: string;
/**
* The unique identifier for the project across all of Firebase and
* Google Cloud.
*/
projectId?: string;
/**
* The default Cloud Storage bucket name.
*/
storageBucket?: string;
/**
* Unique numerical value used to identify each sender that can send
* Firebase Cloud Messaging messages to client apps.
*/
messagingSenderId?: string;
/**
* Unique identifier for the app.
*/
appId?: string;
/**
* An ID automatically created when you enable Analytics in your
* Firebase project and register a web app. In versions 7.20.0
* and higher, this parameter is optional.
*/
measurementId?: string;
}
/**
* @internal
*/
interface _FirebaseService {
app: FirebaseApp;
/**
* Delete the service and free it's resources - called from
* {@link @firebase/app#deleteApp | deleteApp()}
*/
_delete(): Promise<void>;
}
declare module '@firebase/component' {
interface NameServiceMapping {
'app': FirebaseApp;
'app-version': VersionService;
'heartbeat': HeartbeatService;
'platform-logger': PlatformLoggerService;
}
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
type LogLevelString = 'debug' | 'verbose' | 'info' | 'warn' | 'error' | 'silent';
/**
* An object that can be injected into the environment as __FIREBASE_DEFAULTS__,
* either as a property of globalThis, a shell environment variable, or a
* cookie.
*
* This object can be used to automatically configure and initialize
* a Firebase app as well as any emulators.
*
* @public
*/
interface FirebaseDefaults {
config?: Record<string, string>;
emulatorHosts?: Record<string, string>;
_authTokenSyncURL?: string;
_authIdTokenMaxAge?: number;
/**
* Override Firebase's runtime environment detection and
* force the SDK to act as if it were in the specified environment.
*/
forceEnvironment?: 'browser' | 'node';
[key: string]: unknown;
}
declare global {
var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined;
}
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
type FirebaseSignInProvider = 'custom' | 'email' | 'password' | 'phone' | 'anonymous' | 'google.com' | 'facebook.com' | 'github.com' | 'twitter.com' | 'microsoft.com' | 'apple.com';
interface FirebaseIdToken {
iss: string;
aud: string;
sub: string;
iat: number;
exp: number;
user_id: string;
auth_time: number;
provider_id?: 'anonymous';
email?: string;
email_verified?: boolean;
phone_number?: string;
name?: string;
picture?: string;
firebase: {
sign_in_provider: FirebaseSignInProvider;
identities?: {
[provider in FirebaseSignInProvider]?: string[];
};
};
[claim: string]: unknown;
uid?: never;
}
type EmulatorMockTokenOptions = ({
user_id: string;
} | {
sub: string;
}) & Partial<FirebaseIdToken>;
declare class FirebaseError extends Error {
/** The error code for this error. */
readonly code: string;
/** Custom data for this error. */
customData?: Record<string, unknown> | undefined;
/** The custom name for all FirebaseErrors. */
readonly name: string;
constructor(
/** The error code for this error. */
code: string, message: string,
/** Custom data for this error. */
customData?: Record<string, unknown> | undefined);
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Simple wrapper around a nullable UID. Mostly exists to make code more
* readable.
*/
declare class User {
readonly uid: string | null;
/** A user with a null UID. */
static readonly UNAUTHENTICATED: User;
static readonly GOOGLE_CREDENTIALS: User;
static readonly FIRST_PARTY: User;
static readonly MOCK_USER: User;
constructor(uid: string | null);
isAuthenticated(): boolean;
/**
* Returns a key representing this user, suitable for inclusion in a
* dictionary.
*/
toKey(): string;
isEqual(otherUser: User): boolean;
}
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
interface FirebaseAppCheckInternal {
// Get the current AttestationToken. Attaches to the most recent in-flight request if one
// is present. Returns null if no token is present and no token requests are in-flight.
getToken(forceRefresh?: boolean): Promise<AppCheckTokenResult>;
// Always returns a fresh limited-use token suitable for Replay Protection.
// The returned token must be used and consumed as soon as possible.
getLimitedUseToken(): Promise<AppCheckTokenResult>;
// Registers a listener to changes in the token state. There can be more than one listener
// registered at the same time for one or more FirebaseAppAttestation instances. The
// listeners call back on the UI thread whenever the current token associated with this
// FirebaseAppAttestation changes.
addTokenListener(listener: AppCheckTokenListener): void;
// Unregisters a listener to changes in the token state.
removeTokenListener(listener: AppCheckTokenListener): void;
}
type AppCheckTokenListener = (token: AppCheckTokenResult) => void;
// If the error field is defined, the token field will be populated with a dummy token
interface AppCheckTokenResult {
readonly token: string;
readonly error?: Error;
}
declare module '@firebase/component' {
interface NameServiceMapping {
'app-check-internal': FirebaseAppCheckInternal;
}
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
interface FirebaseAuthTokenData {
accessToken: string;
}
interface FirebaseAuthInternal {
getToken(refreshToken?: boolean): Promise<FirebaseAuthTokenData | null>;
getUid(): string | null;
addAuthTokenListener(fn: (token: string | null) => void): void;
removeAuthTokenListener(fn: (token: string | null) => void): void;
}
declare module '@firebase/component' {
interface NameServiceMapping {
'auth-internal': FirebaseAuthInternal;
}
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The set of Firestore status codes. The codes are the same at the ones
* exposed by gRPC here:
* https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
*
* Possible values:
* - 'cancelled': The operation was cancelled (typically by the caller).
* - 'unknown': Unknown error or an error from a different error domain.
* - 'invalid-argument': Client specified an invalid argument. Note that this
* differs from 'failed-precondition'. 'invalid-argument' indicates
* arguments that are problematic regardless of the state of the system
* (e.g. an invalid field name).
* - 'deadline-exceeded': Deadline expired before operation could complete.
* For operations that change the state of the system, this error may be
* returned even if the operation has completed successfully. For example,
* a successful response from a server could have been delayed long enough
* for the deadline to expire.
* - 'not-found': Some requested document was not found.
* - 'already-exists': Some document that we attempted to create already
* exists.
* - 'permission-denied': The caller does not have permission to execute the
* specified operation.
* - 'resource-exhausted': Some resource has been exhausted, perhaps a
* per-user quota, or perhaps the entire file system is out of space.
* - 'failed-precondition': Operation was rejected because the system is not
* in a state required for the operation's execution.
* - 'aborted': The operation was aborted, typically due to a concurrency
* issue like transaction aborts, etc.
* - 'out-of-range': Operation was attempted past the valid range.
* - 'unimplemented': Operation is not implemented or not supported/enabled.
* - 'internal': Internal errors. Means some invariants expected by
* underlying system has been broken. If you see one of these errors,
* something is very broken.
* - 'unavailable': The service is currently unavailable. This is most likely
* a transient condition and may be corrected by retrying with a backoff.
* - 'data-loss': Unrecoverable data loss or corruption.
* - 'unauthenticated': The request does not have valid authentication
* credentials for the operation.
*/
type FirestoreErrorCode$1 = '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';
/** An error returned by a Firestore operation. */
declare class FirestoreError$1 extends FirebaseError {
/**
* The backend error code associated with this error.
*/
readonly code: FirestoreErrorCode$1;
/**
* A custom error description.
*/
readonly message: string;
/** The stack of the error. */
readonly stack?: string;
/** @hideconstructor */
constructor(
/**
* The backend error code associated with this error.
*/
code: FirestoreErrorCode$1,
/**
* A custom error description.
*/
message: string);
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Wellknown "timer" IDs used when scheduling delayed operations on the
* AsyncQueue. These IDs can then be used from tests to check for the presence
* of operations or to run them early.
*
* The string values are used when encoding these timer IDs in JSON spec tests.
*/
declare const enum TimerId {
/** All can be used with runDelayedOperationsEarly() to run all timers. */
All = "all",
/**
* The following 5 timers are used in persistent_stream.ts for the listen and
* write streams. The "Idle" timer is used to close the stream due to
* inactivity. The "ConnectionBackoff" timer is used to restart a stream once
* the appropriate backoff delay has elapsed. The health check is used to mark
* a stream healthy if it has not received an error during its initial setup.
*/
ListenStreamIdle = "listen_stream_idle",
ListenStreamConnectionBackoff = "listen_stream_connection_backoff",
WriteStreamIdle = "write_stream_idle",
WriteStreamConnectionBackoff = "write_stream_connection_backoff",
HealthCheckTimeout = "health_check_timeout",
/**
* A timer used in online_state_tracker.ts to transition from
* OnlineState.Unknown to Offline after a set timeout, rather than waiting
* indefinitely for success or failure.
*/
OnlineStateTimeout = "online_state_timeout",
/**
* A timer used to update the client metadata in IndexedDb, which is used
* to determine the primary leaseholder.
*/
ClientMetadataRefresh = "client_metadata_refresh",
/** A timer used to periodically attempt LRU Garbage collection */
LruGarbageCollection = "lru_garbage_collection",
/**
* A timer used to retry transactions. Since there can be multiple concurrent
* transactions, multiple of these may be in the queue at a given time.
*/
TransactionRetry = "transaction_retry",
/**
* A timer used to retry operations scheduled via retryable AsyncQueue
* operations.
*/
AsyncQueueRetry = "async_queue_retry",
/**
* A timer used to periodically attempt index backfill.
*/
IndexBackfill = "index_backfill"
}
/**
* Represents an operation scheduled to be run in the future on an AsyncQueue.
*
* It is created via DelayedOperation.createAndSchedule().
*
* Supports cancellation (via cancel()) and early execution (via skipDelay()).
*
* Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
* in newer versions of TypeScript defines `finally`, which is not available in
* IE.
*/
declare class DelayedOperation<T extends unknown> implements PromiseLike<T> {
private readonly asyncQueue;
readonly timerId: TimerId;
readonly targetTimeMs: number;
private readonly op;
private readonly removalCallback;
private timerHandle;
private readonly deferred;
private constructor();
get promise(): Promise<T>;
/**
* Creates and returns a DelayedOperation that has been scheduled to be
* executed on the provided asyncQueue after the provided delayMs.
*
* @param asyncQueue - The queue to schedule the operation on.
* @param id - A Timer ID identifying the type of operation this is.
* @param delayMs - The delay (ms) before the operation should be scheduled.
* @param op - The operation to run.
* @param removalCallback - A callback to be called synchronously once the
* operation is executed or canceled, notifying the AsyncQueue to remove it
* from its delayedOperations list.
* PORTING NOTE: This exists to prevent making removeDelayedOperation() and
* the DelayedOperation class public.
*/
static createAndSchedule<R extends unknown>(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise<R>, removalCallback: (op: DelayedOperation<R>) => void): DelayedOperation<R>;
/**
* Starts the timer. This is called immediately after construction by
* createAndSchedule().
*/
private start;
/**
* Queues the operation to run immediately (if it hasn't already been run or
* canceled).
*/
skipDelay(): void;
/**
* Cancels the operation if it hasn't already been executed or canceled. The
* promise will be rejected.
*
* As long as the operation has not yet been run, calling cancel() provides a
* guarantee that the operation will not be run.
*/
cancel(reason?: string): void;
then: <TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined) => Promise<TResult1 | TResult2>;
private handleDelayElapsed;
private clearTimeout;
}
interface AsyncQueue {
readonly isShuttingDown: boolean;
/**
* Adds a new operation to the queue without waiting for it to complete (i.e.
* we ignore the Promise result).
*/
enqueueAndForget<T extends unknown>(op: () => Promise<T>): void;
/**
* Regardless if the queue has initialized shutdown, adds a new operation to the
* queue without waiting for it to complete (i.e. we ignore the Promise result).
*/
enqueueAndForgetEvenWhileRestricted<T extends unknown>(op: () => Promise<T>): void;
/**
* Initialize the shutdown of this queue. Once this method is called, the
* only possible way to request running an operation is through
* `enqueueEvenWhileRestricted()`.
*
* @param purgeExistingTasks Whether already enqueued tasked should be
* rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults
* to false.
*/
enterRestrictedMode(purgeExistingTasks?: boolean): void;
/**
* Adds a new operation to the queue. Returns a promise that will be resolved
* when the promise returned by the new operation is (with its value).
*/
enqueue<T extends unknown>(op: () => Promise<T>): Promise<T>;
/**
* Enqueue a retryable operation.
*
* A retryable operation is rescheduled with backoff if it fails with a
* IndexedDbTransactionError (the error type used by SimpleDb). All
* retryable operations are executed in order and only run if all prior
* operations were retried successfully.
*/
enqueueRetryable(op: () => Promise<void>): void;
/**
* Schedules an operation to be queued on the AsyncQueue once the specified
* `delayMs` has elapsed. The returned DelayedOperation can be used to cancel
* or fast-forward the operation prior to its running.
*/
enqueueAfterDelay<T extends unknown>(timerId: TimerId, delayMs: number, op: () => Promise<T>): DelayedOperation<T>;
/**
* Verifies there's an operation currently in-progress on the AsyncQueue.
* Unfortunately we can't verify that the running code is in the promise chain
* of that operation, so this isn't a foolproof check, but it should be enough
* to catch some bugs.
*/
verifyOperationInProgress(): void;
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @internal
*/
type AuthTokenFactory = () => string;
/**
* @internal
*/
interface FirstPartyCredentialsSettings {
['type']: 'firstParty';
['sessionIndex']: string;
['iamToken']: string | null;
['authTokenFactory']: AuthTokenFactory | null;
}
interface ProviderCredentialsSettings {
['type']: 'provider';
['client']: CredentialsProvider<User>;
}
/** Settings for private credentials */
type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings;
type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';
interface Token {
/** Type of token. */
type: TokenType;
/**
* The user with which the token is associated (used for persisting user
* state on disk, etc.).
* This will be null for Tokens of the type 'AppCheck'.
*/
user?: User;
/** Header values to set for this token */
headers: Map<string, string>;
}
/**
* A Listener for credential change events. The listener should fetch a new
* token and may need to invalidate other state if the current user has also
* changed.
*/
type CredentialChangeListener<T> = (credential: T) => Promise<void>;
/**
* Provides methods for getting the uid and token for the current user and
* listening for changes.
*/
interface CredentialsProvider<T> {
/**
* Starts the credentials provider and specifies a listener to be notified of
* credential changes (sign-in / sign-out, token changes). It is immediately
* called once with the initial user.
*
* The change listener is invoked on the provided AsyncQueue.
*/
start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener<T>): void;
/** Requests a token for the current user. */
getToken(): Promise<Token | null>;
/**
* Marks the last retrieved token as invalid, making the next GetToken request
* force-refresh the token.
*/
invalidateToken(): void;
shutdown(): void;
}
/**
* A CredentialsProvider that always yields an empty token.
* @internal
*/
declare class EmptyAuthCredentialsProvider implements CredentialsProvider<User> {
getToken(): Promise<Token | null>;
invalidateToken(): void;
start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener<User>): void;
shutdown(): void;
}
/**
* An AppCheck token provider that always yields an empty token.
* @internal
*/
declare class EmptyAppCheckTokenProvider implements CredentialsProvider<string> {
getToken(): Promise<Token | null>;
invalidateToken(): void;
start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener<string>): void;
shutdown(): void;
}
/**
* @license
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Options that configure the SDK’s underlying network transport (WebChannel)
* when long-polling is used.
*
* Note: This interface is "experimental" and is subject to change.
*
* See `FirestoreSettings.experimentalAutoDetectLongPolling`,
* `FirestoreSettings.experimentalForceLongPolling`, and
* `FirestoreSettings.experimentalLongPollingOptions`.
*/
interface ExperimentalLongPollingOptions {
/**
* The desired maximum timeout interval, in seconds, to complete a
* long-polling GET response. Valid values are between 5 and 30, inclusive.
* Floating point values are allowed and will be rounded to the nearest
* millisecond.
*
* By default, when long-polling is used the "hanging GET" request sent by
* the client times out after 30 seconds. To request a different timeout
* from the server, set this setting with the desired timeout.
*
* Changing the default timeout may be useful, for example, if the buffering
* proxy that necessitated enabling long-polling in the first place has a
* shorter timeout for hanging GET requests, in which case setting the
* long-polling timeout to a shorter value, such as 25 seconds, may fix
* prematurely-closed hanging GET requests.
* For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.
*/
timeoutSeconds?: number;
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
declare class DatabaseInfo {
readonly databaseId: DatabaseId;
readonly appId: string;
readonly persistenceKey: string;
readonly host: string;
readonly ssl: boolean;
readonly forceLongPolling: boolean;
readonly autoDetectLongPolling: boolean;
readonly longPollingOptions: ExperimentalLongPollingOptions;
readonly useFetchStreams: boolean;
readonly isUsingEmulator: boolean;
/**
* Constructs a DatabaseInfo using the provided host, databaseId and
* persistenceKey.
*
* @param databaseId - The database to use.
* @param appId - The Firebase App Id.
* @param persistenceKey - A unique identifier for this Firestore's local
* storage (used in conjunction with the databaseId).
* @param host - The Firestore backend host to connect to.
* @param ssl - Whether to use SSL when connecting.
* @param forceLongPolling - Whether to use the forceLongPolling option
* when using WebChannel as the network transport.
* @param autoDetectLongPolling - Whether to use the detectBufferingProxy
* option when using WebChannel as the network transport.
* @param longPollingOptions Options that configure long-polling.
* @param useFetchStreams Whether to use the Fetch API instead of
* XMLHTTPRequest
*/
constructor(databaseId: DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, longPollingOptions: ExperimentalLongPollingOptions, useFetchStreams: boolean, isUsingEmulator: boolean);
}
/**
* Represents the database ID a Firestore client is associated with.
* @internal
*/
declare class DatabaseId {
readonly projectId: string;
readonly database: string;
constructor(projectId: string, database?: string);
static empty(): DatabaseId;
get isDefaultDatabase(): boolean;
isEqual(other: {}): boolean;
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* BatchID is a locally assigned ID for a batch of mutations that have been
* applied.
*/
type BatchId = number;
/**
* A locally-assigned ID used to refer to a target being watched via the
* Watch service.
*/
type TargetId = number;
type ListenSequenceNumber = number;
/**
* Describes the online state of the Firestore client. Note that this does not
* indicate whether or not the remote store is trying to connect or not. This is
* primarily used by the View / EventManager code to change their behavior while
* offline (e.g. get() calls shouldn't wait for data from the server and
* snapshot events should set metadata.isFromCache=true).
*
* The string values should not be changed since they are persisted in
* WebStorage.
*/
declare const enum OnlineState {
/**
* The Firestore client is in an unknown online state. This means the client
* is either not actively trying to establish a connection or it is currently
* trying to establish a connection, but it has not succeeded or failed yet.
* Higher-level components should not operate in offline mode.
*/
Unknown = "Unknown",
/**
* The client is connected and the connections are healthy. This state is
* reached after a successful connection and there has been at least one
* successful message received from the backends.
*/
Online = "Online",
/**
* The client is either trying to establish a connection but failing, or it
* has been explicitly marked offline via a call to disableNetwork().
* Higher-level components should operate in offline mode.
*/
Offline = "Offline"
}
/**
* Path represents an ordered sequence of string segments.
*/
declare abstract class BasePath<B extends BasePath<B>> {
private segments;
private offset;
private len;
constructor(segments: string[], offset?: number, length?: number);
/**
* Abstract constructor method to construct an instance of B with the given
* parameters.
*/
protected abstract construct(segments: string[], offset?: number, length?: number): B;
/**
* Returns a String representation.
*
* Implementing classes are required to provide deterministic implementations as
* the String representation is used to obtain canonical Query IDs.
*/
abstract toString(): string;
get length(): number;
isEqual(other: B): boolean;
child(nameOrPath: string | B): B;
/** The index of one past the last segment of the path. */
private limit;
popFirst(size?: number): B;
popLast(): B;
firstSegment(): string;
lastSegment(): string;
get(index: number): string;
isEmpty(): boolean;
isPrefixOf(other: this): boolean;
isImmediateParentOf(potentialChild: this): boolean;
forEach(fn: (segment: string) => void): void;
toArray(): string[];
/**
* Compare 2 paths segment by segment, prioritizing numeric IDs
* (e.g., "__id123__") in numeric ascending order, followed by string
* segments in lexicographical order.
*/
static comparator<T extends BasePath<T>>(p1: BasePath<T>, p2: BasePath<T>): number;
private static compareSegments;
private static isNumericId;
private static extractNumericId;
}
/**
* A slash-separated path for navigating resources (documents and collections)
* within Firestore.
*
* @internal
*/
declare class ResourcePath extends BasePath<ResourcePath> {
protected construct(segments: string[], offset?: number, length?: number): ResourcePath;
canonicalString(): string;
toString(): string;
/**
* Returns a string representation of this path
* where each path segment has been encoded with
* `encodeURIComponent`.
*/
toUriEncodedString(): string;
/**
* Creates a resource path from the given slash-delimited string. If multiple
* arguments are provided, all components are combined. Leading and trailing
* slashes from all components are ignored.
*/
static fromString(...pathComponents: string[]): ResourcePath;
static emptyPath(): ResourcePath;
}
/**
* A dot-separated path for navigating sub-objects within a document.
* @internal
*/
declare class FieldPath$2 extends BasePath<FieldPath$2> {
protected construct(segments: string[], offset?: number, length?: number): FieldPath$2;
/**
* Returns true if the string could be used as a segment in a field path
* without escaping.
*/
private static isValidIdentifier;
canonicalString(): string;
toString(): string;
/**
* Returns true if this field references the key of a document.
*/
isKeyField(): boolean;
/**
* The field designating the key of a document.
*/
static keyField(): FieldPath$2;
/**
* Parses a field string from the given server-formatted string.
*
* - Splitting the empty string is not allowed (for now at least).
* - Empty segments within the string (e.g. if there are two consecutive
* separators) are not allowed.
*
* TODO(b/37244157): we should make this more strict. Right now, it allows
* non-identifier path components, even if they aren't escaped.
*/
static fromServerFormat(path: string): FieldPath$2;
static emptyPath(): FieldPath$2;
}
/**
* @license
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Union type representing the aggregate type to be performed.
*/
type AggregateType = 'count' | 'avg' | 'sum';
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A `Timestamp` represents a point in time independent of any time zone or
* calendar, represented as seconds and fractions of seconds at nanosecond
* resolution in UTC Epoch time.
*
* It is encoded using the Proleptic Gregorian Calendar which extends the
* Gregorian calendar backwards to year one. It is encoded assuming all minutes
* are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
* table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59.999999999Z.
*
* For examples and further specifications, refer to the
* {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
*/
declare class Timestamp$1 {
/**
* The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
*/
readonly seconds: number;
/**
* The fractions of a second at nanosecond resolution.*
*/
readonly nanoseconds: number;
/**
* Creates a new timestamp with the current date, with millisecond precision.
*
* @returns a new timestamp representing the current date.
*/
static now(): Timestamp$1;
/**
* Creates a new timestamp from the given date.
*
* @param date - The date to initialize the `Timestamp` from.
* @returns A new `Timestamp` representing the same point in time as the given
* date.
*/
static fromDate(date: Date): Timestamp$1;
/**
* Creates a new timestamp from the given number of milliseconds.
*
* @param milliseconds - Number of milliseconds since Unix epoch
* 1970-01-01T00:00:00Z.
* @returns A new `Timestamp` representing the same point in time as the given
* number of milliseconds.
*/
static fromMillis(milliseconds: number): Timestamp$1;
/**
* Creates a new timestamp.
*
* @param seconds - The number of seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
* @param nanoseconds - The non-negative fractions of a second at nanosecond
* resolution. Negative second values with fractions must still have
* non-negative nanoseconds values that count forward in time. Must be
* from 0 to 999,999,999 inclusive.
*/
constructor(
/**
* The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
*/
seconds: number,
/**
* The fractions of a second at nanosecond resolution.*
*/
nanoseconds: number);
/**
* Converts a `Timestamp` to a JavaScript `Date` object. This conversion
* causes a loss of precision since `Date` objects only support millisecond
* precision.
*
* @returns JavaScript `Date` object representing the same point in time as
* this `Timestamp`, with millisecond precision.
*/
toDate(): Date;
/**
* Converts a `Timestamp` to a numeric timestamp (in milliseconds since
* epoch). This operation causes a loss of precision.
*
* @returns The point in time corresponding to this timestamp, represented as
* the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
*/
toMillis(): number;
_compareTo(other: Timestamp$1): number;
/**
* Returns true if this `Timestamp` is equal to the provided one.
*
* @param other - The `Timestamp` to compare against.
* @returns true if this `Timestamp` is equal to the provided one.
*/
isEqual(other: Timestamp$1): boolean;
/** Returns a textual representation of this `Timestamp`. */
toString(): string;
/** Returns a JSON-serializable representation of this `Timestamp`. */
toJSON(): {
seconds: number;
nanoseconds: number;
};
/**
* Converts this object to a primitive string, which allows `Timestamp` objects
* to be compared using the `>`, `<=`, `>=` and `>` operators.
*/
valueOf(): string;
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A version of a document in Firestore. This corresponds to the version
* timestamp, such as update_time or read_time.
*/
declare class SnapshotVersion {
private timestamp;
static fromTimestamp(value: Timestamp$1): SnapshotVersion;
static min(): SnapshotVersion;
static max(): SnapshotVersion;
private constructor();
compareTo(other: SnapshotVersion): number;
isEqual(other: SnapshotVersion): boolean;
/** Returns a number representation of the version for use in spec tests. */
toMicroseconds(): number;
toString(): string;
toTimestamp(): Timestamp$1;
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @internal
*/
declare class DocumentKey {
readonly path: ResourcePath;
constructor(path: ResourcePath);
static fromPath(path: string): DocumentKey;
static fromName(name: string): DocumentKey;
static empty(): DocumentKey;
get collectionGroup(): string;
/** Returns true if the document is in the specified collectionId. */
hasCollectionId(collectionId: string): boolean;
/** Returns the collection group (i.e. the name of the parent collection) for this key. */
getCollectionGroup(): string;
/** Returns the fully qualified path to the parent collection. */
getCollectionPath(): ResourcePath;
isEqual(other: DocumentKey | null): boolean;
toString(): string;
static comparator(k1: DocumentKey, k2: DocumentKey): number;
static isDocumentKey(path: ResourcePath): boolean;
/**
* Creates and returns a new document key with the given segments.
*
* @param segments - The segments of the path to the document
* @returns A new instance of DocumentKey
*/
static fromSegments(segments: string[]): DocumentKey;
}
interface ApiClientObjectMap<T> {
[k: string]: T;
}
declare type Timestamp = string | {
seconds?: string | number;
nanos?: number;
};
declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR';
declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN';
declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME';
declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING';
declare type IndexState$1 = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR';
declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING';
declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET';
declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL';
declare type ValueNullValue = 'NULL_VALUE';
declare namespace firestoreV1ApiClientInterfaces {
interface ArrayValue {
values?: Value[];
}
interface BatchGetDocumentsRequest {
database?: string;
documents?: string[];
mask?: DocumentMask;
transaction?: string;
newTransaction?: TransactionOptions;
readTime?: string;
}
interface BatchGetDocumentsResponse {
found?: Document;
missing?: string;
transaction?: string;
readTime?: string;
}
interface BeginTransactionRequest {
options?: TransactionOptions;
}
interface BeginTransactionResponse {
transaction?: string;
}
interface CollectionSelector {
collectionId?: string;
allDescendants?: boolean;
}
interface CommitRequest {
database?: string;
writes?: Write[];
transaction?: string;
}
interface CommitResponse {
writeResults?: WriteResult[];
commitTime?: string;
}
interface CompositeFilter {
op?: CompositeFilterOp;
filters?: Filter[];
}
interface Cursor {
values?: Value[];
before?: boolean;
}
interface Document {
name?: string;
fields?: ApiClientObjectMap<Value>;
createTime?: Timestamp;
updateTime?: Timestamp;
}
interface DocumentChange {
document?: Document;
targetIds?: number[];
removedTargetIds?: number[];
}
interface DocumentDelete {
document?: string;
removedTargetIds?: number[];
readTime?: Timestamp;
}
interface DocumentMask {
fieldPaths?: string[];
}
interface DocumentRemove {
document?: string;
removedTargetIds?: number[];
readTime?: string;
}
interface DocumentTransform {
document?: string;
fieldTransforms?: FieldTransform[];
}
interface DocumentsTarget {
documents?: string[];
}
interface Empty {
}
interface ExistenceFilter {
targetId?: number;
count?: number;
unchangedNames?: BloomFilter;
}
interface BloomFilter {
bits?: BitSequence;
hashCount?: number;
}
interface BitSequence {
bitmap?: string | Uint8Array;
padding?: number;
}
interface FieldFilter {
field?: FieldReference;
op?: FieldFilterOp;
value?: Value;
}
interface FieldReference {
fieldPath?: string;
}
interface FieldTransform {
fieldPath?: string;
setToServerValue?: FieldTransformSetToServerValue;
appendMissingElements?: ArrayValue;