{"version":3,"file":"index.cjs.js","sources":["../../src/auth/user.ts","../../src/core/version.ts","../../src/util/log.ts","../../src/platform/browser/format_json.ts","../../src/util/assert.ts","../../src/util/error.ts","../../src/util/promise.ts","../../src/api/credentials.ts","../../src/core/database_info.ts","../../src/model/path.ts","../../src/model/document_key.ts","../../src/util/input_validation.ts","../../src/api/long_polling_options.ts","../../src/util/debug_uid.ts","../../src/util/types.ts","../../src/remote/rest_connection.ts","../../src/remote/rpc_error.ts","../../src/platform/browser_lite/fetch_connection.ts","../../src/core/aggregate.ts","../../src/platform/browser/random_bytes.ts","../../src/util/misc.ts","../../src/util/obj.ts","../../src/util/base64_decode_error.ts","../../src/util/byte_string.ts","../../src/platform/browser/base64.ts","../../src/model/normalize.ts","../../src/lite-api/timestamp.ts","../../src/model/server_timestamps.ts","../../src/model/values.ts","../../src/core/bound.ts","../../src/core/filter.ts","../../src/core/order_by.ts","../../src/core/snapshot_version.ts","../../src/util/sorted_map.ts","../../src/util/sorted_set.ts","../../src/model/field_mask.ts","../../src/model/object_value.ts","../../src/model/document.ts","../../src/core/target.ts","../../src/core/query.ts","../../src/remote/number_serializer.ts","../../src/model/transform_operation.ts","../../src/model/mutation.ts","../../src/remote/serializer.ts","../../src/platform/browser/serializer.ts","../../src/remote/backoff.ts","../../src/remote/datastore.ts","../../src/lite-api/components.ts","../../src/platform/browser_lite/connection.ts","../../src/lite-api/settings.ts","../../src/local/lru_garbage_collector.ts","../../src/local/lru_garbage_collector_impl.ts","../../src/lite-api/database.ts","../../src/lite-api/aggregate_types.ts","../../src/lite-api/reference.ts","../../src/lite-api/bytes.ts","../../src/lite-api/field_path.ts","../../src/lite-api/field_value.ts","../../src/lite-api/geo_point.ts","../../src/lite-api/user_data_reader.ts","../../src/lite-api/snapshot.ts","../../src/lite-api/query.ts","../../src/lite-api/reference_impl.ts","../../src/lite-api/user_data_writer.ts","../../src/lite-api/aggregate.ts","../../src/lite-api/field_value_impl.ts","../../src/lite-api/write_batch.ts","../../src/core/transaction.ts","../../src/core/transaction_options.ts","../../src/core/transaction_runner.ts","../../src/platform/browser/dom.ts","../../src/util/async_queue.ts","../../src/util/async_queue_impl.ts","../../src/local/simple_db.ts","../../src/lite-api/transaction.ts","../../lite/register.ts","../../lite/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n * \n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n logClient.setLogLevel(logLevel);\n}\n\nexport function logDebug(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n const args = obj.map(argToString);\n logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function logError(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n const args = obj.map(argToString);\n logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * @internal\n */\nexport function logWarn(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n const args = obj.map(argToString);\n logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n if (typeof obj === 'string') {\n return obj;\n } else {\n try {\n return formatJSON(obj);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n return JSON.stringify(value);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../core/version';\n\nimport { logError } from './log';\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */\nexport function fail(failure: string = 'Unexpected state'): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message =\n `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ` + failure;\n logError(message);\n\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n */\nexport function hardAssert(\n assertion: boolean,\n message?: string\n): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */\nexport function debugAssert(\n assertion: boolean,\n message: string\n): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */\nexport function debugCast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n debugAssert(\n obj instanceof constructor,\n `Expected type '${constructor.name}', but was '${obj.constructor.name}'`\n );\n return obj as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * The set of Firestore status codes. The codes are the same at the ones\n * exposed by gRPC here:\n * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * Possible values:\n * - 'cancelled': The operation was cancelled (typically by the caller).\n * - 'unknown': Unknown error or an error from a different error domain.\n * - 'invalid-argument': Client specified an invalid argument. Note that this\n * differs from 'failed-precondition'. 'invalid-argument' indicates\n * arguments that are problematic regardless of the state of the system\n * (e.g. an invalid field name).\n * - 'deadline-exceeded': Deadline expired before operation could complete.\n * For operations that change the state of the system, this error may be\n * returned even if the operation has completed successfully. For example,\n * a successful response from a server could have been delayed long enough\n * for the deadline to expire.\n * - 'not-found': Some requested document was not found.\n * - 'already-exists': Some document that we attempted to create already\n * exists.\n * - 'permission-denied': The caller does not have permission to execute the\n * specified operation.\n * - 'resource-exhausted': Some resource has been exhausted, perhaps a\n * per-user quota, or perhaps the entire file system is out of space.\n * - 'failed-precondition': Operation was rejected because the system is not\n * in a state required for the operation's execution.\n * - 'aborted': The operation was aborted, typically due to a concurrency\n * issue like transaction aborts, etc.\n * - 'out-of-range': Operation was attempted past the valid range.\n * - 'unimplemented': Operation is not implemented or not supported/enabled.\n * - 'internal': Internal errors. Means some invariants expected by\n * underlying system has been broken. If you see one of these errors,\n * something is very broken.\n * - 'unavailable': The service is currently unavailable. This is most likely\n * a transient condition and may be corrected by retrying with a backoff.\n * - 'data-loss': Unrecoverable data loss or corruption.\n * - 'unauthenticated': The request does not have valid authentication\n * credentials for the operation.\n */\nexport type FirestoreErrorCode =\n | 'cancelled'\n | 'unknown'\n | 'invalid-argument'\n | 'deadline-exceeded'\n | 'not-found'\n | 'already-exists'\n | 'permission-denied'\n | 'resource-exhausted'\n | 'failed-precondition'\n | 'aborted'\n | 'out-of-range'\n | 'unimplemented'\n | 'internal'\n | 'unavailable'\n | 'data-loss'\n | 'unauthenticated';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = FirestoreErrorCode;\n\nexport const Code = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: 'ok' as FirestoreErrorCode,\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled' as FirestoreErrorCode,\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown' as FirestoreErrorCode,\n\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: 'invalid-argument' as FirestoreErrorCode,\n\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: 'deadline-exceeded' as FirestoreErrorCode,\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found' as FirestoreErrorCode,\n\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists' as FirestoreErrorCode,\n\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller can not be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: 'permission-denied' as FirestoreErrorCode,\n\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated' as FirestoreErrorCode,\n\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: 'resource-exhausted' as FirestoreErrorCode,\n\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: 'failed-precondition' as FirestoreErrorCode,\n\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: 'aborted' as FirestoreErrorCode,\n\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: 'out-of-range' as FirestoreErrorCode,\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented' as FirestoreErrorCode,\n\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: 'internal' as FirestoreErrorCode,\n\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: 'unavailable' as FirestoreErrorCode,\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss' as FirestoreErrorCode\n};\n\n/** An error returned by a Firestore operation. */\nexport class FirestoreError extends FirebaseError {\n /** The stack of the error. */\n readonly stack?: string;\n\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n readonly code: FirestoreErrorCode,\n /**\n * A custom error description.\n */\n readonly message: string\n ) {\n super(code, message);\n\n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Resolver {\n (value: R | Promise): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport class Deferred {\n promise: Promise;\n // Assigned synchronously in constructor by Promise constructor callback.\n resolve!: Resolver;\n reject!: Rejecter;\n\n constructor() {\n this.promise = new Promise((resolve: Resolver, reject: Rejecter) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\n/**\n * Takes an array of values and a function from a value to a Promise. The function is run on each\n * value sequentially, waiting for the previous promise to resolve before starting the next one.\n * The returned promise resolves once the function has been run on all values.\n */\nexport function sequence(\n values: T[],\n fn: (value: T) => Promise\n): Promise {\n let p = Promise.resolve();\n for (const value of values) {\n p = p.then(() => fn(value));\n }\n return p;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { User } from '../auth/user';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { Deferred } from '../util/promise';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\n/**\n * @internal\n */\nexport type AuthTokenFactory = () => string;\n\n/**\n * @internal\n */\nexport interface FirstPartyCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'firstParty';\n ['sessionIndex']: string;\n ['iamToken']: string | null;\n ['authTokenFactory']: AuthTokenFactory | null;\n}\n\nexport interface ProviderCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'provider';\n ['client']: CredentialsProvider;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n | FirstPartyCredentialsSettings\n | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';\nexport interface Token {\n /** Type of token. */\n type: TokenType;\n\n /**\n * The user with which the token is associated (used for persisting user\n * state on disk, etc.).\n * This will be null for Tokens of the type 'AppCheck'.\n */\n user?: User;\n\n /** Header values to set for this token */\n headers: Map;\n}\n\nexport class OAuthToken implements Token {\n type = 'OAuth' as TokenType;\n headers = new Map();\n\n constructor(value: string, public user: User) {\n this.headers.set('Authorization', `Bearer ${value}`);\n }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener = (credential: T) => Promise;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider {\n /**\n * Starts the credentials provider and specifies a listener to be notified of\n * credential changes (sign-in / sign-out, token changes). It is immediately\n * called once with the initial user.\n *\n * The change listener is invoked on the provided AsyncQueue.\n */\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void;\n\n /** Requests a token for the current user. */\n getToken(): Promise;\n\n /**\n * Marks the last retrieved token as invalid, making the next GetToken request\n * force-refresh the token.\n */\n invalidateToken(): void;\n\n shutdown(): void;\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */\nexport class EmptyAuthCredentialsProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(null);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));\n }\n\n shutdown(): void {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */\nexport class EmulatorAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(private token: Token) {}\n\n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n private changeListener: CredentialChangeListener | null = null;\n\n getToken(): Promise {\n return Promise.resolve(this.token);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n debugAssert(\n !this.changeListener,\n 'Can only call setChangeListener() once.'\n );\n this.changeListener = changeListener;\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(this.token.user!));\n }\n\n shutdown(): void {\n this.changeListener = null;\n }\n}\n\n/** Credential provider for the Lite SDK. */\nexport class LiteAuthCredentialsProvider implements CredentialsProvider {\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(authProvider: Provider) {\n authProvider.onInit(auth => {\n this.auth = auth;\n });\n }\n\n getToken(): Promise {\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken().then(tokenData => {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(\n tokenData.accessToken,\n new User(this.auth!.getUid())\n );\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n implements CredentialsProvider\n{\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener!: () => void;\n\n /** Tracks the current User. */\n private currentUser: User = User.UNAUTHENTICATED;\n\n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n private tokenCounter = 0;\n\n private forceRefresh = false;\n\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(private authProvider: Provider) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n let lastTokenId = this.tokenCounter;\n\n // A change listener that prevents double-firing for the same token change.\n const guardedChangeListener: (user: User) => Promise = user => {\n if (this.tokenCounter !== lastTokenId) {\n lastTokenId = this.tokenCounter;\n return changeListener(user);\n } else {\n return Promise.resolve();\n }\n };\n\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let nextToken = new Deferred();\n\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n nextToken.resolve();\n nextToken = new Deferred();\n asyncQueue.enqueueRetryable(() =>\n guardedChangeListener(this.currentUser)\n );\n };\n\n const awaitNextToken: () => void = () => {\n const currentTokenAttempt = nextToken;\n asyncQueue.enqueueRetryable(async () => {\n await currentTokenAttempt.promise;\n await guardedChangeListener(this.currentUser);\n });\n };\n\n const registerAuth = (auth: FirebaseAuthInternal): void => {\n logDebug('FirebaseAuthCredentialsProvider', 'Auth detected');\n this.auth = auth;\n this.auth.addAuthTokenListener(this.tokenListener);\n awaitNextToken();\n };\n\n this.authProvider.onInit(auth => registerAuth(auth));\n\n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout(() => {\n if (!this.auth) {\n const auth = this.authProvider.getImmediate({ optional: true });\n if (auth) {\n registerAuth(auth);\n } else {\n // If auth is still not available, proceed with `null` user\n logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected');\n nextToken.resolve();\n nextToken = new Deferred();\n }\n }\n }, 0);\n\n awaitNextToken();\n }\n\n getToken(): Promise {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAuthCredentialsProvider not started.'\n );\n\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const initialTokenCounter = this.tokenCounter;\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken(forceRefresh).then(tokenData => {\n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n if (this.tokenCounter !== initialTokenCounter) {\n logDebug(\n 'FirebaseAuthCredentialsProvider',\n 'getToken aborted due to token change.'\n );\n return this.getToken();\n } else {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(tokenData.accessToken, this.currentUser);\n } else {\n return null;\n }\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.auth) {\n this.auth.removeAuthTokenListener(this.tokenListener!);\n }\n }\n\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n private getUser(): User {\n const currentUid = this.auth && this.auth.getUid();\n hardAssert(\n currentUid === null || typeof currentUid === 'string',\n 'Received invalid UID: ' + currentUid\n );\n return new User(currentUid);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */\nexport class FirstPartyToken implements Token {\n type = 'FirstParty' as TokenType;\n user = User.FIRST_PARTY;\n private _headers = new Map();\n\n constructor(\n private readonly sessionIndex: string,\n private readonly iamToken: string | null,\n private readonly authTokenFactory: AuthTokenFactory | null\n ) {}\n\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */\n private getAuthToken(): string | null {\n if (this.authTokenFactory) {\n return this.authTokenFactory();\n } else {\n return null;\n }\n }\n\n get headers(): Map {\n this._headers.set('X-Goog-AuthUser', this.sessionIndex);\n // Use array notation to prevent minification\n const authHeaderTokenValue = this.getAuthToken();\n if (authHeaderTokenValue) {\n this._headers.set('Authorization', authHeaderTokenValue);\n }\n if (this.iamToken) {\n this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);\n }\n\n return this._headers;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nexport class FirstPartyAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(\n private sessionIndex: string,\n private iamToken: string | null,\n private authTokenFactory: AuthTokenFactory | null\n ) {}\n\n getToken(): Promise {\n return Promise.resolve(\n new FirstPartyToken(\n this.sessionIndex,\n this.iamToken,\n this.authTokenFactory\n )\n );\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial uid.\n asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));\n }\n\n shutdown(): void {}\n\n invalidateToken(): void {}\n}\n\nexport class AppCheckToken implements Token {\n type = 'AppCheck' as TokenType;\n headers = new Map();\n\n constructor(private value: string) {\n if (value && value.length > 0) {\n this.headers.set('x-firebase-appcheck', this.value);\n }\n }\n}\n\nexport class FirebaseAppCheckTokenProvider\n implements CredentialsProvider\n{\n /**\n * The AppCheck token listener registered with FirebaseApp, retained here so\n * we can unregister it.\n */\n private tokenListener!: AppCheckTokenListener;\n private forceRefresh = false;\n private appCheck: FirebaseAppCheckInternal | null = null;\n private latestAppCheckToken: string | null = null;\n\n constructor(\n private appCheckProvider: Provider\n ) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n const onTokenChanged: (\n tokenResult: AppCheckTokenResult\n ) => Promise = tokenResult => {\n if (tokenResult.error != null) {\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`\n );\n }\n const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;\n this.latestAppCheckToken = tokenResult.token;\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Received ${tokenUpdated ? 'new' : 'existing'} token.`\n );\n return tokenUpdated\n ? changeListener(tokenResult.token)\n : Promise.resolve();\n };\n\n this.tokenListener = (tokenResult: AppCheckTokenResult) => {\n asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));\n };\n\n const registerAppCheck = (appCheck: FirebaseAppCheckInternal): void => {\n logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected');\n this.appCheck = appCheck;\n this.appCheck.addTokenListener(this.tokenListener);\n };\n\n this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck));\n\n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout(() => {\n if (!this.appCheck) {\n const appCheck = this.appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n registerAppCheck(appCheck);\n } else {\n // If AppCheck is still not available, proceed without it.\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n 'AppCheck not yet detected'\n );\n }\n }\n }, 0);\n }\n\n getToken(): Promise {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAppCheckTokenProvider not started.'\n );\n\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken(forceRefresh).then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 'Invalid tokenResult returned from getToken():' + tokenResult\n );\n this.latestAppCheckToken = tokenResult.token;\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.appCheck) {\n this.appCheck.removeTokenListener(this.tokenListener!);\n }\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */\nexport class EmptyAppCheckTokenProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(new AppCheckToken(''));\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider {\n private appCheck: FirebaseAppCheckInternal | null = null;\n\n constructor(\n private appCheckProvider: Provider\n ) {\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken().then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 'Invalid tokenResult returned from getToken():' + tokenResult\n );\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeAuthCredentialsProvider(\n credentials?: CredentialsSettings\n): CredentialsProvider {\n if (!credentials) {\n return new EmptyAuthCredentialsProvider();\n }\n switch (credentials['type']) {\n case 'firstParty':\n return new FirstPartyAuthCredentialsProvider(\n credentials['sessionIndex'] || '0',\n credentials['iamToken'] || null,\n credentials['authTokenFactory'] || null\n );\n\n case 'provider':\n return credentials['client'];\n\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'makeAuthCredentialsProvider failed due to invalid credential type'\n );\n }\n}\n","import { FirebaseApp } from '@firebase/app';\n\nimport { ExperimentalLongPollingOptions } from '../api/long_polling_options';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class DatabaseInfo {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param longPollingOptions Options that configure long-polling.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(\n readonly databaseId: DatabaseId,\n readonly appId: string,\n readonly persistenceKey: string,\n readonly host: string,\n readonly ssl: boolean,\n readonly forceLongPolling: boolean,\n readonly autoDetectLongPolling: boolean,\n readonly longPollingOptions: ExperimentalLongPollingOptions,\n readonly useFetchStreams: boolean\n ) {}\n}\n\n/** The default database name for a project. */\nexport const DEFAULT_DATABASE_NAME = '(default)';\n\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nexport class DatabaseId {\n readonly database: string;\n constructor(readonly projectId: string, database?: string) {\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n\n static empty(): DatabaseId {\n return new DatabaseId('', '');\n }\n\n get isDefaultDatabase(): boolean {\n return this.database === DEFAULT_DATABASE_NAME;\n }\n\n isEqual(other: {}): boolean {\n return (\n other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database\n );\n }\n}\n\nexport function databaseIdFromApp(\n app: FirebaseApp,\n database?: string\n): DatabaseId {\n if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"projectId\" not provided in firebase.initializeApp.'\n );\n }\n\n return new DatabaseId(app.options.projectId!, database);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DOCUMENT_KEY_NAME = '__name__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath> {\n private segments: string[];\n private offset: number;\n private len: number;\n\n constructor(segments: string[], offset?: number, length?: number) {\n if (offset === undefined) {\n offset = 0;\n } else if (offset > segments.length) {\n fail('offset ' + offset + ' out of range ' + segments.length);\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail('length ' + length + ' out of range ' + (segments.length - offset));\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n }\n\n /**\n * Abstract constructor method to construct an instance of B with the given\n * parameters.\n */\n protected abstract construct(\n segments: string[],\n offset?: number,\n length?: number\n ): B;\n\n /**\n * Returns a String representation.\n *\n * Implementing classes are required to provide deterministic implementations as\n * the String representation is used to obtain canonical Query IDs.\n */\n abstract toString(): string;\n\n get length(): number {\n return this.len;\n }\n\n isEqual(other: B): boolean {\n return BasePath.comparator(this, other) === 0;\n }\n\n child(nameOrPath: string | B): B {\n const segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof BasePath) {\n nameOrPath.forEach(segment => {\n segments.push(segment);\n });\n } else {\n segments.push(nameOrPath);\n }\n return this.construct(segments);\n }\n\n /** The index of one past the last segment of the path. */\n private limit(): number {\n return this.offset + this.length;\n }\n\n popFirst(size?: number): B {\n size = size === undefined ? 1 : size;\n debugAssert(\n this.length >= size,\n \"Can't call popFirst() with less segments\"\n );\n return this.construct(\n this.segments,\n this.offset + size,\n this.length - size\n );\n }\n\n popLast(): B {\n debugAssert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n\n firstSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n }\n\n lastSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.get(this.length - 1);\n }\n\n get(index: number): string {\n debugAssert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n }\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n isPrefixOf(other: this): boolean {\n if (other.length < this.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n isImmediateParentOf(potentialChild: this): boolean {\n if (this.length + 1 !== potentialChild.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== potentialChild.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n forEach(fn: (segment: string) => void): void {\n for (let i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n }\n\n toArray(): string[] {\n return this.segments.slice(this.offset, this.limit());\n }\n\n static comparator>(\n p1: BasePath,\n p2: BasePath\n ): number {\n const len = Math.min(p1.length, p2.length);\n for (let i = 0; i < len; i++) {\n const left = p1.get(i);\n const right = p2.get(i);\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n }\n if (p1.length < p2.length) {\n return -1;\n }\n if (p1.length > p2.length) {\n return 1;\n }\n return 0;\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */\nexport class ResourcePath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): ResourcePath {\n return new ResourcePath(segments, offset, length);\n }\n\n canonicalString(): string {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n return this.toArray().join('/');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns a string representation of this path\n * where each path segment has been encoded with\n * `encodeURIComponent`.\n */\n toUriEncodedString(): string {\n return this.toArray().map(encodeURIComponent).join('/');\n }\n\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */\n static fromString(...pathComponents: string[]): ResourcePath {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n const segments: string[] = [];\n for (const path of pathComponents) {\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid segment (${path}). Paths must not contain // in them.`\n );\n }\n // Strip leading and traling slashed.\n segments.push(...path.split('/').filter(segment => segment.length > 0));\n }\n\n return new ResourcePath(segments);\n }\n\n static emptyPath(): ResourcePath {\n return new ResourcePath([]);\n }\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */\nexport class FieldPath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): FieldPath {\n return new FieldPath(segments, offset, length);\n }\n\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n private static isValidIdentifier(segment: string): boolean {\n return identifierRegExp.test(segment);\n }\n\n canonicalString(): string {\n return this.toArray()\n .map(str => {\n str = str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns true if this field references the key of a document.\n */\n isKeyField(): boolean {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n }\n\n /**\n * The field designating the key of a document.\n */\n static keyField(): FieldPath {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n }\n\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */\n static fromServerFormat(path: string): FieldPath {\n const segments: string[] = [];\n let current = '';\n let i = 0;\n\n const addCurrentSegment = (): void => {\n if (current.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, begin ` +\n `with '.', end with '.', or contain '..'`\n );\n }\n segments.push(current);\n current = '';\n };\n\n let inBackticks = false;\n\n while (i < path.length) {\n const c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has trailing escape character: ' + path\n );\n }\n const next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has invalid escape sequence: ' + path\n );\n }\n current += next;\n i += 2;\n } else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n } else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n } else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n\n if (inBackticks) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unterminated ` in path: ' + path\n );\n }\n\n return new FieldPath(segments);\n }\n\n static emptyPath(): FieldPath {\n return new FieldPath([]);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\n/**\n * @internal\n */\nexport class DocumentKey {\n constructor(readonly path: ResourcePath) {\n debugAssert(\n DocumentKey.isDocumentKey(path),\n 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/')\n );\n }\n\n static fromPath(path: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(path));\n }\n\n static fromName(name: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(name).popFirst(5));\n }\n\n static empty(): DocumentKey {\n return new DocumentKey(ResourcePath.emptyPath());\n }\n\n get collectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.popLast().lastSegment();\n }\n\n /** Returns true if the document is in the specified collectionId. */\n hasCollectionId(collectionId: string): boolean {\n return (\n this.path.length >= 2 &&\n this.path.get(this.path.length - 2) === collectionId\n );\n }\n\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */\n getCollectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.get(this.path.length - 2);\n }\n\n /** Returns the fully qualified path to the parent collection. */\n getCollectionPath(): ResourcePath {\n return this.path.popLast();\n }\n\n isEqual(other: DocumentKey | null): boolean {\n return (\n other !== null && ResourcePath.comparator(this.path, other.path) === 0\n );\n }\n\n toString(): string {\n return this.path.toString();\n }\n\n static comparator(k1: DocumentKey, k2: DocumentKey): number {\n return ResourcePath.comparator(k1.path, k2.path);\n }\n\n static isDocumentKey(path: ResourcePath): boolean {\n return path.length % 2 === 0;\n }\n\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */\n static fromSegments(segments: string[]): DocumentKey {\n return new DocumentKey(new ResourcePath(segments.slice()));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\n\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\n\n/** Types accepted by validateType() and related methods for validation. */\nexport type ValidationType =\n | 'undefined'\n | 'object'\n | 'function'\n | 'boolean'\n | 'number'\n | 'string'\n | 'non-empty string';\n\nexport function validateNonEmptyArgument(\n functionName: string,\n argumentName: string,\n argument?: string\n): asserts argument is string {\n if (!argument) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() cannot be called with an empty ${argumentName}.`\n );\n }\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */\nexport function validateIsNotUsedTogether(\n optionName1: string,\n argument1: boolean | undefined,\n optionName2: string,\n argument2: boolean | undefined\n): void {\n if (argument1 === true && argument2 === true) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `${optionName1} and ${optionName2} cannot be used together.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */\nexport function validateDocumentPath(path: ResourcePath): void {\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */\nexport function validateCollectionPath(path: ResourcePath): void {\n if (DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n (Object.getPrototypeOf(input) === Object.prototype ||\n Object.getPrototypeOf(input) === null)\n );\n}\n\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input: unknown): string {\n if (input === undefined) {\n return 'undefined';\n } else if (input === null) {\n return 'null';\n } else if (typeof input === 'string') {\n if (input.length > 20) {\n input = `${input.substring(0, 20)}...`;\n }\n return JSON.stringify(input);\n } else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n } else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n } else {\n const customObjectName = tryGetCustomObjectType(input!);\n if (customObjectName) {\n return `a custom ${customObjectName} object`;\n } else {\n return 'an object';\n }\n }\n } else if (typeof input === 'function') {\n return 'a function';\n } else {\n return fail('Unknown wrong type: ' + typeof input);\n }\n}\n\n/** try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n if (input.constructor) {\n return input.constructor.name;\n }\n return null;\n}\n\n/**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */\nexport function cast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n if ('_delegate' in obj) {\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj = (obj as any)._delegate;\n }\n\n if (!(obj instanceof constructor)) {\n if (constructor.name === obj.constructor.name) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Type does not match the expected instance. Did you pass a ' +\n `reference from a different Firestore SDK?`\n );\n } else {\n const description = valueDescription(obj);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected type '${constructor.name}', but it was: ${description}`\n );\n }\n }\n return obj as T;\n}\n\nexport function validatePositiveNumber(functionName: string, n: number): void {\n if (n <= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires a positive number, but it was: ${n}.`\n );\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Options that configure the SDK’s underlying network transport (WebChannel)\n * when long-polling is used.\n *\n * Note: This interface is \"experimental\" and is subject to change.\n *\n * See `FirestoreSettings.experimentalAutoDetectLongPolling`,\n * `FirestoreSettings.experimentalForceLongPolling`, and\n * `FirestoreSettings.experimentalLongPollingOptions`.\n */\nexport interface ExperimentalLongPollingOptions {\n /**\n * The desired maximum timeout interval, in seconds, to complete a\n * long-polling GET response. Valid values are between 5 and 30, inclusive.\n * Floating point values are allowed and will be rounded to the nearest\n * millisecond.\n *\n * By default, when long-polling is used the \"hanging GET\" request sent by\n * the client times out after 30 seconds. To request a different timeout\n * from the server, set this setting with the desired timeout.\n *\n * Changing the default timeout may be useful, for example, if the buffering\n * proxy that necessitated enabling long-polling in the first place has a\n * shorter timeout for hanging GET requests, in which case setting the\n * long-polling timeout to a shorter value, such as 25 seconds, may fix\n * prematurely-closed hanging GET requests.\n * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.\n */\n timeoutSeconds?: number;\n}\n\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\nexport function longPollingOptionsEqual(\n options1: ExperimentalLongPollingOptions,\n options2: ExperimentalLongPollingOptions\n): boolean {\n return options1.timeoutSeconds === options2.timeoutSeconds;\n}\n\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nexport function cloneLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): ExperimentalLongPollingOptions {\n const clone: ExperimentalLongPollingOptions = {};\n\n if (options.timeoutSeconds !== undefined) {\n clone.timeoutSeconds = options.timeoutSeconds;\n }\n\n return clone;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */\nlet lastUniqueDebugId: number | null = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\nfunction generateInitialUniqueDebugId(): number {\n const minResult = 0x10000000;\n const maxResult = 0x90000000;\n const resultRange = maxResult - minResult;\n const resultOffset = Math.round(resultRange * Math.random());\n return minResult + resultOffset;\n}\n\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nexport function generateUniqueDebugId(): string {\n if (lastUniqueDebugId === null) {\n lastUniqueDebugId = generateInitialUniqueDebugId();\n } else {\n lastUniqueDebugId++;\n }\n return '0x' + lastUniqueDebugId.toString(16);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === 0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../../src/core/version';\nimport { Token } from '../api/credentials';\nimport {\n DatabaseId,\n DatabaseInfo,\n DEFAULT_DATABASE_NAME\n} from '../core/database_info';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { generateUniqueDebugId } from '../util/debug_uid';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { StringMap } from '../util/types';\n\nimport { Connection, Stream } from './connection';\n\nconst LOG_TAG = 'RestConnection';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\nconst RPC_NAME_URL_MAPPING: StringMap = {};\n\nRPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_URL_MAPPING['Commit'] = 'commit';\nRPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';\nRPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';\n\nconst RPC_URL_VERSION = 'v1';\n\n// SDK_VERSION is updated to different value at runtime depending on the entry point,\n// so we need to get its value when we need it in a function.\nfunction getGoogApiClientValue(): string {\n return 'gl-js/ fire/' + SDK_VERSION;\n}\n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nexport abstract class RestConnection implements Connection {\n protected readonly databaseId: DatabaseId;\n protected readonly baseUrl: string;\n private readonly databasePath: string;\n private readonly requestParams: string;\n\n get shouldResourcePathBeIncludedInRequest(): boolean {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return false;\n }\n\n constructor(private readonly databaseInfo: DatabaseInfo) {\n this.databaseId = databaseInfo.databaseId;\n const proto = databaseInfo.ssl ? 'https' : 'http';\n const projectId = encodeURIComponent(this.databaseId.projectId);\n const databaseId = encodeURIComponent(this.databaseId.database);\n this.baseUrl = proto + '://' + databaseInfo.host;\n this.databasePath = `projects/${projectId}/databases/${databaseId}`;\n this.requestParams =\n this.databaseId.database === DEFAULT_DATABASE_NAME\n ? `project_id=${projectId}`\n : `project_id=${projectId}&database_id=${databaseId}`;\n }\n\n invokeRPC(\n rpcName: string,\n path: ResourcePath,\n req: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise {\n const streamId = generateUniqueDebugId();\n const url = this.makeUrl(rpcName, path.toUriEncodedString());\n logDebug(LOG_TAG, `Sending RPC '${rpcName}' ${streamId}:`, url, req);\n\n const headers: StringMap = {\n 'google-cloud-resource-prefix': this.databasePath,\n 'x-goog-request-params': this.requestParams\n };\n this.modifyHeadersForRequest(headers, authToken, appCheckToken);\n\n return this.performRPCRequest(rpcName, url, headers, req).then(\n response => {\n logDebug(LOG_TAG, `Received RPC '${rpcName}' ${streamId}: `, response);\n return response;\n },\n (err: FirestoreError) => {\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error: `,\n err,\n 'url: ',\n url,\n 'request:',\n req\n );\n throw err;\n }\n );\n }\n\n invokeStreamingRPC(\n rpcName: string,\n path: ResourcePath,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null,\n expectedResponseCount?: number\n ): Promise {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n }\n\n abstract openStream(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream;\n\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n protected modifyHeadersForRequest(\n headers: StringMap,\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n headers['X-Goog-Api-Client'] = getGoogApiClientValue();\n\n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n headers['Content-Type'] = 'text/plain';\n\n if (this.databaseInfo.appId) {\n headers['X-Firebase-GMPID'] = this.databaseInfo.appId;\n }\n\n if (authToken) {\n authToken.headers.forEach((value, key) => (headers[key] = value));\n }\n if (appCheckToken) {\n appCheckToken.headers.forEach((value, key) => (headers[key] = value));\n }\n }\n\n /**\n * Performs an RPC request using an implementation specific networking layer.\n */\n protected abstract performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise;\n\n private makeUrl(rpcName: string, path: string): string {\n const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];\n debugAssert(\n urlRpcName !== undefined,\n 'Unknown REST mapping for: ' + rpcName\n );\n return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;\n }\n\n /**\n * Closes and cleans up any resources associated with the connection. This\n * implementation is a no-op because there are no resources associated\n * with the RestConnection that need to be cleaned up.\n */\n terminate(): void {\n // No-op\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport { logError } from '../util/log';\n\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */\nenum RpcCode {\n OK = 0,\n CANCELLED = 1,\n UNKNOWN = 2,\n INVALID_ARGUMENT = 3,\n DEADLINE_EXCEEDED = 4,\n NOT_FOUND = 5,\n ALREADY_EXISTS = 6,\n PERMISSION_DENIED = 7,\n UNAUTHENTICATED = 16,\n RESOURCE_EXHAUSTED = 8,\n FAILED_PRECONDITION = 9,\n ABORTED = 10,\n OUT_OF_RANGE = 11,\n UNIMPLEMENTED = 12,\n INTERNAL = 13,\n UNAVAILABLE = 14,\n DATA_LOSS = 15\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nexport function isPermanentError(code: Code): boolean {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\nexport function isPermanentWriteError(code: Code): boolean {\n return isPermanentError(code) && code !== Code.ABORTED;\n}\n\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const code: RpcCode = RpcCode[status as any] as any;\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\n\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n if (code === undefined) {\n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n logError('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code: Code | undefined): number {\n if (code === undefined) {\n return RpcCode.OK;\n }\n\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status - An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status?: number): Code {\n if (status === undefined) {\n logError('RPC_ERROR', 'HTTP error has no status');\n return Code.UNKNOWN;\n }\n\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200: // OK\n return Code.OK;\n\n case 400: // Bad Request\n return Code.FAILED_PRECONDITION;\n // Other possibilities based on the forward mapping\n // return Code.INVALID_ARGUMENT;\n // return Code.OUT_OF_RANGE;\n\n case 401: // Unauthorized\n return Code.UNAUTHENTICATED;\n\n case 403: // Forbidden\n return Code.PERMISSION_DENIED;\n\n case 404: // Not Found\n return Code.NOT_FOUND;\n\n case 409: // Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n\n case 416: // Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n\n case 429: // Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n\n case 499: // Client Closed Request\n return Code.CANCELLED;\n\n case 500: // Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n\n case 501: // Unimplemented\n return Code.UNIMPLEMENTED;\n\n case 503: // Service Unavailable\n return Code.UNAVAILABLE;\n\n case 504: // Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n\n default:\n if (status >= 200 && status < 300) {\n return Code.OK;\n }\n if (status >= 400 && status < 500) {\n return Code.FAILED_PRECONDITION;\n }\n if (status >= 500 && status < 600) {\n return Code.INTERNAL;\n }\n return Code.UNKNOWN;\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpResponseErrorStatus(status: string): Code {\n const serverError = status.toLowerCase().replace(/_/g, '-');\n return Object.values(Code).indexOf(serverError as Code) >= 0\n ? (serverError as Code)\n : Code.UNKNOWN;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Token } from '../../api/credentials';\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport { mapCodeFromHttpStatus } from '../../remote/rpc_error';\nimport { FirestoreError } from '../../util/error';\nimport { StringMap } from '../../util/types';\n\n/**\n * A Rest-based connection that relies on the native HTTP stack\n * (e.g. `fetch` or a polyfill).\n */\nexport class FetchConnection extends RestConnection {\n /**\n * @param databaseInfo - The connection info.\n * @param fetchImpl - `fetch` or a Polyfill that implements the fetch API.\n */\n constructor(\n databaseInfo: DatabaseInfo,\n private readonly fetchImpl: typeof fetch\n ) {\n super(databaseInfo);\n }\n\n openStream(\n rpcName: string,\n token: Token | null\n ): Stream {\n throw new Error('Not supported by FetchConnection');\n }\n\n protected async performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise {\n const requestJson = JSON.stringify(body);\n let response: Response;\n\n try {\n response = await this.fetchImpl(url, {\n method: 'POST',\n headers,\n body: requestJson\n });\n } catch (e) {\n const err = e as { status: number | undefined; statusText: string };\n throw new FirestoreError(\n mapCodeFromHttpStatus(err.status),\n 'Request failed with error: ' + err.statusText\n );\n }\n\n if (!response.ok) {\n let errorResponse = await response.json();\n if (Array.isArray(errorResponse)) {\n errorResponse = errorResponse[0];\n }\n const errorMessage = errorResponse?.error?.message;\n throw new FirestoreError(\n mapCodeFromHttpStatus(response.status),\n `Request failed with error: ${errorMessage ?? response.statusText}`\n );\n }\n\n return response.json();\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: FieldPath\n ) {}\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../../util/assert';\n\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nexport function randomBytes(nBytes: number): Uint8Array {\n debugAssert(nBytes >= 0, `Expecting non-negative nBytes, got: ${nBytes}`);\n\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const crypto =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof self !== 'undefined' && (self.crypto || (self as any)['msCrypto']);\n const bytes = new Uint8Array(nBytes);\n if (crypto && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n // Falls back to Math.random\n for (let i = 0; i < nBytes; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return bytes;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes } from '../platform/random_bytes';\n\nimport { debugAssert } from './assert';\n\nexport type EventHandler = (value: E) => void;\nexport interface Indexable {\n [k: string]: unknown;\n}\n\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */\nexport class AutoId {\n static newId(): string {\n // Alphanumeric characters\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n // The largest byte value that is a multiple of `char.length`.\n const maxMultiple = Math.floor(256 / chars.length) * chars.length;\n debugAssert(\n 0 < maxMultiple && maxMultiple < 256,\n `Expect maxMultiple to be (0, 256), but got ${maxMultiple}`\n );\n\n let autoId = '';\n const targetLength = 20;\n while (autoId.length < targetLength) {\n const bytes = randomBytes(40);\n for (let i = 0; i < bytes.length; ++i) {\n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n if (autoId.length < targetLength && bytes[i] < maxMultiple) {\n autoId += chars.charAt(bytes[i] % chars.length);\n }\n }\n }\n debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);\n\n return autoId;\n }\n}\n\nexport function primitiveComparator(left: T, right: T): number {\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n return 0;\n}\n\nexport interface Equatable {\n isEqual(other: T): boolean;\n}\n\nexport interface Iterable {\n forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals(\n left: T[],\n right: T[],\n comparator: (l: T, r: T) => boolean\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => comparator(value, right[index]));\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s: string): string {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\n [stringKey: string]: V;\n}\n\nexport function objectSize(obj: object): number {\n let count = 0;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n\nexport function forEach(\n obj: Dict | undefined,\n fn: (key: string, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\nexport function mapToArray(\n obj: Dict,\n fn: (element: V, key: string, obj: Dict) => R\n): R[] {\n const result: R[] = [];\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result.push(fn(obj[key], key, obj));\n }\n }\n return result;\n}\n\nexport function isEmpty(obj: Dict): boolean {\n debugAssert(\n obj != null && typeof obj === 'object',\n 'isEmpty() expects object parameter.'\n );\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class Base64DecodeError extends Error {\n readonly name = 'Base64DecodeError';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { decodeBase64, encodeBase64 } from '../platform/base64';\n\nimport { primitiveComparator } from './misc';\n\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */\nexport class ByteString {\n static readonly EMPTY_BYTE_STRING = new ByteString('');\n\n private constructor(private readonly binaryString: string) {}\n\n static fromBase64String(base64: string): ByteString {\n const binaryString = decodeBase64(base64);\n return new ByteString(binaryString);\n }\n\n static fromUint8Array(array: Uint8Array): ByteString {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const binaryString = binaryStringFromUint8Array(array);\n return new ByteString(binaryString);\n }\n\n [Symbol.iterator](): Iterator {\n let i = 0;\n return {\n next: () => {\n if (i < this.binaryString.length) {\n return { value: this.binaryString.charCodeAt(i++), done: false };\n } else {\n return { value: undefined, done: true };\n }\n }\n };\n }\n\n toBase64(): string {\n return encodeBase64(this.binaryString);\n }\n\n toUint8Array(): Uint8Array {\n return uint8ArrayFromBinaryString(this.binaryString);\n }\n\n approximateByteSize(): number {\n return this.binaryString.length * 2;\n }\n\n compareTo(other: ByteString): number {\n return primitiveComparator(this.binaryString, other.binaryString);\n }\n\n isEqual(other: ByteString): boolean {\n return this.binaryString === other.binaryString;\n }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n let binaryString = '';\n for (let i = 0; i < array.length; ++i) {\n binaryString += String.fromCharCode(array[i]);\n }\n return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n const buffer = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n buffer[i] = binaryString.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Base64DecodeError } from '../../util/base64_decode_error';\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n try {\n return atob(encoded);\n } catch (e) {\n // Check that `DOMException` is defined before using it to avoid\n // \"ReferenceError: Property 'DOMException' doesn't exist\" in react-native.\n // (https://github.com/firebase/firebase-js-sdk/issues/7115)\n if (typeof DOMException !== 'undefined' && e instanceof DOMException) {\n throw new Base64DecodeError('Invalid base64 string: ' + e);\n } else {\n throw e;\n }\n }\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return btoa(raw);\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return typeof atob !== 'undefined';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../protos/firestore_proto_api';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_TIMESTAMP_REG_EXP = new RegExp(\n /^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/\n);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */\nexport function normalizeTimestamp(date: Timestamp): {\n seconds: number;\n nanos: number;\n} {\n hardAssert(!!date, 'Cannot normalize null or undefined timestamp.');\n\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (typeof date === 'string') {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n\n // Parse the nanos right out of the string.\n let nanos = 0;\n const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);\n hardAssert(!!fraction, 'invalid timestamp: ' + date);\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n\n // Parse the date to get the seconds.\n const parsedDate = new Date(date);\n const seconds = Math.floor(parsedDate.getTime() / 1000);\n\n return { seconds, nanos };\n } else {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n const seconds = normalizeNumber(date.seconds);\n const nanos = normalizeNumber(date.nanos);\n return { seconds, nanos };\n }\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */\nexport function normalizeNumber(value: number | string | undefined): number {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n } else if (typeof value === 'string') {\n return Number(value);\n } else {\n return 0;\n }\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */\nexport function normalizeByteString(blob: string | Uint8Array): ByteString {\n if (typeof blob === 'string') {\n return ByteString.fromBase64String(blob);\n } else {\n return ByteString.fromUint8Array(blob);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\nconst MIN_SECONDS = -62135596800;\n\n// Number of nanoseconds in a millisecond.\nconst MS_TO_NANOS = 1e6;\n\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nexport class Timestamp {\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */\n static now(): Timestamp {\n return Timestamp.fromMillis(Date.now());\n }\n\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */\n static fromDate(date: Date): Timestamp {\n return Timestamp.fromMillis(date.getTime());\n }\n\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */\n static fromMillis(milliseconds: number): Timestamp {\n const seconds = Math.floor(milliseconds / 1000);\n const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);\n return new Timestamp(seconds, nanos);\n }\n\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n readonly seconds: number,\n /**\n * The fractions of a second at nanosecond resolution.*\n */\n readonly nanoseconds: number\n ) {\n if (nanoseconds < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (seconds < MIN_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n // This will break in the year 10,000.\n if (seconds >= 253402300800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n }\n\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */\n toDate(): Date {\n return new Date(this.toMillis());\n }\n\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */\n toMillis(): number {\n return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;\n }\n\n _compareTo(other: Timestamp): number {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\n }\n return primitiveComparator(this.seconds, other.seconds);\n }\n\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */\n isEqual(other: Timestamp): boolean {\n return (\n other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n );\n }\n\n /** Returns a textual representation of this `Timestamp`. */\n toString(): string {\n return (\n 'Timestamp(seconds=' +\n this.seconds +\n ', nanoseconds=' +\n this.nanoseconds +\n ')'\n );\n }\n\n /** Returns a JSON-serializable representation of this `Timestamp`. */\n toJSON(): { seconds: number; nanoseconds: number } {\n return { seconds: this.seconds, nanoseconds: this.nanoseconds };\n }\n\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */\n valueOf(): string {\n // This method returns a string of the form . where\n // is translated to have a non-negative value and both \n // and are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexiographical ordering that matches\n // the expected ordering. The translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexiographical ordering.\n const adjustedSeconds = this.seconds - MIN_SECONDS;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n const formattedSeconds = String(adjustedSeconds).padStart(12, '0');\n const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');\n return formattedSeconds + '.' + formattedNanoseconds;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n Value as ProtoValue,\n MapValue as ProtoMapValue\n} from '../protos/firestore_proto_api';\n\nimport { normalizeTimestamp } from './normalize';\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\n\nconst SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';\nconst TYPE_KEY = '__type__';\nconst PREVIOUS_VALUE_KEY = '__previous_value__';\nconst LOCAL_WRITE_TIME_KEY = '__local_write_time__';\n\nexport function isServerTimestamp(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === SERVER_TIMESTAMP_SENTINEL;\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\nexport function serverTimestamp(\n localWriteTime: Timestamp,\n previousValue: ProtoValue | null\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: SERVER_TIMESTAMP_SENTINEL\n },\n [LOCAL_WRITE_TIME_KEY]: {\n timestampValue: {\n seconds: localWriteTime.seconds,\n nanos: localWriteTime.nanoseconds\n }\n }\n }\n };\n\n // We should avoid storing deeply nested server timestamp map values\n // because we never use the intermediate \"previous values\".\n // For example:\n // previous: 42L, add: t1, result: t1 -> 42L\n // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n // `getPreviousValue` recursively traverses server timestamps to find the\n // least recent Value.\n if (previousValue && isServerTimestamp(previousValue)) {\n previousValue = getPreviousValue(previousValue);\n }\n if (previousValue) {\n mapValue.fields![PREVIOUS_VALUE_KEY] = previousValue;\n }\n\n return { mapValue };\n}\n\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nexport function getPreviousValue(value: ProtoValue): ProtoValue | null {\n const previousValue = value.mapValue!.fields![PREVIOUS_VALUE_KEY];\n\n if (isServerTimestamp(previousValue)) {\n return getPreviousValue(previousValue);\n }\n return previousValue;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */\nexport function getLocalWriteTime(value: ProtoValue): Timestamp {\n const localWriteTime = normalizeTimestamp(\n value.mapValue!.fields![LOCAL_WRITE_TIME_KEY].timestampValue!\n );\n return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport {\n ArrayValue,\n LatLng,\n MapValue,\n Timestamp,\n Value\n} from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport { arrayEquals, primitiveComparator } from '../util/misc';\nimport { forEach, objectSize } from '../util/obj';\nimport { isNegativeZero } from '../util/types';\n\nimport { DocumentKey } from './document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from './normalize';\nimport {\n getLocalWriteTime,\n getPreviousValue,\n isServerTimestamp\n} from './server_timestamps';\nimport { TypeOrder } from './type_order';\n\nconst MAX_VALUE_TYPE = '__max__';\nexport const MAX_VALUE: Value = {\n mapValue: {\n fields: {\n '__type__': { stringValue: MAX_VALUE_TYPE }\n }\n }\n};\n\nexport const MIN_VALUE: Value = {\n nullValue: 'NULL_VALUE'\n};\n\n/** Extracts the backend's type order for the provided value. */\nexport function typeOrder(value: Value): TypeOrder {\n if ('nullValue' in value) {\n return TypeOrder.NullValue;\n } else if ('booleanValue' in value) {\n return TypeOrder.BooleanValue;\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return TypeOrder.NumberValue;\n } else if ('timestampValue' in value) {\n return TypeOrder.TimestampValue;\n } else if ('stringValue' in value) {\n return TypeOrder.StringValue;\n } else if ('bytesValue' in value) {\n return TypeOrder.BlobValue;\n } else if ('referenceValue' in value) {\n return TypeOrder.RefValue;\n } else if ('geoPointValue' in value) {\n return TypeOrder.GeoPointValue;\n } else if ('arrayValue' in value) {\n return TypeOrder.ArrayValue;\n } else if ('mapValue' in value) {\n if (isServerTimestamp(value)) {\n return TypeOrder.ServerTimestampValue;\n } else if (isMaxValue(value)) {\n return TypeOrder.MaxValue;\n }\n return TypeOrder.ObjectValue;\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */\nexport function valueEquals(left: Value, right: Value): boolean {\n if (left === right) {\n return true;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n if (leftType !== rightType) {\n return false;\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n return true;\n case TypeOrder.BooleanValue:\n return left.booleanValue === right.booleanValue;\n case TypeOrder.ServerTimestampValue:\n return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));\n case TypeOrder.TimestampValue:\n return timestampEquals(left, right);\n case TypeOrder.StringValue:\n return left.stringValue === right.stringValue;\n case TypeOrder.BlobValue:\n return blobEquals(left, right);\n case TypeOrder.RefValue:\n return left.referenceValue === right.referenceValue;\n case TypeOrder.GeoPointValue:\n return geoPointEquals(left, right);\n case TypeOrder.NumberValue:\n return numberEquals(left, right);\n case TypeOrder.ArrayValue:\n return arrayEquals(\n left.arrayValue!.values || [],\n right.arrayValue!.values || [],\n valueEquals\n );\n case TypeOrder.ObjectValue:\n return objectEquals(left, right);\n case TypeOrder.MaxValue:\n return true;\n default:\n return fail('Unexpected value type: ' + JSON.stringify(left));\n }\n}\n\nfunction timestampEquals(left: Value, right: Value): boolean {\n if (\n typeof left.timestampValue === 'string' &&\n typeof right.timestampValue === 'string' &&\n left.timestampValue.length === right.timestampValue.length\n ) {\n // Use string equality for ISO 8601 timestamps\n return left.timestampValue === right.timestampValue;\n }\n\n const leftTimestamp = normalizeTimestamp(left.timestampValue!);\n const rightTimestamp = normalizeTimestamp(right.timestampValue!);\n return (\n leftTimestamp.seconds === rightTimestamp.seconds &&\n leftTimestamp.nanos === rightTimestamp.nanos\n );\n}\n\nfunction geoPointEquals(left: Value, right: Value): boolean {\n return (\n normalizeNumber(left.geoPointValue!.latitude) ===\n normalizeNumber(right.geoPointValue!.latitude) &&\n normalizeNumber(left.geoPointValue!.longitude) ===\n normalizeNumber(right.geoPointValue!.longitude)\n );\n}\n\nfunction blobEquals(left: Value, right: Value): boolean {\n return normalizeByteString(left.bytesValue!).isEqual(\n normalizeByteString(right.bytesValue!)\n );\n}\n\nexport function numberEquals(left: Value, right: Value): boolean {\n if ('integerValue' in left && 'integerValue' in right) {\n return (\n normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)\n );\n } else if ('doubleValue' in left && 'doubleValue' in right) {\n const n1 = normalizeNumber(left.doubleValue!);\n const n2 = normalizeNumber(right.doubleValue!);\n\n if (n1 === n2) {\n return isNegativeZero(n1) === isNegativeZero(n2);\n } else {\n return isNaN(n1) && isNaN(n2);\n }\n }\n\n return false;\n}\n\nfunction objectEquals(left: Value, right: Value): boolean {\n const leftMap = left.mapValue!.fields || {};\n const rightMap = right.mapValue!.fields || {};\n\n if (objectSize(leftMap) !== objectSize(rightMap)) {\n return false;\n }\n\n for (const key in leftMap) {\n if (leftMap.hasOwnProperty(key)) {\n if (\n rightMap[key] === undefined ||\n !valueEquals(leftMap[key], rightMap[key])\n ) {\n return false;\n }\n }\n }\n return true;\n}\n\n/** Returns true if the ArrayValue contains the specified element. */\nexport function arrayValueContains(\n haystack: ArrayValue,\n needle: Value\n): boolean {\n return (\n (haystack.values || []).find(v => valueEquals(v, needle)) !== undefined\n );\n}\n\nexport function valueCompare(left: Value, right: Value): number {\n if (left === right) {\n return 0;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n\n if (leftType !== rightType) {\n return primitiveComparator(leftType, rightType);\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n case TypeOrder.MaxValue:\n return 0;\n case TypeOrder.BooleanValue:\n return primitiveComparator(left.booleanValue!, right.booleanValue!);\n case TypeOrder.NumberValue:\n return compareNumbers(left, right);\n case TypeOrder.TimestampValue:\n return compareTimestamps(left.timestampValue!, right.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return compareTimestamps(\n getLocalWriteTime(left),\n getLocalWriteTime(right)\n );\n case TypeOrder.StringValue:\n return primitiveComparator(left.stringValue!, right.stringValue!);\n case TypeOrder.BlobValue:\n return compareBlobs(left.bytesValue!, right.bytesValue!);\n case TypeOrder.RefValue:\n return compareReferences(left.referenceValue!, right.referenceValue!);\n case TypeOrder.GeoPointValue:\n return compareGeoPoints(left.geoPointValue!, right.geoPointValue!);\n case TypeOrder.ArrayValue:\n return compareArrays(left.arrayValue!, right.arrayValue!);\n case TypeOrder.ObjectValue:\n return compareMaps(left.mapValue!, right.mapValue!);\n default:\n throw fail('Invalid value type: ' + leftType);\n }\n}\n\nfunction compareNumbers(left: Value, right: Value): number {\n const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);\n const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);\n\n if (leftNumber < rightNumber) {\n return -1;\n } else if (leftNumber > rightNumber) {\n return 1;\n } else if (leftNumber === rightNumber) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(leftNumber)) {\n return isNaN(rightNumber) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n\nfunction compareTimestamps(left: Timestamp, right: Timestamp): number {\n if (\n typeof left === 'string' &&\n typeof right === 'string' &&\n left.length === right.length\n ) {\n return primitiveComparator(left, right);\n }\n\n const leftTimestamp = normalizeTimestamp(left);\n const rightTimestamp = normalizeTimestamp(right);\n\n const comparison = primitiveComparator(\n leftTimestamp.seconds,\n rightTimestamp.seconds\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);\n}\n\nfunction compareReferences(leftPath: string, rightPath: string): number {\n const leftSegments = leftPath.split('/');\n const rightSegments = rightPath.split('/');\n for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {\n const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(leftSegments.length, rightSegments.length);\n}\n\nfunction compareGeoPoints(left: LatLng, right: LatLng): number {\n const comparison = primitiveComparator(\n normalizeNumber(left.latitude),\n normalizeNumber(right.latitude)\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(\n normalizeNumber(left.longitude),\n normalizeNumber(right.longitude)\n );\n}\n\nfunction compareBlobs(\n left: string | Uint8Array,\n right: string | Uint8Array\n): number {\n const leftBytes = normalizeByteString(left);\n const rightBytes = normalizeByteString(right);\n return leftBytes.compareTo(rightBytes);\n}\n\nfunction compareArrays(left: ArrayValue, right: ArrayValue): number {\n const leftArray = left.values || [];\n const rightArray = right.values || [];\n\n for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {\n const compare = valueCompare(leftArray[i], rightArray[i]);\n if (compare) {\n return compare;\n }\n }\n return primitiveComparator(leftArray.length, rightArray.length);\n}\n\nfunction compareMaps(left: MapValue, right: MapValue): number {\n if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {\n return 0;\n } else if (left === MAX_VALUE.mapValue) {\n return 1;\n } else if (right === MAX_VALUE.mapValue) {\n return -1;\n }\n\n const leftMap = left.fields || {};\n const leftKeys = Object.keys(leftMap);\n const rightMap = right.fields || {};\n const rightKeys = Object.keys(rightMap);\n\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n leftKeys.sort();\n rightKeys.sort();\n\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {\n const keyCompare = primitiveComparator(leftKeys[i], rightKeys[i]);\n if (keyCompare !== 0) {\n return keyCompare;\n }\n const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);\n if (compare !== 0) {\n return compare;\n }\n }\n\n return primitiveComparator(leftKeys.length, rightKeys.length);\n}\n\n/**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */\nexport function canonicalId(value: Value): string {\n return canonifyValue(value);\n}\n\nfunction canonifyValue(value: Value): string {\n if ('nullValue' in value) {\n return 'null';\n } else if ('booleanValue' in value) {\n return '' + value.booleanValue!;\n } else if ('integerValue' in value) {\n return '' + value.integerValue!;\n } else if ('doubleValue' in value) {\n return '' + value.doubleValue!;\n } else if ('timestampValue' in value) {\n return canonifyTimestamp(value.timestampValue!);\n } else if ('stringValue' in value) {\n return value.stringValue!;\n } else if ('bytesValue' in value) {\n return canonifyByteString(value.bytesValue!);\n } else if ('referenceValue' in value) {\n return canonifyReference(value.referenceValue!);\n } else if ('geoPointValue' in value) {\n return canonifyGeoPoint(value.geoPointValue!);\n } else if ('arrayValue' in value) {\n return canonifyArray(value.arrayValue!);\n } else if ('mapValue' in value) {\n return canonifyMap(value.mapValue!);\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nfunction canonifyByteString(byteString: string | Uint8Array): string {\n return normalizeByteString(byteString).toBase64();\n}\n\nfunction canonifyTimestamp(timestamp: Timestamp): string {\n const normalizedTimestamp = normalizeTimestamp(timestamp);\n return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`;\n}\n\nfunction canonifyGeoPoint(geoPoint: LatLng): string {\n return `geo(${geoPoint.latitude},${geoPoint.longitude})`;\n}\n\nfunction canonifyReference(referenceValue: string): string {\n return DocumentKey.fromName(referenceValue).toString();\n}\n\nfunction canonifyMap(mapValue: MapValue): string {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const sortedKeys = Object.keys(mapValue.fields || {}).sort();\n\n let result = '{';\n let first = true;\n for (const key of sortedKeys) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += `${key}:${canonifyValue(mapValue.fields![key])}`;\n }\n return result + '}';\n}\n\nfunction canonifyArray(arrayValue: ArrayValue): string {\n let result = '[';\n let first = true;\n for (const value of arrayValue.values || []) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += canonifyValue(value);\n }\n return result + ']';\n}\n\n/**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */\nexport function estimateByteSize(value: Value): number {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return 4;\n case TypeOrder.BooleanValue:\n return 4;\n case TypeOrder.NumberValue:\n return 8;\n case TypeOrder.TimestampValue:\n // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n return 16;\n case TypeOrder.ServerTimestampValue:\n const previousValue = getPreviousValue(value);\n return previousValue ? 16 + estimateByteSize(previousValue) : 16;\n case TypeOrder.StringValue:\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return value.stringValue!.length * 2;\n case TypeOrder.BlobValue:\n return normalizeByteString(value.bytesValue!).approximateByteSize();\n case TypeOrder.RefValue:\n return value.referenceValue!.length;\n case TypeOrder.GeoPointValue:\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n case TypeOrder.ArrayValue:\n return estimateArrayByteSize(value.arrayValue!);\n case TypeOrder.ObjectValue:\n return estimateMapByteSize(value.mapValue!);\n default:\n throw fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nfunction estimateMapByteSize(mapValue: MapValue): number {\n let size = 0;\n forEach(mapValue.fields, (key, val) => {\n size += key.length + estimateByteSize(val);\n });\n return size;\n}\n\nfunction estimateArrayByteSize(arrayValue: ArrayValue): number {\n return (arrayValue.values || []).reduce(\n (previousSize, value) => previousSize + estimateByteSize(value),\n 0\n );\n}\n\n/** Returns a reference value for the provided database and key. */\nexport function refValue(databaseId: DatabaseId, key: DocumentKey): Value {\n return {\n referenceValue: `projects/${databaseId.projectId}/databases/${\n databaseId.database\n }/documents/${key.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */\nexport function isInteger(\n value?: Value | null\n): value is { integerValue: string | number } {\n return !!value && 'integerValue' in value;\n}\n\n/** Returns true if `value` is a DoubleValue. */\nexport function isDouble(\n value?: Value | null\n): value is { doubleValue: string | number } {\n return !!value && 'doubleValue' in value;\n}\n\n/** Returns true if `value` is either an IntegerValue or a DoubleValue. */\nexport function isNumber(value?: Value | null): boolean {\n return isInteger(value) || isDouble(value);\n}\n\n/** Returns true if `value` is an ArrayValue. */\nexport function isArray(\n value?: Value | null\n): value is { arrayValue: ArrayValue } {\n return !!value && 'arrayValue' in value;\n}\n\n/** Returns true if `value` is a ReferenceValue. */\nexport function isReferenceValue(\n value?: Value | null\n): value is { referenceValue: string } {\n return !!value && 'referenceValue' in value;\n}\n\n/** Returns true if `value` is a NullValue. */\nexport function isNullValue(\n value?: Value | null\n): value is { nullValue: 'NULL_VALUE' } {\n return !!value && 'nullValue' in value;\n}\n\n/** Returns true if `value` is NaN. */\nexport function isNanValue(\n value?: Value | null\n): value is { doubleValue: 'NaN' | number } {\n return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */\nexport function isMapValue(\n value?: Value | null\n): value is { mapValue: MapValue } {\n return !!value && 'mapValue' in value;\n}\n\n/** Creates a deep copy of `source`. */\nexport function deepClone(source: Value): Value {\n if (source.geoPointValue) {\n return { geoPointValue: { ...source.geoPointValue } };\n } else if (\n source.timestampValue &&\n typeof source.timestampValue === 'object'\n ) {\n return { timestampValue: { ...source.timestampValue } };\n } else if (source.mapValue) {\n const target: Value = { mapValue: { fields: {} } };\n forEach(\n source.mapValue.fields,\n (key, val) => (target.mapValue!.fields![key] = deepClone(val))\n );\n return target;\n } else if (source.arrayValue) {\n const target: Value = { arrayValue: { values: [] } };\n for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {\n target.arrayValue!.values![i] = deepClone(source.arrayValue.values![i]);\n }\n return target;\n } else {\n return { ...source };\n }\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */\nexport function isMaxValue(value: Value): boolean {\n return (\n (((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===\n MAX_VALUE_TYPE\n );\n}\n\n/** Returns the lowest value for the given value type (inclusive). */\nexport function valuesGetLowerBound(value: Value): Value {\n if ('nullValue' in value) {\n return MIN_VALUE;\n } else if ('booleanValue' in value) {\n return { booleanValue: false };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { doubleValue: NaN };\n } else if ('timestampValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('stringValue' in value) {\n return { stringValue: '' };\n } else if ('bytesValue' in value) {\n return { bytesValue: '' };\n } else if ('referenceValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('geoPointValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('arrayValue' in value) {\n return { arrayValue: {} };\n } else if ('mapValue' in value) {\n return { mapValue: {} };\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\n/** Returns the largest value for the given value type (exclusive). */\nexport function valuesGetUpperBound(value: Value): Value {\n if ('nullValue' in value) {\n return { booleanValue: false };\n } else if ('booleanValue' in value) {\n return { doubleValue: NaN };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('timestampValue' in value) {\n return { stringValue: '' };\n } else if ('stringValue' in value) {\n return { bytesValue: '' };\n } else if ('bytesValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('referenceValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('geoPointValue' in value) {\n return { arrayValue: {} };\n } else if ('arrayValue' in value) {\n return { mapValue: {} };\n } else if ('mapValue' in value) {\n return MAX_VALUE;\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nexport function lowerBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return -1;\n } else if (!left.inclusive && right.inclusive) {\n return 1;\n }\n\n return 0;\n}\n\nexport function upperBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return 1;\n } else if (!left.inclusive && right.inclusive) {\n return -1;\n }\n\n return 0;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { isReferenceValue, valueCompare, valueEquals } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\n\nimport { Direction, OrderBy } from './order_by';\n\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nexport class Bound {\n constructor(readonly position: ProtoValue[], readonly inclusive: boolean) {}\n}\n\nfunction boundCompareToDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): number {\n debugAssert(\n bound.position.length <= orderBy.length,\n \"Bound has more components than query's orderBy\"\n );\n let comparison = 0;\n for (let i = 0; i < bound.position.length; i++) {\n const orderByComponent = orderBy[i];\n const component = bound.position[i];\n if (orderByComponent.field.isKeyField()) {\n debugAssert(\n isReferenceValue(component),\n 'Bound has a non-key value where the key path is being used.'\n );\n comparison = DocumentKey.comparator(\n DocumentKey.fromName(component.referenceValue),\n doc.key\n );\n } else {\n const docValue = doc.data.field(orderByComponent.field);\n debugAssert(\n docValue !== null,\n 'Field should exist since document matched the orderBy already.'\n );\n comparison = valueCompare(component, docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return comparison;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */\nexport function boundSortsAfterDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison >= 0 : comparison > 0;\n}\n\n/**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\nexport function boundSortsBeforeDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison <= 0 : comparison < 0;\n}\n\nexport function boundEquals(left: Bound | null, right: Bound | null): boolean {\n if (left === null) {\n return right === null;\n } else if (right === null) {\n return false;\n }\n\n if (\n left.inclusive !== right.inclusive ||\n left.position.length !== right.position.length\n ) {\n return false;\n }\n for (let i = 0; i < left.position.length; i++) {\n const leftPosition = left.position[i];\n const rightPosition = right.position[i];\n if (!valueEquals(leftPosition, rightPosition)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath } from '../model/path';\nimport {\n arrayValueContains,\n canonicalId,\n isArray,\n isReferenceValue,\n typeOrder,\n valueCompare,\n valueEquals\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail } from '../util/assert';\n\n// The operator of a FieldFilter\nexport const enum Operator {\n LESS_THAN = '<',\n LESS_THAN_OR_EQUAL = '<=',\n EQUAL = '==',\n NOT_EQUAL = '!=',\n GREATER_THAN = '>',\n GREATER_THAN_OR_EQUAL = '>=',\n ARRAY_CONTAINS = 'array-contains',\n IN = 'in',\n NOT_IN = 'not-in',\n ARRAY_CONTAINS_ANY = 'array-contains-any'\n}\n\n// The operator of a CompositeFilter\nexport const enum CompositeOperator {\n OR = 'or',\n AND = 'and'\n}\n\nexport abstract class Filter {\n abstract matches(doc: Document): boolean;\n\n abstract getFlattenedFilters(): readonly FieldFilter[];\n\n abstract getFilters(): Filter[];\n}\n\nexport class FieldFilter extends Filter {\n protected constructor(\n public readonly field: FieldPath,\n public readonly op: Operator,\n public readonly value: ProtoValue\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(\n field: FieldPath,\n op: Operator,\n value: ProtoValue\n ): FieldFilter {\n if (field.isKeyField()) {\n if (op === Operator.IN || op === Operator.NOT_IN) {\n return this.createKeyFieldInFilter(field, op, value);\n } else {\n debugAssert(\n isReferenceValue(value),\n 'Comparing on key, but filter value not a RefValue'\n );\n debugAssert(\n op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY,\n `'${op.toString()}' queries don't make sense on document keys.`\n );\n return new KeyFieldFilter(field, op, value);\n }\n } else if (op === Operator.ARRAY_CONTAINS) {\n return new ArrayContainsFilter(field, value);\n } else if (op === Operator.IN) {\n debugAssert(\n isArray(value),\n 'IN filter has invalid value: ' + value.toString()\n );\n return new InFilter(field, value);\n } else if (op === Operator.NOT_IN) {\n debugAssert(\n isArray(value),\n 'NOT_IN filter has invalid value: ' + value.toString()\n );\n return new NotInFilter(field, value);\n } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n debugAssert(\n isArray(value),\n 'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString()\n );\n return new ArrayContainsAnyFilter(field, value);\n } else {\n return new FieldFilter(field, op, value);\n }\n }\n\n private static createKeyFieldInFilter(\n field: FieldPath,\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n ): FieldFilter {\n debugAssert(\n isArray(value),\n `Comparing on key with ${op.toString()}` +\n ', but filter value not an ArrayValue'\n );\n debugAssert(\n (value.arrayValue.values || []).every(elem => isReferenceValue(elem)),\n `Comparing on key with ${op.toString()}` +\n ', but an array value was not a RefValue'\n );\n\n return op === Operator.IN\n ? new KeyFieldInFilter(field, value)\n : new KeyFieldNotInFilter(field, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n if (this.op === Operator.NOT_EQUAL) {\n return (\n other !== null &&\n this.matchesComparison(valueCompare(other!, this.value))\n );\n }\n\n // Only compare types with matching backend order (such as double and int).\n return (\n other !== null &&\n typeOrder(this.value) === typeOrder(other) &&\n this.matchesComparison(valueCompare(other, this.value))\n );\n }\n\n protected matchesComparison(comparison: number): boolean {\n switch (this.op) {\n case Operator.LESS_THAN:\n return comparison < 0;\n case Operator.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case Operator.EQUAL:\n return comparison === 0;\n case Operator.NOT_EQUAL:\n return comparison !== 0;\n case Operator.GREATER_THAN:\n return comparison > 0;\n case Operator.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail('Unknown FieldFilter operator: ' + this.op);\n }\n }\n\n isInequality(): boolean {\n return (\n [\n Operator.LESS_THAN,\n Operator.LESS_THAN_OR_EQUAL,\n Operator.GREATER_THAN,\n Operator.GREATER_THAN_OR_EQUAL,\n Operator.NOT_EQUAL,\n Operator.NOT_IN\n ].indexOf(this.op) >= 0\n );\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n return [this];\n }\n\n getFilters(): Filter[] {\n return [this];\n }\n}\n\nexport class CompositeFilter extends Filter {\n private memoizedFlattenedFilters: FieldFilter[] | null = null;\n\n protected constructor(\n public readonly filters: readonly Filter[],\n public readonly op: CompositeOperator\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(filters: Filter[], op: CompositeOperator): CompositeFilter {\n return new CompositeFilter(filters, op);\n }\n\n matches(doc: Document): boolean {\n if (compositeFilterIsConjunction(this)) {\n // For conjunctions, all filters must match, so return false if any filter doesn't match.\n return this.filters.find(filter => !filter.matches(doc)) === undefined;\n } else {\n // For disjunctions, at least one filter should match.\n return this.filters.find(filter => filter.matches(doc)) !== undefined;\n }\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n if (this.memoizedFlattenedFilters !== null) {\n return this.memoizedFlattenedFilters;\n }\n\n this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {\n return result.concat(subfilter.getFlattenedFilters());\n }, [] as FieldFilter[]);\n\n return this.memoizedFlattenedFilters;\n }\n\n // Returns a mutable copy of `this.filters`\n getFilters(): Filter[] {\n return Object.assign([], this.filters);\n }\n}\n\nexport function compositeFilterIsConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.AND;\n}\n\nexport function compositeFilterIsDisjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.OR;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */\nexport function compositeFilterIsFlatConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return (\n compositeFilterIsFlat(compositeFilter) &&\n compositeFilterIsConjunction(compositeFilter)\n );\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */\nexport function compositeFilterIsFlat(\n compositeFilter: CompositeFilter\n): boolean {\n for (const filter of compositeFilter.filters) {\n if (filter instanceof CompositeFilter) {\n return false;\n }\n }\n return true;\n}\n\nexport function canonifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'canonifyFilter() only supports FieldFilters and CompositeFilters'\n );\n\n if (filter instanceof FieldFilter) {\n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return (\n filter.field.canonicalString() +\n filter.op.toString() +\n canonicalId(filter.value)\n );\n } else if (compositeFilterIsFlatConjunction(filter)) {\n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return filter.filters.map(filter => canonifyFilter(filter)).join(',');\n } else {\n // filter instanceof CompositeFilter\n const canonicalIdsString = filter.filters\n .map(filter => canonifyFilter(filter))\n .join(',');\n return `${filter.op}(${canonicalIdsString})`;\n }\n}\n\nexport function filterEquals(f1: Filter, f2: Filter): boolean {\n if (f1 instanceof FieldFilter) {\n return fieldFilterEquals(f1, f2);\n } else if (f1 instanceof CompositeFilter) {\n return compositeFilterEquals(f1, f2);\n } else {\n fail('Only FieldFilters and CompositeFilters can be compared');\n }\n}\n\nexport function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean {\n return (\n f2 instanceof FieldFilter &&\n f1.op === f2.op &&\n f1.field.isEqual(f2.field) &&\n valueEquals(f1.value, f2.value)\n );\n}\n\nexport function compositeFilterEquals(\n f1: CompositeFilter,\n f2: Filter\n): boolean {\n if (\n f2 instanceof CompositeFilter &&\n f1.op === f2.op &&\n f1.filters.length === f2.filters.length\n ) {\n const subFiltersMatch: boolean = f1.filters.reduce(\n (result: boolean, f1Filter: Filter, index: number): boolean =>\n result && filterEquals(f1Filter, f2.filters[index]),\n true\n );\n\n return subFiltersMatch;\n }\n\n return false;\n}\n\n/**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */\nexport function compositeFilterWithAddedFilters(\n compositeFilter: CompositeFilter,\n otherFilters: Filter[]\n): CompositeFilter {\n const mergedFilters = compositeFilter.filters.concat(otherFilters);\n return CompositeFilter.create(mergedFilters, compositeFilter.op);\n}\n\n/** Returns a debug description for `filter`. */\nexport function stringifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'stringifyFilter() only supports FieldFilters and CompositeFilters'\n );\n if (filter instanceof FieldFilter) {\n return stringifyFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return stringifyCompositeFilter(filter);\n } else {\n return 'Filter';\n }\n}\n\nexport function stringifyCompositeFilter(filter: CompositeFilter): string {\n return (\n filter.op.toString() +\n ` {` +\n filter.getFilters().map(stringifyFilter).join(' ,') +\n '}'\n );\n}\n\nexport function stringifyFieldFilter(filter: FieldFilter): string {\n return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(\n filter.value\n )}`;\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n private readonly key: DocumentKey;\n\n constructor(field: FieldPath, op: Operator, value: ProtoValue) {\n super(field, op, value);\n debugAssert(\n isReferenceValue(value),\n 'KeyFieldFilter expects a ReferenceValue'\n );\n this.key = DocumentKey.fromName(value.referenceValue);\n }\n\n matches(doc: Document): boolean {\n const comparison = DocumentKey.comparator(doc.key, this.key);\n return this.matchesComparison(comparison);\n }\n}\n\n/** Filter that matches on key fields within an array. */\nexport class KeyFieldInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n return this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */\nexport class KeyFieldNotInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value);\n }\n\n matches(doc: Document): boolean {\n return !this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\nfunction extractDocumentKeysFromArrayValue(\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n): DocumentKey[] {\n debugAssert(\n isArray(value),\n 'KeyFieldInFilter/KeyFieldNotInFilter expects an ArrayValue'\n );\n return (value.arrayValue?.values || []).map(v => {\n debugAssert(\n isReferenceValue(v),\n `Comparing on key with ${op.toString()}, but an array value was not ` +\n `a ReferenceValue`\n );\n return DocumentKey.fromName(v.referenceValue);\n });\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return isArray(other) && arrayValueContains(other.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n debugAssert(isArray(value), 'InFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return other !== null && arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the not-in operator. */\nexport class NotInFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n debugAssert(isArray(value), 'NotInFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n if (\n arrayValueContains(this.value.arrayValue!, { nullValue: 'NULL_VALUE' })\n ) {\n return false;\n }\n const other = doc.data.field(this.field);\n return other !== null && !arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS_ANY, value);\n debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n if (!isArray(other) || !other.arrayValue.values) {\n return false;\n }\n return other.arrayValue.values.some(val =>\n arrayValueContains(this.value.arrayValue!, val)\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * The direction of sorting in an order by.\n */\nexport const enum Direction {\n ASCENDING = 'asc',\n DESCENDING = 'desc'\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n constructor(\n readonly field: FieldPath,\n readonly dir: Direction = Direction.ASCENDING\n ) {}\n}\n\nexport function canonifyOrderBy(orderBy: OrderBy): string {\n // TODO(b/29183165): Make this collision robust.\n return orderBy.field.canonicalString() + orderBy.dir;\n}\n\nexport function stringifyOrderBy(orderBy: OrderBy): string {\n return `${orderBy.field.canonicalString()} (${orderBy.dir})`;\n}\n\nexport function orderByEquals(left: OrderBy, right: OrderBy): boolean {\n return left.dir === right.dir && left.field.isEqual(right.field);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\n\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nexport class SnapshotVersion {\n static fromTimestamp(value: Timestamp): SnapshotVersion {\n return new SnapshotVersion(value);\n }\n\n static min(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(0, 0));\n }\n\n static max(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));\n }\n\n private constructor(private timestamp: Timestamp) {}\n\n compareTo(other: SnapshotVersion): number {\n return this.timestamp._compareTo(other.timestamp);\n }\n\n isEqual(other: SnapshotVersion): boolean {\n return this.timestamp.isEqual(other.timestamp);\n }\n\n /** Returns a number representation of the version for use in spec tests. */\n toMicroseconds(): number {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n }\n\n toString(): string {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n }\n\n toTimestamp(): Timestamp {\n return this.timestamp;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from './assert';\n\n/*\n * Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\nexport type Comparator = (key1: K, key2: K) => number;\n\nexport interface Entry {\n key: K;\n value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap {\n // visible for testing\n root: LLRBNode | LLRBEmptyNode;\n\n constructor(\n public comparator: Comparator,\n root?: LLRBNode | LLRBEmptyNode\n ) {\n this.root = root ? root : LLRBNode.EMPTY;\n }\n\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(key: K, value: V): SortedMap {\n return new SortedMap(\n this.comparator,\n this.root\n .insert(key, value, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns a copy of the map, with the specified key removed.\n remove(key: K): SortedMap {\n return new SortedMap(\n this.comparator,\n this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns the value of the node with the given key, or null.\n get(key: K): V | null {\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(key: K): number {\n // Number of nodes that were pruned when descending right\n let prunedNodes = 0;\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n }\n\n isEmpty(): boolean {\n return this.root.isEmpty();\n }\n\n // Returns the total number of nodes in the map.\n get size(): number {\n return this.root.size;\n }\n\n // Returns the minimum key in the map.\n minKey(): K | null {\n return this.root.minKey();\n }\n\n // Returns the maximum key in the map.\n maxKey(): K | null {\n return this.root.maxKey();\n }\n\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).inorderTraversal(action);\n }\n\n forEach(fn: (k: K, v: V) => void): void {\n this.inorderTraversal((k, v) => {\n fn(k, v);\n return false;\n });\n }\n\n toString(): string {\n const descriptions: string[] = [];\n this.inorderTraversal((k, v) => {\n descriptions.push(`${k}:${v}`);\n return false;\n });\n return `{${descriptions.join(', ')}}`;\n }\n\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).reverseTraversal(action);\n }\n\n // Returns an iterator over the SortedMap.\n getIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, false);\n }\n\n getIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, false);\n }\n\n getReverseIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, true);\n }\n\n getReverseIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, true);\n }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator {\n private isReverse: boolean;\n private nodeStack: Array | LLRBEmptyNode>;\n\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\n isReverse: boolean\n ) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n\n let cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (startKey && isReverse) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n } else {\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(node);\n if (this.isReverse) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): Entry {\n debugAssert(\n this.nodeStack.length > 0,\n 'getNext() called on iterator when hasNext() is false.'\n );\n\n let node = this.nodeStack.pop()!;\n const result = { key: node.key, value: node.value };\n\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack.length > 0;\n }\n\n peek(): Entry | null {\n if (this.nodeStack.length === 0) {\n return null;\n }\n\n const node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode {\n readonly color: boolean;\n readonly left: LLRBNode | LLRBEmptyNode;\n readonly right: LLRBNode | LLRBEmptyNode;\n readonly size: number;\n\n // Empty node is shared between all LLRB trees.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static EMPTY: LLRBEmptyNode = null as any;\n\n static RED = true;\n static BLACK = false;\n\n constructor(\n public key: K,\n public value: V,\n color?: boolean,\n left?: LLRBNode | LLRBEmptyNode,\n right?: LLRBNode | LLRBEmptyNode\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBNode {\n return new LLRBNode(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n isEmpty(): boolean {\n return false;\n }\n\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.left as LLRBNode).inorderTraversal(action) ||\n action(this.key, this.value) ||\n (this.right as LLRBNode).inorderTraversal(action)\n );\n }\n\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.right as LLRBNode).reverseTraversal(action) ||\n action(this.key, this.value) ||\n (this.left as LLRBNode).reverseTraversal(action)\n );\n }\n\n // Returns the minimum node in the tree.\n private min(): LLRBNode {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode).min();\n }\n }\n\n // Returns the maximum key in the tree.\n minKey(): K | null {\n return this.min().key;\n }\n\n // Returns the maximum key in the tree.\n maxKey(): K | null {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n // Returns new tree, with the key/value added.\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n let n: LLRBNode = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp();\n }\n\n private removeMin(): LLRBNode | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n let n: LLRBNode = this;\n if (!n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode).removeMin(), null);\n return n.fixUp();\n }\n\n // Returns new tree, with the specified item removed.\n remove(\n key: K,\n comparator: Comparator\n ): LLRBNode | LLRBEmptyNode {\n let smallest: LLRBNode;\n let n: LLRBNode = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed()) {\n n = n.rotateRight();\n }\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n } else {\n smallest = (n.right as LLRBNode).min();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode).removeMin()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n }\n\n isRed(): boolean {\n return this.color;\n }\n\n // Returns new tree after performing any needed rotations.\n private fixUp(): LLRBNode {\n let n: LLRBNode = this;\n if (n.right.isRed() && !n.left.isRed()) {\n n = n.rotateLeft();\n }\n if (n.left.isRed() && n.left.left.isRed()) {\n n = n.rotateRight();\n }\n if (n.left.isRed() && n.right.isRed()) {\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedLeft(): LLRBNode {\n let n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode).rotateRight()\n );\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedRight(): LLRBNode {\n let n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n }\n\n private rotateLeft(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return (this.right as LLRBNode).copy(\n null,\n null,\n this.color,\n nl,\n null\n );\n }\n\n private rotateRight(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return (this.left as LLRBNode).copy(null, null, this.color, null, nr);\n }\n\n private colorFlip(): LLRBNode {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n const blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n } else {\n return false;\n }\n }\n\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n protected check(): number {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail('Black depths differ');\n } else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n }\n} // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nexport class LLRBEmptyNode {\n get key(): never {\n throw fail('LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail('LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail('LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail('LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail('LLRBEmptyNode has no right child.');\n }\n size = 0;\n\n // Returns a copy of the current node.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBEmptyNode {\n return this;\n }\n\n // Returns a copy of the tree, with the specified key/value added.\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n return new LLRBNode(key, value);\n }\n\n // Returns a copy of the tree, with the specified key removed.\n remove(key: K, comparator: Comparator): LLRBEmptyNode {\n return this;\n }\n\n isEmpty(): boolean {\n return true;\n }\n\n inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n minKey(): K | null {\n return null;\n }\n\n maxKey(): K | null {\n return null;\n }\n\n isRed(): boolean {\n return false;\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n return true;\n }\n\n protected check(): 0 {\n return 0;\n }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap, SortedMapIterator } from './sorted_map';\n\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nexport class SortedSet {\n private data: SortedMap;\n\n constructor(private comparator: (left: T, right: T) => number) {\n this.data = new SortedMap(this.comparator);\n }\n\n has(elem: T): boolean {\n return this.data.get(elem) !== null;\n }\n\n first(): T | null {\n return this.data.minKey();\n }\n\n last(): T | null {\n return this.data.maxKey();\n }\n\n get size(): number {\n return this.data.size;\n }\n\n indexOf(elem: T): number {\n return this.data.indexOf(elem);\n }\n\n /** Iterates elements in order defined by \"comparator\" */\n forEach(cb: (elem: T) => void): void {\n this.data.inorderTraversal((k: T, v: boolean) => {\n cb(k);\n return false;\n });\n }\n\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n const iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n const elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) {\n return;\n }\n cb(elem.key);\n }\n }\n\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n const elem = iter.getNext();\n const result = cb(elem.key);\n if (!result) {\n return;\n }\n }\n }\n\n /** Finds the least element greater than or equal to `elem`. */\n firstAfterOrEqual(elem: T): T | null {\n const iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n }\n\n getIterator(): SortedSetIterator {\n return new SortedSetIterator(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator {\n return new SortedSetIterator(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet {\n if (!this.has(elem)) {\n return this;\n }\n return this.copy(this.data.remove(elem));\n }\n\n isEmpty(): boolean {\n return this.data.isEmpty();\n }\n\n unionWith(other: SortedSet): SortedSet {\n let result: SortedSet = this;\n\n // Make sure `result` always refers to the larger one of the two sets.\n if (result.size < other.size) {\n result = other;\n other = this;\n }\n\n other.forEach(elem => {\n result = result.add(elem);\n });\n return result;\n }\n\n isEqual(other: SortedSet): boolean {\n if (!(other instanceof SortedSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.data.getIterator();\n const otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n const thisElem = thisIt.getNext().key;\n const otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) {\n return false;\n }\n }\n return true;\n }\n\n toArray(): T[] {\n const res: T[] = [];\n this.forEach(targetId => {\n res.push(targetId);\n });\n return res;\n }\n\n toString(): string {\n const result: T[] = [];\n this.forEach(elem => result.push(elem));\n return 'SortedSet(' + result.toString() + ')';\n }\n\n private copy(data: SortedMap): SortedSet {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator {\n constructor(private iter: SortedMapIterator) {}\n\n getNext(): T {\n return this.iter.getNext().key;\n }\n\n hasNext(): boolean {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffSortedSets(\n before: SortedSet,\n after: SortedSet,\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n const beforeIt = before.getIterator();\n const afterIt = after.getIterator();\n\n let beforeValue = advanceIterator(beforeIt);\n let afterValue = advanceIterator(afterIt);\n\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n while (beforeValue || afterValue) {\n let added = false;\n let removed = false;\n\n if (beforeValue && afterValue) {\n const cmp = comparator(beforeValue, afterValue);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n removed = true;\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n added = true;\n }\n } else if (beforeValue != null) {\n removed = true;\n } else {\n added = true;\n }\n\n if (added) {\n onAdd(afterValue!);\n afterValue = advanceIterator(afterIt);\n } else if (removed) {\n onRemove(beforeValue!);\n beforeValue = advanceIterator(beforeIt);\n } else {\n beforeValue = advanceIterator(beforeIt);\n afterValue = advanceIterator(afterIt);\n }\n }\n}\n\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction advanceIterator(it: SortedSetIterator): T | undefined {\n return it.hasNext() ? it.getNext() : undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { FieldPath } from './path';\n\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */\nexport class FieldMask {\n constructor(readonly fields: FieldPath[]) {\n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n fields.sort(FieldPath.comparator);\n debugAssert(\n !fields.some((v, i) => i !== 0 && v.isEqual(fields[i - 1])),\n 'FieldMask contains field that is not unique: ' +\n fields.find((v, i) => i !== 0 && v.isEqual(fields[i - 1]))!\n );\n }\n\n static empty(): FieldMask {\n return new FieldMask([]);\n }\n\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */\n unionWith(extraFields: FieldPath[]): FieldMask {\n let mergedMaskSet = new SortedSet(FieldPath.comparator);\n for (const fieldPath of this.fields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n for (const fieldPath of extraFields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n return new FieldMask(mergedMaskSet.toArray());\n }\n\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */\n covers(fieldPath: FieldPath): boolean {\n for (const fieldMaskPath of this.fields) {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n return true;\n }\n }\n return false;\n }\n\n isEqual(other: FieldMask): boolean {\n return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\nimport { forEach } from '../util/obj';\n\nimport { FieldMask } from './field_mask';\nimport { FieldPath } from './path';\nimport { isServerTimestamp } from './server_timestamps';\nimport { deepClone, isMapValue, valueEquals } from './values';\n\nexport interface JsonObject {\n [name: string]: T;\n}\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */\nexport class ObjectValue {\n constructor(readonly value: { mapValue: ProtoMapValue }) {\n debugAssert(\n !isServerTimestamp(value),\n 'ServerTimestamps should be converted to ServerTimestampValue'\n );\n }\n\n static empty(): ObjectValue {\n return new ObjectValue({ mapValue: {} });\n }\n\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */\n field(path: FieldPath): ProtoValue | null {\n if (path.isEmpty()) {\n return this.value;\n } else {\n let currentLevel: ProtoValue = this.value;\n for (let i = 0; i < path.length - 1; ++i) {\n currentLevel = (currentLevel.mapValue!.fields || {})[path.get(i)];\n if (!isMapValue(currentLevel)) {\n return null;\n }\n }\n currentLevel = (currentLevel.mapValue!.fields! || {})[path.lastSegment()];\n return currentLevel || null;\n }\n }\n\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */\n set(path: FieldPath, value: ProtoValue): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot set field for empty path on ObjectValue'\n );\n const fieldsMap = this.getFieldsMap(path.popLast());\n fieldsMap[path.lastSegment()] = deepClone(value);\n }\n\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */\n setAll(data: Map): void {\n let parent = FieldPath.emptyPath();\n\n let upserts: { [key: string]: ProtoValue } = {};\n let deletes: string[] = [];\n\n data.forEach((value, path) => {\n if (!parent.isImmediateParentOf(path)) {\n // Insert the accumulated changes at this parent location\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n upserts = {};\n deletes = [];\n parent = path.popLast();\n }\n\n if (value) {\n upserts[path.lastSegment()] = deepClone(value);\n } else {\n deletes.push(path.lastSegment());\n }\n });\n\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n }\n\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */\n delete(path: FieldPath): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n const nestedValue = this.field(path.popLast());\n if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {\n delete nestedValue.mapValue.fields[path.lastSegment()];\n }\n }\n\n isEqual(other: ObjectValue): boolean {\n return valueEquals(this.value, other.value);\n }\n\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */\n private getFieldsMap(path: FieldPath): Record {\n let current = this.value;\n\n if (!current.mapValue!.fields) {\n current.mapValue = { fields: {} };\n }\n\n for (let i = 0; i < path.length; ++i) {\n let next = current.mapValue!.fields![path.get(i)];\n if (!isMapValue(next) || !next.mapValue.fields) {\n next = { mapValue: { fields: {} } };\n current.mapValue!.fields![path.get(i)] = next;\n }\n current = next as { mapValue: ProtoMapValue };\n }\n\n return current.mapValue!.fields!;\n }\n\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */\n private applyChanges(\n fieldsMap: Record,\n inserts: { [key: string]: ProtoValue },\n deletes: string[]\n ): void {\n forEach(inserts, (key, val) => (fieldsMap[key] = val));\n for (const field of deletes) {\n delete fieldsMap[field];\n }\n }\n\n clone(): ObjectValue {\n return new ObjectValue(\n deepClone(this.value) as { mapValue: ProtoMapValue }\n );\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */\nexport function extractFieldMask(value: ProtoMapValue): FieldMask {\n const fields: FieldPath[] = [];\n forEach(value!.fields, (key, value) => {\n const currentPath = new FieldPath([key]);\n if (isMapValue(value)) {\n const nestedMask = extractFieldMask(value.mapValue!);\n const nestedFields = nestedMask.fields;\n if (nestedFields.length === 0) {\n // Preserve the empty map by adding it to the FieldMask.\n fields.push(currentPath);\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const nestedPath of nestedFields) {\n fields.push(currentPath.child(nestedPath));\n }\n }\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n fields.push(currentPath);\n }\n });\n return new FieldMask(fields);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { DocumentKey } from './document_key';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport { valueCompare } from './values';\n\n/**\n * Whether the document represents an existing document, a document that is\n * known to exist or a document whose state or existence is unknown.\n */\nconst enum DocumentType {\n /**\n * Represents the initial state of a MutableDocument when only the document\n * key is known. Invalid documents transition to other states as mutations are\n * applied. If a document remains invalid after applying mutations, it should\n * be discarded.\n *\n * Invalid documents can have neither local nor committed mutations.\n */\n INVALID,\n /**\n * Represents a document in Firestore with a key, version, data and whether\n * the data has local mutations applied to it.\n *\n * Found documents can be sycned or have or committed mutations applied.\n */\n FOUND_DOCUMENT,\n /**\n * Represents that no documents exists for the key at the given version.\n *\n * Documents that are deleted based on a local mutation do not raise snapshots\n * with `hasPendingWrites`. As such, deleted documents never have\n * `HAS_LOCAL_MUTATIONS` set. Once a delete is committed, we store them with\n * `HAS_COMMITTED_MUTATIONS` until we received the delete from the Watch\n * stream.\n */\n NO_DOCUMENT,\n /**\n * Represents an existing document whose data is unknown (e.g. a document that\n * was updated without a known base document).\n *\n * An unknown document always has `HAS_COMMITTED_MUTATIONS` set, since unknown\n * documents can only be generated by applying a patch mutation from a write\n * acknowledgement.\n */\n UNKNOWN_DOCUMENT\n}\n\n/** Describes whether a document has latency-compensated edits applied. */\nconst enum DocumentState {\n /** No mutations applied. Document was sent to us by Watch. */\n SYNCED,\n /**\n * Local mutations applied via the mutation queue. Document is potentially\n * inconsistent.\n */\n HAS_LOCAL_MUTATIONS,\n /**\n * Mutations applied based on a write acknowledgment. Document is potentially\n * inconsistent.\n */\n HAS_COMMITTED_MUTATIONS\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether the\n * data has local mutations applied to it.\n */\nexport interface Document {\n /** The key for this document */\n readonly key: DocumentKey;\n\n /**\n * The version of this document if it exists or a version at which this\n * document was guaranteed to not exist.\n */\n readonly version: SnapshotVersion;\n\n /**\n * The timestamp at which this document was read from the remote server. Uses\n * `SnapshotVersion.min()` for documents created by the user.\n */\n readonly readTime: SnapshotVersion;\n\n /**\n * The timestamp at which the document was created. This value increases\n * monotonically when a document is deleted then recreated. It can also be\n * compared to `createTime` of other documents and the `readTime` of a query.\n */\n readonly createTime: SnapshotVersion;\n\n /** The underlying data of this document or an empty value if no data exists. */\n readonly data: ObjectValue;\n\n /** Returns whether local mutations were applied via the mutation queue. */\n readonly hasLocalMutations: boolean;\n\n /** Returns whether mutations were applied based on a write acknowledgment. */\n readonly hasCommittedMutations: boolean;\n\n /**\n * Whether this document had a local mutation applied that has not yet been\n * acknowledged by Watch.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * Returns whether this document is valid (i.e. it is an entry in the\n * RemoteDocumentCache, was created by a mutation or read from the backend).\n */\n isValidDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is known at the current\n * version.\n */\n isFoundDocument(): boolean;\n\n /**\n * Returns whether the document is known to not exist at the current version.\n */\n isNoDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is unknown at the current\n * version.\n */\n isUnknownDocument(): boolean;\n\n isEqual(other: Document | null | undefined): boolean;\n\n /** Creates a mutable copy of this document. */\n mutableCopy(): MutableDocument;\n\n toString(): string;\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */\nexport class MutableDocument implements Document {\n private constructor(\n readonly key: DocumentKey,\n private documentType: DocumentType,\n public version: SnapshotVersion,\n public readTime: SnapshotVersion,\n public createTime: SnapshotVersion,\n public data: ObjectValue,\n private documentState: DocumentState\n ) {}\n\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */\n static newInvalidDocument(documentKey: DocumentKey): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.INVALID,\n /* version */ SnapshotVersion.min(),\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */\n static newFoundDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion,\n createTime: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.FOUND_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ createTime,\n value,\n DocumentState.SYNCED\n );\n }\n\n /** Creates a new document that is known to not exist at the given version. */\n static newNoDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.NO_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */\n static newUnknownDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.UNKNOWN_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.HAS_COMMITTED_MUTATIONS\n );\n }\n\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */\n convertToFoundDocument(\n version: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n if (\n this.createTime.isEqual(SnapshotVersion.min()) &&\n (this.documentType === DocumentType.NO_DOCUMENT ||\n this.documentType === DocumentType.INVALID)\n ) {\n this.createTime = version;\n }\n this.version = version;\n this.documentType = DocumentType.FOUND_DOCUMENT;\n this.data = value;\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */\n convertToNoDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.NO_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */\n convertToUnknownDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.UNKNOWN_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasCommittedMutations(): MutableDocument {\n debugAssert(\n this.isValidDocument(),\n 'Invalid documents cannot have committed mutations'\n );\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasLocalMutations(): MutableDocument {\n this.documentState = DocumentState.HAS_LOCAL_MUTATIONS;\n this.version = SnapshotVersion.min();\n return this;\n }\n\n setReadTime(readTime: SnapshotVersion): MutableDocument {\n this.readTime = readTime;\n return this;\n }\n\n get hasLocalMutations(): boolean {\n return this.documentState === DocumentState.HAS_LOCAL_MUTATIONS;\n }\n\n get hasCommittedMutations(): boolean {\n return this.documentState === DocumentState.HAS_COMMITTED_MUTATIONS;\n }\n\n get hasPendingWrites(): boolean {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n\n isValidDocument(): boolean {\n return this.documentType !== DocumentType.INVALID;\n }\n\n isFoundDocument(): boolean {\n return this.documentType === DocumentType.FOUND_DOCUMENT;\n }\n\n isNoDocument(): boolean {\n return this.documentType === DocumentType.NO_DOCUMENT;\n }\n\n isUnknownDocument(): boolean {\n return this.documentType === DocumentType.UNKNOWN_DOCUMENT;\n }\n\n isEqual(other: Document | null | undefined): boolean {\n return (\n other instanceof MutableDocument &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.documentType === other.documentType &&\n this.documentState === other.documentState &&\n this.data.isEqual(other.data)\n );\n }\n\n mutableCopy(): MutableDocument {\n return new MutableDocument(\n this.key,\n this.documentType,\n this.version,\n this.readTime,\n this.createTime,\n this.data.clone(),\n this.documentState\n );\n }\n\n toString(): string {\n return (\n `Document(${this.key}, ${this.version}, ${JSON.stringify(\n this.data.value\n )}, ` +\n `{createTime: ${this.createTime}}), ` +\n `{documentType: ${this.documentType}}), ` +\n `{documentState: ${this.documentState}})`\n );\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\nexport function compareDocumentsByField(\n field: FieldPath,\n d1: Document,\n d2: Document\n): number {\n const v1 = d1.data.field(field);\n const v2 = d2.data.field(field);\n if (v1 !== null && v2 !== null) {\n return valueCompare(v1, v2);\n } else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n canonicalId,\n MAX_VALUE,\n MIN_VALUE,\n lowerBoundCompare,\n upperBoundCompare,\n valuesGetLowerBound,\n valuesGetUpperBound\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugCast } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Bound, boundEquals } from './bound';\nimport {\n Filter,\n FieldFilter,\n canonifyFilter,\n stringifyFilter,\n filterEquals,\n Operator\n} from './filter';\nimport {\n canonifyOrderBy,\n OrderBy,\n orderByEquals,\n stringifyOrderBy\n} from './order_by';\n\n/**\n * A Target represents the WatchTarget representation of a Query, which is used\n * by the LocalStore and the RemoteStore to keep track of and to execute\n * backend queries. While a Query can represent multiple Targets, each Targets\n * maps to a single WatchTarget in RemoteStore and a single TargetData entry\n * in persistence.\n */\nexport interface Target {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly orderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n// Visible for testing\nexport class TargetImpl implements Target {\n memoizedCanonicalId: string | null = null;\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly orderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {}\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */\nexport function newTarget(\n path: ResourcePath,\n collectionGroup: string | null = null,\n orderBy: OrderBy[] = [],\n filters: Filter[] = [],\n limit: number | null = null,\n startAt: Bound | null = null,\n endAt: Bound | null = null\n): Target {\n return new TargetImpl(\n path,\n collectionGroup,\n orderBy,\n filters,\n limit,\n startAt,\n endAt\n );\n}\n\nexport function canonifyTarget(target: Target): string {\n const targetImpl = debugCast(target, TargetImpl);\n\n if (targetImpl.memoizedCanonicalId === null) {\n let str = targetImpl.path.canonicalString();\n if (targetImpl.collectionGroup !== null) {\n str += '|cg:' + targetImpl.collectionGroup;\n }\n str += '|f:';\n str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');\n str += '|ob:';\n str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');\n\n if (!isNullOrUndefined(targetImpl.limit)) {\n str += '|l:';\n str += targetImpl.limit!;\n }\n if (targetImpl.startAt) {\n str += '|lb:';\n str += targetImpl.startAt.inclusive ? 'b:' : 'a:';\n str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (targetImpl.endAt) {\n str += '|ub:';\n str += targetImpl.endAt.inclusive ? 'a:' : 'b:';\n str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');\n }\n targetImpl.memoizedCanonicalId = str;\n }\n return targetImpl.memoizedCanonicalId;\n}\n\nexport function stringifyTarget(target: Target): string {\n let str = target.path.canonicalString();\n if (target.collectionGroup !== null) {\n str += ' collectionGroup=' + target.collectionGroup;\n }\n if (target.filters.length > 0) {\n str += `, filters: [${target.filters\n .map(f => stringifyFilter(f))\n .join(', ')}]`;\n }\n if (!isNullOrUndefined(target.limit)) {\n str += ', limit: ' + target.limit;\n }\n if (target.orderBy.length > 0) {\n str += `, orderBy: [${target.orderBy\n .map(o => stringifyOrderBy(o))\n .join(', ')}]`;\n }\n if (target.startAt) {\n str += ', startAt: ';\n str += target.startAt.inclusive ? 'b:' : 'a:';\n str += target.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (target.endAt) {\n str += ', endAt: ';\n str += target.endAt.inclusive ? 'a:' : 'b:';\n str += target.endAt.position.map(p => canonicalId(p)).join(',');\n }\n return `Target(${str})`;\n}\n\nexport function targetEquals(left: Target, right: Target): boolean {\n if (left.limit !== right.limit) {\n return false;\n }\n\n if (left.orderBy.length !== right.orderBy.length) {\n return false;\n }\n\n for (let i = 0; i < left.orderBy.length; i++) {\n if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {\n return false;\n }\n }\n\n if (left.filters.length !== right.filters.length) {\n return false;\n }\n\n for (let i = 0; i < left.filters.length; i++) {\n if (!filterEquals(left.filters[i], right.filters[i])) {\n return false;\n }\n }\n\n if (left.collectionGroup !== right.collectionGroup) {\n return false;\n }\n\n if (!left.path.isEqual(right.path)) {\n return false;\n }\n\n if (!boundEquals(left.startAt, right.startAt)) {\n return false;\n }\n\n return boundEquals(left.endAt, right.endAt);\n}\n\nexport function targetIsDocumentTarget(target: Target): boolean {\n return (\n DocumentKey.isDocumentKey(target.path) &&\n target.collectionGroup === null &&\n target.filters.length === 0\n );\n}\n\n/** Returns the field filters that target the given field path. */\nexport function targetGetFieldFiltersForPath(\n target: Target,\n path: FieldPath\n): FieldFilter[] {\n return target.filters.filter(\n f => f instanceof FieldFilter && f.field.isEqual(path)\n ) as FieldFilter[];\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\nexport function targetGetArrayValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const segment = fieldIndexGetArraySegment(fieldIndex);\n if (segment === undefined) {\n return null;\n }\n\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.ARRAY_CONTAINS_ANY:\n return fieldFilter.value.arrayValue!.values || [];\n case Operator.ARRAY_CONTAINS:\n return [fieldFilter.value];\n default:\n // Remaining filters are not array filters.\n }\n }\n return null;\n}\n\n/**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */\nexport function targetGetNotInValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const values = new Map();\n\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.EQUAL:\n case Operator.IN:\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n break;\n case Operator.NOT_IN:\n case Operator.NOT_EQUAL:\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n return Array.from(values.values());\n default:\n // Remaining filters cannot be used as notIn bounds.\n }\n }\n }\n\n return null;\n}\n\n/**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */\nexport function targetGetLowerBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)\n : targetGetDescendingBound(target, segment.fieldPath, target.startAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */\nexport function targetGetUpperBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)\n : targetGetAscendingBound(target, segment.fieldPath, target.endAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction targetGetAscendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MIN_VALUE;\n\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MIN_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.LESS_THAN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = valuesGetLowerBound(fieldFilter.value);\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.GREATER_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.GREATER_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MIN_VALUE;\n break;\n default:\n // Remaining filters cannot be used as lower bounds.\n }\n\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) < 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) < 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */\nfunction targetGetDescendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MAX_VALUE;\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MAX_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.GREATER_THAN_OR_EQUAL:\n case Operator.GREATER_THAN:\n filterValue = valuesGetUpperBound(fieldFilter.value);\n filterInclusive = false;\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.LESS_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MAX_VALUE;\n break;\n default:\n // Remaining filters cannot be used as upper bounds.\n }\n\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) > 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) > 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\nexport function targetGetSegmentCount(target: Target): number {\n let fields = new SortedSet(FieldPath.comparator);\n let hasArraySegment = false;\n\n for (const filter of target.filters) {\n for (const subFilter of filter.getFlattenedFilters()) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (subFilter.field.isKeyField()) {\n continue;\n }\n\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n if (\n subFilter.op === Operator.ARRAY_CONTAINS ||\n subFilter.op === Operator.ARRAY_CONTAINS_ANY\n ) {\n hasArraySegment = true;\n } else {\n fields = fields.add(subFilter.field);\n }\n }\n }\n\n for (const orderBy of target.orderBy) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (!orderBy.field.isKeyField()) {\n fields = fields.add(orderBy.field);\n }\n }\n\n return fields.size + (hasArraySegment ? 1 : 0);\n}\n\nexport function targetHasLimit(target: Target): boolean {\n return target.limit !== null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { compareDocumentsByField, Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { debugAssert, debugCast, fail } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n Bound,\n boundSortsAfterDocument,\n boundSortsBeforeDocument\n} from './bound';\nimport { FieldFilter, Filter } from './filter';\nimport { Direction, OrderBy } from './order_by';\nimport {\n canonifyTarget,\n newTarget,\n stringifyTarget,\n Target,\n targetEquals\n} from './target';\n\nexport const enum LimitType {\n First = 'F',\n Last = 'L'\n}\n\n/**\n * The Query interface defines all external properties of a query.\n *\n * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy`\n * and `queryToTarget`.\n */\nexport interface Query {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly explicitOrderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly limitType: LimitType;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nexport class QueryImpl implements Query {\n memoizedNormalizedOrderBy: OrderBy[] | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // non-aggregate queries.\n memoizedTarget: Target | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // aggregate queries. Unlike targets for non-aggregate queries,\n // aggregate query targets do not contain normalized order-bys, they only\n // contain explicit order-bys.\n memoizedAggregateTarget: Target | null = null;\n\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly explicitOrderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly limitType: LimitType = LimitType.First,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {\n if (this.startAt) {\n debugAssert(\n this.startAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n if (this.endAt) {\n debugAssert(\n this.endAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n }\n}\n\n/** Creates a new Query instance with the options provided. */\nexport function newQuery(\n path: ResourcePath,\n collectionGroup: string | null,\n explicitOrderBy: OrderBy[],\n filters: Filter[],\n limit: number | null,\n limitType: LimitType,\n startAt: Bound | null,\n endAt: Bound | null\n): Query {\n return new QueryImpl(\n path,\n collectionGroup,\n explicitOrderBy,\n filters,\n limit,\n limitType,\n startAt,\n endAt\n );\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */\nexport function newQueryForPath(path: ResourcePath): Query {\n return new QueryImpl(path);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\nexport function asCollectionQueryAtPath(\n query: Query,\n path: ResourcePath\n): Query {\n return new QueryImpl(\n path,\n /*collectionGroup=*/ null,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nexport function queryMatchesAllDocuments(query: Query): boolean {\n return (\n query.filters.length === 0 &&\n query.limit === null &&\n query.startAt == null &&\n query.endAt == null &&\n (query.explicitOrderBy.length === 0 ||\n (query.explicitOrderBy.length === 1 &&\n query.explicitOrderBy[0].field.isKeyField()))\n );\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\nexport function getInequalityFilterFields(query: Query): SortedSet {\n let result = new SortedSet(FieldPath.comparator);\n query.filters.forEach((filter: Filter) => {\n const subFilters = filter.getFlattenedFilters();\n subFilters.forEach((filter: FieldFilter) => {\n if (filter.isInequality()) {\n result = result.add(filter.field);\n }\n });\n });\n return result;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\nexport function newQueryForCollectionGroup(collectionId: string): Query {\n return new QueryImpl(ResourcePath.emptyPath(), collectionId);\n}\n\n/**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\nexport function isDocumentQuery(query: Query): boolean {\n return (\n DocumentKey.isDocumentKey(query.path) &&\n query.collectionGroup === null &&\n query.filters.length === 0\n );\n}\n\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nexport function isCollectionGroupQuery(query: Query): boolean {\n return query.collectionGroup !== null;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */\nexport function queryNormalizedOrderBy(query: Query): OrderBy[] {\n const queryImpl = debugCast(query, QueryImpl);\n if (queryImpl.memoizedNormalizedOrderBy === null) {\n queryImpl.memoizedNormalizedOrderBy = [];\n const fieldsNormalized = new Set();\n\n // Any explicit order by fields should be added as is.\n for (const orderBy of queryImpl.explicitOrderBy) {\n queryImpl.memoizedNormalizedOrderBy.push(orderBy);\n fieldsNormalized.add(orderBy.field.canonicalString());\n }\n\n // The order of the implicit ordering always matches the last explicit order by.\n const lastDirection =\n queryImpl.explicitOrderBy.length > 0\n ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n\n // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n // order. When there are multiple inequality filters on the same field, the field should be added\n // only once.\n // Note: `SortedSet` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n const inequalityFields: SortedSet =\n getInequalityFilterFields(queryImpl);\n inequalityFields.forEach(field => {\n if (\n !fieldsNormalized.has(field.canonicalString()) &&\n !field.isKeyField()\n ) {\n queryImpl.memoizedNormalizedOrderBy!.push(\n new OrderBy(field, lastDirection)\n );\n }\n });\n\n // Add the document key field to the last if it is not explicitly ordered.\n if (!fieldsNormalized.has(FieldPath.keyField().canonicalString())) {\n queryImpl.memoizedNormalizedOrderBy.push(\n new OrderBy(FieldPath.keyField(), lastDirection)\n );\n }\n }\n return queryImpl.memoizedNormalizedOrderBy;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */\nexport function queryToTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n if (!queryImpl.memoizedTarget) {\n queryImpl.memoizedTarget = _queryToTarget(\n queryImpl,\n queryNormalizedOrderBy(query)\n );\n }\n\n return queryImpl.memoizedTarget;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */\nexport function queryToAggregateTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n\n if (!queryImpl.memoizedAggregateTarget) {\n // Do not include implicit order-bys for aggregate queries.\n queryImpl.memoizedAggregateTarget = _queryToTarget(\n queryImpl,\n query.explicitOrderBy\n );\n }\n\n return queryImpl.memoizedAggregateTarget;\n}\n\nfunction _queryToTarget(queryImpl: QueryImpl, orderBys: OrderBy[]): Target {\n if (queryImpl.limitType === LimitType.First) {\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n queryImpl.startAt,\n queryImpl.endAt\n );\n } else {\n // Flip the orderBy directions since we want the last results\n orderBys = orderBys.map(orderBy => {\n const dir =\n orderBy.dir === Direction.DESCENDING\n ? Direction.ASCENDING\n : Direction.DESCENDING;\n return new OrderBy(orderBy.field, dir);\n });\n\n // We need to swap the cursors to match the now-flipped query ordering.\n const startAt = queryImpl.endAt\n ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)\n : null;\n const endAt = queryImpl.startAt\n ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)\n : null;\n\n // Now return as a LimitType.First query.\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n startAt,\n endAt\n );\n }\n}\n\nexport function queryWithAddedFilter(query: Query, filter: Filter): Query {\n debugAssert(\n !isDocumentQuery(query),\n 'No filtering allowed for document query'\n );\n\n const newFilters = query.filters.concat([filter]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n newFilters,\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query {\n debugAssert(\n !query.startAt && !query.endAt,\n 'Bounds must be set after orderBy'\n );\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const newOrderBy = query.explicitOrderBy.concat([orderBy]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n newOrderBy,\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithLimit(\n query: Query,\n limit: number | null,\n limitType: LimitType\n): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n limit,\n limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithStartAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n bound,\n query.endAt\n );\n}\n\nexport function queryWithEndAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n bound\n );\n}\n\nexport function queryEquals(left: Query, right: Query): boolean {\n return (\n targetEquals(queryToTarget(left), queryToTarget(right)) &&\n left.limitType === right.limitType\n );\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nexport function canonifyQuery(query: Query): string {\n return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;\n}\n\nexport function stringifyQuery(query: Query): string {\n return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${\n query.limitType\n })`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */\nexport function queryMatches(query: Query, doc: Document): boolean {\n return (\n doc.isFoundDocument() &&\n queryMatchesPathAndCollectionGroup(query, doc) &&\n queryMatchesOrderBy(query, doc) &&\n queryMatchesFilters(query, doc) &&\n queryMatchesBounds(query, doc)\n );\n}\n\nfunction queryMatchesPathAndCollectionGroup(\n query: Query,\n doc: Document\n): boolean {\n const docPath = doc.key.path;\n if (query.collectionGroup !== null) {\n // NOTE: this.path is currently always empty since we don't expose Collection\n // Group queries rooted at a document path yet.\n return (\n doc.key.hasCollectionId(query.collectionGroup) &&\n query.path.isPrefixOf(docPath)\n );\n } else if (DocumentKey.isDocumentKey(query.path)) {\n // exact match for document queries\n return query.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return query.path.isImmediateParentOf(docPath);\n }\n}\n\n/**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\nfunction queryMatchesOrderBy(query: Query, doc: Document): boolean {\n // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n // order-by key always matches\n if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {\n return false;\n }\n }\n return true;\n}\n\nfunction queryMatchesFilters(query: Query, doc: Document): boolean {\n for (const filter of query.filters) {\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n}\n\n/** Makes sure a document is within the bounds, if provided. */\nfunction queryMatchesBounds(query: Query, doc: Document): boolean {\n if (\n query.startAt &&\n !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n if (\n query.endAt &&\n !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */\nexport function queryCollectionGroup(query: Query): string {\n return (\n query.collectionGroup ||\n (query.path.length % 2 === 1\n ? query.path.lastSegment()\n : query.path.get(query.path.length - 2))\n );\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */\nexport function newQueryComparator(\n query: Query\n): (d1: Document, d2: Document) => number {\n return (d1: Document, d2: Document): number => {\n let comparedOnKeyField = false;\n for (const orderBy of queryNormalizedOrderBy(query)) {\n const comp = compareDocs(orderBy, d1, d2);\n if (comp !== 0) {\n return comp;\n }\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n debugAssert(\n comparedOnKeyField,\n \"orderBy used that doesn't compare on key field\"\n );\n return 0;\n };\n}\n\nexport function compareDocs(\n orderBy: OrderBy,\n d1: Document,\n d2: Document\n): number {\n const comparison = orderBy.field.isKeyField()\n ? DocumentKey.comparator(d1.key, d2.key)\n : compareDocumentsByField(orderBy.field, d1, d2);\n switch (orderBy.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + orderBy.dir);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { isNegativeZero, isSafeInteger } from '../util/types';\n\n/** Base interface for the Serializer implementation. */\nexport interface Serializer {\n readonly useProto3Json: boolean;\n}\n\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */\nexport function toDouble(serializer: Serializer, value: number): ProtoValue {\n if (serializer.useProto3Json) {\n if (isNaN(value)) {\n return { doubleValue: 'NaN' };\n } else if (value === Infinity) {\n return { doubleValue: 'Infinity' };\n } else if (value === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: isNegativeZero(value) ? '-0' : value };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */\nexport function toInteger(value: number): ProtoValue {\n return { integerValue: '' + value };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */\nexport function toNumber(serializer: Serializer, value: number): ProtoValue {\n return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Serializer, toDouble, toInteger } from '../remote/number_serializer';\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport { normalizeNumber } from './normalize';\nimport { serverTimestamp } from './server_timestamps';\nimport { isArray, isInteger, isNumber, valueEquals } from './values';\n\n/** Used to represent a field transform on a mutation. */\nexport class TransformOperation {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n private _ = undefined;\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */\nexport function applyTransformOperationToLocalView(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n localWriteTime: Timestamp\n): ProtoValue {\n if (transform instanceof ServerTimestampTransform) {\n return serverTimestamp(localWriteTime, previousValue);\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n } else {\n debugAssert(\n transform instanceof NumericIncrementTransformOperation,\n 'Expected NumericIncrementTransformOperation but was: ' + transform\n );\n return applyNumericIncrementTransformOperationToLocalView(\n transform,\n previousValue\n );\n }\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */\nexport function applyTransformOperationToRemoteDocument(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n transformResult: ProtoValue | null\n): ProtoValue {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n }\n\n debugAssert(\n transformResult !== null,\n \"Didn't receive transformResult for non-array transform\"\n );\n return transformResult;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */\nexport function computeTransformOperationBaseValue(\n transform: TransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue | null {\n if (transform instanceof NumericIncrementTransformOperation) {\n return isNumber(previousValue) ? previousValue! : { integerValue: 0 };\n }\n return null;\n}\n\nexport function transformOperationEquals(\n left: TransformOperation,\n right: TransformOperation\n): boolean {\n if (\n left instanceof ArrayUnionTransformOperation &&\n right instanceof ArrayUnionTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof ArrayRemoveTransformOperation &&\n right instanceof ArrayRemoveTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof NumericIncrementTransformOperation &&\n right instanceof NumericIncrementTransformOperation\n ) {\n return valueEquals(left.operand, right.operand);\n }\n\n return (\n left instanceof ServerTimestampTransform &&\n right instanceof ServerTimestampTransform\n );\n}\n\n/** Transforms a value into a server-generated timestamp. */\nexport class ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */\nexport class ArrayUnionTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayUnionTransformOperation(\n transform: ArrayUnionTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n const values = coercedFieldValuesArray(previousValue);\n for (const toUnion of transform.elements) {\n if (!values.some(element => valueEquals(element, toUnion))) {\n values.push(toUnion);\n }\n }\n return { arrayValue: { values } };\n}\n\n/** Transforms an array value via a remove operation. */\nexport class ArrayRemoveTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayRemoveTransformOperation(\n transform: ArrayRemoveTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n let values = coercedFieldValuesArray(previousValue);\n for (const toRemove of transform.elements) {\n values = values.filter(element => !valueEquals(element, toRemove));\n }\n return { arrayValue: { values } };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */\nexport class NumericIncrementTransformOperation extends TransformOperation {\n constructor(readonly serializer: Serializer, readonly operand: ProtoValue) {\n super();\n debugAssert(\n isNumber(operand),\n 'NumericIncrementTransform transform requires a NumberValue'\n );\n }\n}\n\nexport function applyNumericIncrementTransformOperationToLocalView(\n transform: NumericIncrementTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const baseValue = computeTransformOperationBaseValue(\n transform,\n previousValue\n )!;\n const sum = asNumber(baseValue) + asNumber(transform.operand);\n if (isInteger(baseValue) && isInteger(transform.operand)) {\n return toInteger(sum);\n } else {\n return toDouble(transform.serializer, sum);\n }\n}\n\nfunction asNumber(value: ProtoValue): number {\n return normalizeNumber(value.integerValue || value.doubleValue);\n}\n\nfunction coercedFieldValuesArray(value: ProtoValue | null): ProtoValue[] {\n return isArray(value) && value.arrayValue.values\n ? value.arrayValue.values.slice()\n : [];\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './field_mask';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport {\n applyTransformOperationToLocalView,\n applyTransformOperationToRemoteDocument,\n computeTransformOperationBaseValue,\n TransformOperation,\n transformOperationEquals\n} from './transform_operation';\n\n/** A field path and the TransformOperation to perform upon it. */\nexport class FieldTransform {\n constructor(\n readonly field: FieldPath,\n readonly transform: TransformOperation\n ) {}\n}\n\nexport function fieldTransformEquals(\n left: FieldTransform,\n right: FieldTransform\n): boolean {\n return (\n left.field.isEqual(right.field) &&\n transformOperationEquals(left.transform, right.transform)\n );\n}\n\nexport function fieldTransformsAreEqual(\n left?: FieldTransform[],\n right?: FieldTransform[]\n): boolean {\n if (left === undefined && right === undefined) {\n return true;\n }\n\n if (left && right) {\n return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r));\n }\n\n return false;\n}\n\n/** The result of successfully applying a mutation to the backend. */\nexport class MutationResult {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n readonly version: SnapshotVersion,\n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n readonly transformResults: Array\n ) {}\n}\n\nexport const enum MutationType {\n Set,\n Patch,\n Delete,\n Verify\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */\nexport class Precondition {\n private constructor(\n readonly updateTime?: SnapshotVersion,\n readonly exists?: boolean\n ) {\n debugAssert(\n updateTime === undefined || exists === undefined,\n 'Precondition can specify \"exists\" or \"updateTime\" but not both'\n );\n }\n\n /** Creates a new empty Precondition. */\n static none(): Precondition {\n return new Precondition();\n }\n\n /** Creates a new Precondition with an exists flag. */\n static exists(exists: boolean): Precondition {\n return new Precondition(undefined, exists);\n }\n\n /** Creates a new Precondition based on a version a document exists at. */\n static updateTime(version: SnapshotVersion): Precondition {\n return new Precondition(version);\n }\n\n /** Returns whether this Precondition is empty. */\n get isNone(): boolean {\n return this.updateTime === undefined && this.exists === undefined;\n }\n\n isEqual(other: Precondition): boolean {\n return (\n this.exists === other.exists &&\n (this.updateTime\n ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)\n : !other.updateTime)\n );\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */\nexport function preconditionIsValidForDocument(\n precondition: Precondition,\n document: MutableDocument\n): boolean {\n if (precondition.updateTime !== undefined) {\n return (\n document.isFoundDocument() &&\n document.version.isEqual(precondition.updateTime)\n );\n } else if (precondition.exists !== undefined) {\n return precondition.exists === document.isFoundDocument();\n } else {\n debugAssert(precondition.isNone, 'Precondition should be empty');\n return true;\n }\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */\nexport abstract class Mutation {\n abstract readonly type: MutationType;\n abstract readonly key: DocumentKey;\n abstract readonly precondition: Precondition;\n abstract readonly fieldTransforms: FieldTransform[];\n /**\n * Returns a `FieldMask` representing the fields that will be changed by\n * applying this mutation. Returns `null` if the mutation will overwrite the\n * entire document.\n */\n abstract getFieldMask(): FieldMask | null;\n}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */\nexport function calculateOverlayMutation(\n doc: MutableDocument,\n mask: FieldMask | null\n): Mutation | null {\n if (!doc.hasLocalMutations || (mask && mask!.fields.length === 0)) {\n return null;\n }\n\n // mask is null when sets or deletes are applied to the current document.\n if (mask === null) {\n if (doc.isNoDocument()) {\n return new DeleteMutation(doc.key, Precondition.none());\n } else {\n return new SetMutation(doc.key, doc.data, Precondition.none());\n }\n } else {\n const docValue = doc.data;\n const patchValue = ObjectValue.empty();\n let maskSet = new SortedSet(FieldPath.comparator);\n for (let path of mask.fields) {\n if (!maskSet.has(path)) {\n let value = docValue.field(path);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n if (value === null && path.length > 1) {\n path = path.popLast();\n value = docValue.field(path);\n }\n if (value === null) {\n patchValue.delete(path);\n } else {\n patchValue.set(path, value);\n }\n maskSet = maskSet.add(path);\n }\n }\n return new PatchMutation(\n doc.key,\n patchValue,\n new FieldMask(maskSet.toArray()),\n Precondition.none()\n );\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */\nexport function mutationApplyToRemoteDocument(\n mutation: Mutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n mutationVerifyKeyMatches(mutation, document);\n if (mutation instanceof SetMutation) {\n setMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else if (mutation instanceof PatchMutation) {\n patchMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n deleteMutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */\nexport function mutationApplyToLocalView(\n mutation: Mutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n mutationVerifyKeyMatches(mutation, document);\n\n if (mutation instanceof SetMutation) {\n return setMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else if (mutation instanceof PatchMutation) {\n return patchMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n return deleteMutationApplyToLocalView(mutation, document, previousMask);\n }\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */\nexport function mutationExtractBaseValue(\n mutation: Mutation,\n document: Document\n): ObjectValue | null {\n let baseObject: ObjectValue | null = null;\n for (const fieldTransform of mutation.fieldTransforms) {\n const existingValue = document.data.field(fieldTransform.field);\n const coercedValue = computeTransformOperationBaseValue(\n fieldTransform.transform,\n existingValue || null\n );\n\n if (coercedValue != null) {\n if (baseObject === null) {\n baseObject = ObjectValue.empty();\n }\n baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n return baseObject ? baseObject : null;\n}\n\nexport function mutationEquals(left: Mutation, right: Mutation): boolean {\n if (left.type !== right.type) {\n return false;\n }\n\n if (!left.key.isEqual(right.key)) {\n return false;\n }\n\n if (!left.precondition.isEqual(right.precondition)) {\n return false;\n }\n\n if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) {\n return false;\n }\n\n if (left.type === MutationType.Set) {\n return (left as SetMutation).value.isEqual((right as SetMutation).value);\n }\n\n if (left.type === MutationType.Patch) {\n return (\n (left as PatchMutation).data.isEqual((right as PatchMutation).data) &&\n (left as PatchMutation).fieldMask.isEqual(\n (right as PatchMutation).fieldMask\n )\n );\n }\n\n return true;\n}\n\nfunction mutationVerifyKeyMatches(\n mutation: Mutation,\n document: MutableDocument\n): void {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply a mutation to a document with the same key'\n );\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nexport class SetMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly value: ObjectValue,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Set;\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction setMutationApplyToRemoteDocument(\n mutation: SetMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const newData = mutation.value.clone();\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction setMutationApplyToLocalView(\n mutation: SetMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return previousMask;\n }\n\n const newData = mutation.value.clone();\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n return null; // SetMutation overwrites all fields.\n}\n\n/**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */\nexport class PatchMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Patch;\n\n getFieldMask(): FieldMask | null {\n return this.fieldMask;\n }\n}\n\nfunction patchMutationApplyToRemoteDocument(\n mutation: PatchMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n document.convertToUnknownDocument(mutationResult.version);\n return;\n }\n\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction patchMutationApplyToLocalView(\n mutation: PatchMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n return previousMask;\n }\n\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n\n if (previousMask === null) {\n return null;\n }\n\n return previousMask\n .unionWith(mutation.fieldMask.fields)\n .unionWith(mutation.fieldTransforms.map(transform => transform.field));\n}\n\n/**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */\nfunction getPatch(mutation: PatchMutation): Map {\n const result = new Map();\n mutation.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = mutation.data.field(fieldPath);\n result.set(fieldPath, newValue);\n }\n });\n return result;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */\nfunction serverTransformResults(\n fieldTransforms: FieldTransform[],\n mutableDocument: MutableDocument,\n serverTransformResults: Array\n): Map {\n const transformResults = new Map();\n hardAssert(\n fieldTransforms.length === serverTransformResults.length,\n `server transform result count (${serverTransformResults.length}) ` +\n `should match field transform count (${fieldTransforms.length})`\n );\n\n for (let i = 0; i < serverTransformResults.length; i++) {\n const fieldTransform = fieldTransforms[i];\n const transform = fieldTransform.transform;\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToRemoteDocument(\n transform,\n previousValue,\n serverTransformResults[i]\n )\n );\n }\n return transformResults;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */\nfunction localTransformResults(\n fieldTransforms: FieldTransform[],\n localWriteTime: Timestamp,\n mutableDocument: MutableDocument\n): Map {\n const transformResults = new Map();\n for (const fieldTransform of fieldTransforms) {\n const transform = fieldTransform.transform;\n\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToLocalView(\n transform,\n previousValue,\n localWriteTime\n )\n );\n }\n return transformResults;\n}\n\n/** A mutation that deletes the document at the given key. */\nexport class DeleteMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Delete;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction deleteMutationApplyToRemoteDocument(\n mutation: DeleteMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n debugAssert(\n mutationResult.transformResults.length === 0,\n 'Transform results received by DeleteMutation.'\n );\n\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n document\n .convertToNoDocument(mutationResult.version)\n .setHasCommittedMutations();\n}\n\nfunction deleteMutationApplyToLocalView(\n mutation: DeleteMutation,\n document: MutableDocument,\n previousMask: FieldMask | null\n): FieldMask | null {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply mutation to document with same key'\n );\n if (preconditionIsValidForDocument(mutation.precondition, document)) {\n document.convertToNoDocument(document.version).setHasLocalMutations();\n return null;\n }\n return previousMask;\n}\n\n/**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */\nexport class VerifyMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Verify;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Aggregate } from '../core/aggregate';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n compositeFilterIsFlatConjunction,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, Target } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n DeleteMutation,\n FieldTransform,\n Mutation,\n MutationResult,\n PatchMutation,\n Precondition,\n SetMutation,\n VerifyMutation\n} from '../model/mutation';\nimport { normalizeTimestamp } from '../model/normalize';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform,\n TransformOperation\n} from '../model/transform_operation';\nimport { isNanValue, isNullValue } from '../model/values';\nimport {\n ApiClientObjectMap as ProtoApiClientObjectMap,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n CompositeFilterOp as ProtoCompositeFilterOp,\n Cursor as ProtoCursor,\n Document as ProtoDocument,\n DocumentMask as ProtoDocumentMask,\n DocumentsTarget as ProtoDocumentsTarget,\n FieldFilterOp as ProtoFieldFilterOp,\n FieldReference as ProtoFieldReference,\n FieldTransform as ProtoFieldTransform,\n Filter as ProtoFilter,\n ListenResponse as ProtoListenResponse,\n Order as ProtoOrder,\n OrderDirection as ProtoOrderDirection,\n Precondition as ProtoPrecondition,\n QueryTarget as ProtoQueryTarget,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n Aggregation as ProtoAggregation,\n Status as ProtoStatus,\n Target as ProtoTarget,\n TargetChangeTargetChangeType as ProtoTargetChangeTargetChangeType,\n Timestamp as ProtoTimestamp,\n Write as ProtoWrite,\n WriteResult as ProtoWriteResult\n} from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExistenceFilter } from './existence_filter';\nimport { Serializer } from './number_serializer';\nimport { mapCodeFromRpcCode } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n const dirs: { [dir: string]: ProtoOrderDirection } = {};\n dirs[Direction.ASCENDING] = 'ASCENDING';\n dirs[Direction.DESCENDING] = 'DESCENDING';\n return dirs;\n})();\n\nconst OPERATORS = (() => {\n const ops: { [op: string]: ProtoFieldFilterOp } = {};\n ops[Operator.LESS_THAN] = 'LESS_THAN';\n ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';\n ops[Operator.GREATER_THAN] = 'GREATER_THAN';\n ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';\n ops[Operator.EQUAL] = 'EQUAL';\n ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';\n ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';\n ops[Operator.IN] = 'IN';\n ops[Operator.NOT_IN] = 'NOT_IN';\n ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';\n return ops;\n})();\n\nconst COMPOSITE_OPERATORS = (() => {\n const ops: { [op: string]: ProtoCompositeFilterOp } = {};\n ops[CompositeOperator.AND] = 'AND';\n ops[CompositeOperator.OR] = 'OR';\n return ops;\n})();\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n debugAssert(!isNullOrUndefined(value), description + ' is missing');\n}\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer implements Serializer {\n constructor(\n readonly databaseId: DatabaseId,\n readonly useProto3Json: boolean\n ) {}\n}\n\nfunction fromRpcStatus(status: ProtoStatus): FirestoreError {\n const code =\n status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: } struct.\n */\nfunction toInt32Proto(\n serializer: JsonProtoSerializer,\n val: number | null\n): number | { value: number } | null {\n if (serializer.useProto3Json || isNullOrUndefined(val)) {\n return val;\n } else {\n return { value: val };\n }\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\nfunction fromInt32Proto(\n val: number | { value: number } | undefined\n): number | null {\n let result;\n if (typeof val === 'object') {\n result = val.value;\n } else {\n result = val;\n }\n return isNullOrUndefined(result) ? null : result;\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nexport function toTimestamp(\n serializer: JsonProtoSerializer,\n timestamp: Timestamp\n): ProtoTimestamp {\n if (serializer.useProto3Json) {\n // Serialize to ISO-8601 date format, but with full nano resolution.\n // Since JS Date has only millis, let's only use it for the seconds and\n // then manually add the fractions to the end.\n const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();\n // Remove .xxx frac part and Z in the end.\n const strUntilSeconds = jsDateStr.replace(/\\.\\d*/, '').replace('Z', '');\n // Pad the fraction out to 9 digits (nanos).\n const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);\n\n return `${strUntilSeconds}.${nanoStr}Z`;\n } else {\n return {\n seconds: '' + timestamp.seconds,\n nanos: timestamp.nanoseconds\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n}\n\nfunction fromTimestamp(date: ProtoTimestamp): Timestamp {\n const timestamp = normalizeTimestamp(date);\n return new Timestamp(timestamp.seconds, timestamp.nanos);\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nexport function toBytes(\n serializer: JsonProtoSerializer,\n bytes: ByteString\n): string | Uint8Array {\n if (serializer.useProto3Json) {\n return bytes.toBase64();\n } else {\n return bytes.toUint8Array();\n }\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */\nexport function fromBytes(\n serializer: JsonProtoSerializer,\n value: string | Uint8Array | undefined\n): ByteString {\n if (serializer.useProto3Json) {\n hardAssert(\n value === undefined || typeof value === 'string',\n 'value must be undefined or a string when using proto3 Json'\n );\n return ByteString.fromBase64String(value ? value : '');\n } else {\n hardAssert(\n value === undefined || value instanceof Uint8Array,\n 'value must be undefined or Uint8Array'\n );\n return ByteString.fromUint8Array(value ? value : new Uint8Array());\n }\n}\n\nexport function toVersion(\n serializer: JsonProtoSerializer,\n version: SnapshotVersion\n): ProtoTimestamp {\n return toTimestamp(serializer, version.toTimestamp());\n}\n\nexport function fromVersion(version: ProtoTimestamp): SnapshotVersion {\n hardAssert(!!version, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(fromTimestamp(version));\n}\n\nexport function toResourceName(\n databaseId: DatabaseId,\n path: ResourcePath\n): string {\n return toResourcePath(databaseId, path).canonicalString();\n}\n\nexport function toResourcePath(\n databaseId: DatabaseId,\n path?: ResourcePath\n): ResourcePath {\n const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents');\n return path === undefined ? resourcePath : resourcePath.child(path);\n}\n\nfunction fromResourceName(name: string): ResourcePath {\n const resource = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resource),\n 'Tried to deserialize invalid key ' + resource.toString()\n );\n return resource;\n}\n\nexport function toName(\n serializer: JsonProtoSerializer,\n key: DocumentKey\n): string {\n return toResourceName(serializer.databaseId, key.path);\n}\n\nexport function fromName(\n serializer: JsonProtoSerializer,\n name: string\n): DocumentKey {\n const resource = fromResourceName(name);\n\n if (resource.get(1) !== serializer.databaseId.projectId) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n serializer.databaseId.projectId\n );\n }\n\n if (resource.get(3) !== serializer.databaseId.database) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n serializer.databaseId.database\n );\n }\n return new DocumentKey(extractLocalPathFromResourceName(resource));\n}\n\nfunction toQueryPath(\n serializer: JsonProtoSerializer,\n path: ResourcePath\n): string {\n return toResourceName(serializer.databaseId, path);\n}\n\nfunction fromQueryPath(name: string): ResourcePath {\n const resourceName = fromResourceName(name);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n if (resourceName.length === 4) {\n return ResourcePath.emptyPath();\n }\n return extractLocalPathFromResourceName(resourceName);\n}\n\nexport function getEncodedDatabaseId(serializer: JsonProtoSerializer): string {\n const path = new ResourcePath([\n 'projects',\n serializer.databaseId.projectId,\n 'databases',\n serializer.databaseId.database\n ]);\n return path.canonicalString();\n}\n\nfunction fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n}\n\nfunction extractLocalPathFromResourceName(\n resourceName: ResourcePath\n): ResourcePath {\n hardAssert(\n resourceName.length > 4 && resourceName.get(4) === 'documents',\n 'tried to deserialize invalid key ' + resourceName.toString()\n );\n return resourceName.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */\nexport function toMutationDocument(\n serializer: JsonProtoSerializer,\n key: DocumentKey,\n fields: ObjectValue\n): ProtoDocument {\n return {\n name: toName(serializer, key),\n fields: fields.value.mapValue.fields\n };\n}\n\nexport function toDocument(\n serializer: JsonProtoSerializer,\n document: MutableDocument\n): ProtoDocument {\n debugAssert(\n !document.hasLocalMutations,\n \"Can't serialize documents with mutations.\"\n );\n return {\n name: toName(serializer, document.key),\n fields: document.data.value.mapValue.fields,\n updateTime: toTimestamp(serializer, document.version.toTimestamp()),\n createTime: toTimestamp(serializer, document.createTime.toTimestamp())\n };\n}\n\nexport function fromDocument(\n serializer: JsonProtoSerializer,\n document: ProtoDocument,\n hasCommittedMutations?: boolean\n): MutableDocument {\n const key = fromName(serializer, document.name!);\n const version = fromVersion(document.updateTime!);\n // If we read a document from persistence that is missing createTime, it's due\n // to older SDK versions not storing this information. In such cases, we'll\n // set the createTime to zero. This can be removed in the long term.\n const createTime = document.createTime\n ? fromVersion(document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: document.fields } });\n const result = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n if (hasCommittedMutations) {\n result.setHasCommittedMutations();\n }\n return hasCommittedMutations ? result.setHasCommittedMutations() : result;\n}\n\nfunction fromFound(\n serializer: JsonProtoSerializer,\n doc: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!doc.found,\n 'Tried to deserialize a found document from a missing document.'\n );\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n const key = fromName(serializer, doc.found.name);\n const version = fromVersion(doc.found.updateTime);\n const createTime = doc.found.createTime\n ? fromVersion(doc.found.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });\n return MutableDocument.newFoundDocument(key, version, createTime, data);\n}\n\nfunction fromMissing(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!result.missing,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 'Tried to deserialize a missing document without a read time.'\n );\n const key = fromName(serializer, result.missing);\n const version = fromVersion(result.readTime);\n return MutableDocument.newNoDocument(key, version);\n}\n\nexport function fromBatchGetDocumentsResponse(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n if ('found' in result) {\n return fromFound(serializer, result);\n } else if ('missing' in result) {\n return fromMissing(serializer, result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n}\n\nexport function fromWatchChange(\n serializer: JsonProtoSerializer,\n change: ProtoListenResponse\n): WatchChange {\n let watchChange: WatchChange;\n if ('targetChange' in change) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const state = fromWatchTargetChangeState(\n change.targetChange.targetChangeType || 'NO_CHANGE'\n );\n const targetIds: TargetId[] = change.targetChange.targetIds || [];\n\n const resumeToken = fromBytes(serializer, change.targetChange.resumeToken);\n const causeProto = change.targetChange!.cause;\n const cause = causeProto && fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(\n state,\n targetIds,\n resumeToken,\n cause || null\n );\n } else if ('documentChange' in change) {\n assertPresent(change.documentChange, 'documentChange');\n const entityChange = change.documentChange;\n assertPresent(entityChange.document, 'documentChange.name');\n assertPresent(entityChange.document.name, 'documentChange.document.name');\n assertPresent(\n entityChange.document.updateTime,\n 'documentChange.document.updateTime'\n );\n const key = fromName(serializer, entityChange.document.name);\n const version = fromVersion(entityChange.document.updateTime);\n const createTime = entityChange.document.createTime\n ? fromVersion(entityChange.document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({\n mapValue: { fields: entityChange.document.fields }\n });\n const doc = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n const updatedTargetIds = entityChange.targetIds || [];\n const removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(\n updatedTargetIds,\n removedTargetIds,\n doc.key,\n doc\n );\n } else if ('documentDelete' in change) {\n assertPresent(change.documentDelete, 'documentDelete');\n const docDelete = change.documentDelete;\n assertPresent(docDelete.document, 'documentDelete.document');\n const key = fromName(serializer, docDelete.document);\n const version = docDelete.readTime\n ? fromVersion(docDelete.readTime)\n : SnapshotVersion.min();\n const doc = MutableDocument.newNoDocument(key, version);\n const removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n } else if ('documentRemove' in change) {\n assertPresent(change.documentRemove, 'documentRemove');\n const docRemove = change.documentRemove;\n assertPresent(docRemove.document, 'documentRemove');\n const key = fromName(serializer, docRemove.document);\n const removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n } else if ('filter' in change) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n const filter = change.filter;\n assertPresent(filter.targetId, 'filter.targetId');\n const { count = 0, unchangedNames } = filter;\n const existenceFilter = new ExistenceFilter(count, unchangedNames);\n const targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n } else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n return watchChange;\n}\n\nfunction fromWatchTargetChangeState(\n state: ProtoTargetChangeTargetChangeType\n): WatchTargetChangeState {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n } else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n } else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n } else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n } else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n } else {\n return fail('Got unexpected TargetChange.state: ' + state);\n }\n}\n\nexport function versionFromListenResponse(\n change: ProtoListenResponse\n): SnapshotVersion {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!('targetChange' in change)) {\n return SnapshotVersion.min();\n }\n const targetChange = change.targetChange!;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.min();\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.min();\n }\n return fromVersion(targetChange.readTime);\n}\n\nexport function toMutation(\n serializer: JsonProtoSerializer,\n mutation: Mutation\n): ProtoWrite {\n let result: ProtoWrite;\n if (mutation instanceof SetMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = { delete: toName(serializer, mutation.key) };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.data),\n updateMask: toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof VerifyMutation) {\n result = {\n verify: toName(serializer, mutation.key)\n };\n } else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n\n if (mutation.fieldTransforms.length > 0) {\n result.updateTransforms = mutation.fieldTransforms.map(transform =>\n toFieldTransform(serializer, transform)\n );\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = toPrecondition(serializer, mutation.precondition);\n }\n\n return result;\n}\n\nexport function fromMutation(\n serializer: JsonProtoSerializer,\n proto: ProtoWrite\n): Mutation {\n const precondition = proto.currentDocument\n ? fromPrecondition(proto.currentDocument)\n : Precondition.none();\n\n const fieldTransforms = proto.updateTransforms\n ? proto.updateTransforms.map(transform =>\n fromFieldTransform(serializer, transform)\n )\n : [];\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n const key = fromName(serializer, proto.update.name);\n const value = new ObjectValue({\n mapValue: { fields: proto.update.fields }\n });\n\n if (proto.updateMask) {\n const fieldMask = fromDocumentMask(proto.updateMask);\n return new PatchMutation(\n key,\n value,\n fieldMask,\n precondition,\n fieldTransforms\n );\n } else {\n return new SetMutation(key, value, precondition, fieldTransforms);\n }\n } else if (proto.delete) {\n const key = fromName(serializer, proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.verify) {\n const key = fromName(serializer, proto.verify);\n return new VerifyMutation(key, precondition);\n } else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n}\n\nfunction toPrecondition(\n serializer: JsonProtoSerializer,\n precondition: Precondition\n): ProtoPrecondition {\n debugAssert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: toVersion(serializer, precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n } else {\n return fail('Unknown precondition');\n }\n}\n\nfunction fromPrecondition(precondition: ProtoPrecondition): Precondition {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.none();\n }\n}\n\nfunction fromWriteResult(\n proto: ProtoWriteResult,\n commitTime: ProtoTimestamp\n): MutationResult {\n // NOTE: Deletes don't have an updateTime.\n let version = proto.updateTime\n ? fromVersion(proto.updateTime)\n : fromVersion(commitTime);\n\n if (version.isEqual(SnapshotVersion.min())) {\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n version = fromVersion(commitTime);\n }\n\n return new MutationResult(version, proto.transformResults || []);\n}\n\nexport function fromWriteResults(\n protos: ProtoWriteResult[] | undefined,\n commitTime?: ProtoTimestamp\n): MutationResult[] {\n if (protos && protos.length > 0) {\n hardAssert(\n commitTime !== undefined,\n 'Received a write result without a commit time'\n );\n return protos.map(proto => fromWriteResult(proto, commitTime));\n } else {\n return [];\n }\n}\n\nfunction toFieldTransform(\n serializer: JsonProtoSerializer,\n fieldTransform: FieldTransform\n): ProtoFieldTransform {\n const transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n appendMissingElements: {\n values: transform.elements\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements\n }\n };\n } else if (transform instanceof NumericIncrementTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n increment: transform.operand\n };\n } else {\n throw fail('Unknown transform: ' + fieldTransform.transform);\n }\n}\n\nfunction fromFieldTransform(\n serializer: JsonProtoSerializer,\n proto: ProtoFieldTransform\n): FieldTransform {\n let transform: TransformOperation | null = null;\n if ('setToServerValue' in proto) {\n hardAssert(\n proto.setToServerValue === 'REQUEST_TIME',\n 'Unknown server value transform proto: ' + JSON.stringify(proto)\n );\n transform = new ServerTimestampTransform();\n } else if ('appendMissingElements' in proto) {\n const values = proto.appendMissingElements!.values || [];\n transform = new ArrayUnionTransformOperation(values);\n } else if ('removeAllFromArray' in proto) {\n const values = proto.removeAllFromArray!.values || [];\n transform = new ArrayRemoveTransformOperation(values);\n } else if ('increment' in proto) {\n transform = new NumericIncrementTransformOperation(\n serializer,\n proto.increment!\n );\n } else {\n fail('Unknown transform proto: ' + JSON.stringify(proto));\n }\n const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);\n return new FieldTransform(fieldPath, transform!);\n}\n\nexport function toDocumentsTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): ProtoDocumentsTarget {\n return { documents: [toQueryPath(serializer, target.path)] };\n}\n\nexport function fromDocumentsTarget(\n documentsTarget: ProtoDocumentsTarget\n): Target {\n const count = documentsTarget.documents!.length;\n hardAssert(\n count === 1,\n 'DocumentsTarget contained other than 1 document: ' + count\n );\n const name = documentsTarget.documents![0];\n return queryToTarget(newQueryForPath(fromQueryPath(name)));\n}\n\nexport function toQueryTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): { queryTarget: ProtoQueryTarget; parent: ResourcePath } {\n // Dissect the path into parent, collectionId, and optional key filter.\n const queryTarget: ProtoQueryTarget = { structuredQuery: {} };\n const path = target.path;\n let parent: ResourcePath;\n if (target.collectionGroup !== null) {\n debugAssert(\n path.length % 2 === 0,\n 'Collection Group queries should be within a document path or root.'\n );\n parent = path;\n queryTarget.structuredQuery!.from = [\n {\n collectionId: target.collectionGroup,\n allDescendants: true\n }\n ];\n } else {\n debugAssert(\n path.length % 2 !== 0,\n 'Document queries with filters are not supported.'\n );\n parent = path.popLast();\n queryTarget.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n }\n queryTarget.parent = toQueryPath(serializer, parent);\n\n const where = toFilters(target.filters);\n if (where) {\n queryTarget.structuredQuery!.where = where;\n }\n\n const orderBy = toOrder(target.orderBy);\n if (orderBy) {\n queryTarget.structuredQuery!.orderBy = orderBy;\n }\n\n const limit = toInt32Proto(serializer, target.limit);\n if (limit !== null) {\n queryTarget.structuredQuery!.limit = limit;\n }\n\n if (target.startAt) {\n queryTarget.structuredQuery!.startAt = toStartAtCursor(target.startAt);\n }\n if (target.endAt) {\n queryTarget.structuredQuery!.endAt = toEndAtCursor(target.endAt);\n }\n\n return { queryTarget, parent };\n}\n\nexport function toRunAggregationQueryRequest(\n serializer: JsonProtoSerializer,\n target: Target,\n aggregates: Aggregate[]\n): {\n request: ProtoRunAggregationQueryRequest;\n aliasMap: Record;\n parent: ResourcePath;\n} {\n const { queryTarget, parent } = toQueryTarget(serializer, target);\n const aliasMap: Record = {};\n\n const aggregations: ProtoAggregation[] = [];\n let aggregationNum = 0;\n\n aggregates.forEach(aggregate => {\n // Map all client-side aliases to a unique short-form\n // alias. This avoids issues with client-side aliases that\n // exceed the 1500-byte string size limit.\n const serverAlias = `aggregate_${aggregationNum++}`;\n aliasMap[serverAlias] = aggregate.alias;\n\n if (aggregate.aggregateType === 'count') {\n aggregations.push({\n alias: serverAlias,\n count: {}\n });\n } else if (aggregate.aggregateType === 'avg') {\n aggregations.push({\n alias: serverAlias,\n avg: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n } else if (aggregate.aggregateType === 'sum') {\n aggregations.push({\n alias: serverAlias,\n sum: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n }\n });\n\n return {\n request: {\n structuredAggregationQuery: {\n aggregations,\n structuredQuery: queryTarget.structuredQuery\n },\n parent: queryTarget.parent\n },\n aliasMap,\n parent\n };\n}\n\nexport function convertQueryTargetToQuery(target: ProtoQueryTarget): Query {\n let path = fromQueryPath(target.parent!);\n\n const query = target.structuredQuery!;\n const fromCount = query.from ? query.from.length : 0;\n let collectionGroup: string | null = null;\n if (fromCount > 0) {\n hardAssert(\n fromCount === 1,\n 'StructuredQuery.from with more than one collection is not supported.'\n );\n const from = query.from![0];\n if (from.allDescendants) {\n collectionGroup = from.collectionId!;\n } else {\n path = path.child(from.collectionId!);\n }\n }\n\n let filterBy: Filter[] = [];\n if (query.where) {\n filterBy = fromFilters(query.where);\n }\n\n let orderBy: OrderBy[] = [];\n if (query.orderBy) {\n orderBy = fromOrder(query.orderBy);\n }\n\n let limit: number | null = null;\n if (query.limit) {\n limit = fromInt32Proto(query.limit);\n }\n\n let startAt: Bound | null = null;\n if (query.startAt) {\n startAt = fromStartAtCursor(query.startAt);\n }\n\n let endAt: Bound | null = null;\n if (query.endAt) {\n endAt = fromEndAtCursor(query.endAt);\n }\n\n return newQuery(\n path,\n collectionGroup,\n orderBy,\n filterBy,\n limit,\n LimitType.First,\n startAt,\n endAt\n );\n}\n\nexport function fromQueryTarget(target: ProtoQueryTarget): Target {\n return queryToTarget(convertQueryTargetToQuery(target));\n}\n\nexport function toListenRequestLabels(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoApiClientObjectMap | null {\n const value = toLabel(targetData.purpose);\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n}\n\nexport function toLabel(purpose: TargetPurpose): string | null {\n switch (purpose) {\n case TargetPurpose.Listen:\n return null;\n case TargetPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case TargetPurpose.ExistenceFilterMismatchBloom:\n return 'existence-filter-mismatch-bloom';\n case TargetPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n}\n\nexport function toTarget(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoTarget {\n let result: ProtoTarget;\n const target = targetData.target;\n\n if (targetIsDocumentTarget(target)) {\n result = { documents: toDocumentsTarget(serializer, target) };\n } else {\n result = { query: toQueryTarget(serializer, target).queryTarget };\n }\n\n result.targetId = targetData.targetId;\n\n if (targetData.resumeToken.approximateByteSize() > 0) {\n result.resumeToken = toBytes(serializer, targetData.resumeToken);\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n } else if (targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n result.readTime = toTimestamp(\n serializer,\n targetData.snapshotVersion.toTimestamp()\n );\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n }\n\n return result;\n}\n\nfunction toFilters(filters: Filter[]): ProtoFilter | undefined {\n if (filters.length === 0) {\n return;\n }\n\n return toFilter(CompositeFilter.create(filters, CompositeOperator.AND));\n}\n\nfunction fromFilters(filter: ProtoFilter): Filter[] {\n const result = fromFilter(filter);\n\n if (\n result instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(result)\n ) {\n return result.getFilters();\n }\n\n return [result];\n}\n\nfunction fromFilter(filter: ProtoFilter): Filter {\n if (filter.unaryFilter !== undefined) {\n return fromUnaryFilter(filter);\n } else if (filter.fieldFilter !== undefined) {\n return fromFieldFilter(filter);\n } else if (filter.compositeFilter !== undefined) {\n return fromCompositeFilter(filter);\n } else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n}\n\nfunction toOrder(orderBys: OrderBy[]): ProtoOrder[] | undefined {\n if (orderBys.length === 0) {\n return;\n }\n return orderBys.map(order => toPropertyOrder(order));\n}\n\nfunction fromOrder(orderBys: ProtoOrder[]): OrderBy[] {\n return orderBys.map(order => fromPropertyOrder(order));\n}\n\nfunction toStartAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction toEndAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: !cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction fromStartAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !!cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\nfunction fromEndAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\n// visible for testing\nexport function toDirection(dir: Direction): ProtoOrderDirection {\n return DIRECTIONS[dir];\n}\n\n// visible for testing\nexport function fromDirection(\n dir: ProtoOrderDirection | undefined\n): Direction | undefined {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n}\n\n// visible for testing\nexport function toOperatorName(op: Operator): ProtoFieldFilterOp {\n return OPERATORS[op];\n}\n\nexport function toCompositeOperatorName(\n op: CompositeOperator\n): ProtoCompositeFilterOp {\n return COMPOSITE_OPERATORS[op];\n}\n\nexport function fromOperatorName(op: ProtoFieldFilterOp): Operator {\n switch (op) {\n case 'EQUAL':\n return Operator.EQUAL;\n case 'NOT_EQUAL':\n return Operator.NOT_EQUAL;\n case 'GREATER_THAN':\n return Operator.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return Operator.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return Operator.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return Operator.LESS_THAN_OR_EQUAL;\n case 'ARRAY_CONTAINS':\n return Operator.ARRAY_CONTAINS;\n case 'IN':\n return Operator.IN;\n case 'NOT_IN':\n return Operator.NOT_IN;\n case 'ARRAY_CONTAINS_ANY':\n return Operator.ARRAY_CONTAINS_ANY;\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified operator');\n default:\n return fail('Unknown operator');\n }\n}\n\nexport function fromCompositeOperatorName(\n op: ProtoCompositeFilterOp\n): CompositeOperator {\n switch (op) {\n case 'AND':\n return CompositeOperator.AND;\n case 'OR':\n return CompositeOperator.OR;\n default:\n return fail('Unknown operator');\n }\n}\n\nexport function toFieldPathReference(path: FieldPath): ProtoFieldReference {\n return { fieldPath: path.canonicalString() };\n}\n\nexport function fromFieldPathReference(\n fieldReference: ProtoFieldReference\n): FieldPath {\n return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n}\n\n// visible for testing\nexport function toPropertyOrder(orderBy: OrderBy): ProtoOrder {\n return {\n field: toFieldPathReference(orderBy.field),\n direction: toDirection(orderBy.dir)\n };\n}\n\nexport function fromPropertyOrder(orderBy: ProtoOrder): OrderBy {\n return new OrderBy(\n fromFieldPathReference(orderBy.field!),\n fromDirection(orderBy.direction)\n );\n}\n\n// visible for testing\nexport function toFilter(filter: Filter): ProtoFilter {\n if (filter instanceof FieldFilter) {\n return toUnaryOrFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return toCompositeFilter(filter);\n } else {\n return fail('Unrecognized filter type ' + JSON.stringify(filter));\n }\n}\n\nexport function toCompositeFilter(filter: CompositeFilter): ProtoFilter {\n const protos = filter.getFilters().map(filter => toFilter(filter));\n\n if (protos.length === 1) {\n return protos[0];\n }\n\n return {\n compositeFilter: {\n op: toCompositeOperatorName(filter.op),\n filters: protos\n }\n };\n}\n\nexport function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter {\n if (filter.op === Operator.EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n } else if (filter.op === Operator.NOT_EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NULL'\n }\n };\n }\n }\n return {\n fieldFilter: {\n field: toFieldPathReference(filter.field),\n op: toOperatorName(filter.op),\n value: filter.value\n }\n };\n}\n\nexport function fromUnaryFilter(filter: ProtoFilter): Filter {\n switch (filter.unaryFilter!.op!) {\n case 'IS_NAN':\n const nanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nanField, Operator.EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NULL':\n const nullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nullField, Operator.EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'IS_NOT_NAN':\n const notNanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNanField, Operator.NOT_EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NOT_NULL':\n const notNullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNullField, Operator.NOT_EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n}\n\nexport function fromFieldFilter(filter: ProtoFilter): FieldFilter {\n return FieldFilter.create(\n fromFieldPathReference(filter.fieldFilter!.field!),\n fromOperatorName(filter.fieldFilter!.op!),\n filter.fieldFilter!.value!\n );\n}\n\nexport function fromCompositeFilter(filter: ProtoFilter): CompositeFilter {\n return CompositeFilter.create(\n filter.compositeFilter!.filters!.map(filter => fromFilter(filter)),\n fromCompositeOperatorName(filter.compositeFilter!.op!)\n );\n}\n\nexport function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask {\n const canonicalFields: string[] = [];\n fieldMask.fields.forEach(field =>\n canonicalFields.push(field.canonicalString())\n );\n return {\n fieldPaths: canonicalFields\n };\n}\n\nexport function fromDocumentMask(proto: ProtoDocumentMask): FieldMask {\n const paths = proto.fieldPaths || [];\n return new FieldMask(paths.map(path => FieldPath.fromServerFormat(path)));\n}\n\nexport function isValidResourceName(path: ResourcePath): boolean {\n // Resource names have at least 4 components (project ID, database ID)\n return (\n path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases'\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Return the Platform-specific serializer monitor. */\nimport { DatabaseId } from '../../core/database_info';\nimport { JsonProtoSerializer } from '../../remote/serializer';\n\nexport function newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nconst LOG_TAG = 'ExponentialBackoff';\n\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nconst DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;\n\nconst DEFAULT_BACKOFF_FACTOR = 1.5;\n\n/** Maximum backoff time in milliseconds */\nconst DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;\n\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nexport class ExponentialBackoff {\n private currentBaseMs: number = 0;\n private timerPromise: DelayedOperation | null = null;\n /** The last backoff attempt, as epoch milliseconds. */\n private lastAttemptTime = Date.now();\n\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n private readonly queue: AsyncQueue,\n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n private readonly timerId: TimerId,\n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n private readonly initialDelayMs: number = DEFAULT_BACKOFF_INITIAL_DELAY_MS,\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n private readonly backoffFactor: number = DEFAULT_BACKOFF_FACTOR,\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */\n private readonly maxDelayMs: number = DEFAULT_BACKOFF_MAX_DELAY_MS\n ) {\n this.reset();\n }\n\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */\n reset(): void {\n this.currentBaseMs = 0;\n }\n\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n resetToMax(): void {\n this.currentBaseMs = this.maxDelayMs;\n }\n\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */\n backoffAndRun(op: () => Promise): void {\n // Cancel any pending backoff operation.\n this.cancel();\n\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const desiredDelayWithJitterMs = Math.floor(\n this.currentBaseMs + this.jitterDelayMs()\n );\n\n // Guard against lastAttemptTime being in the future due to a clock change.\n const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\n\n // Guard against the backoff delay already being past.\n const remainingDelayMs = Math.max(\n 0,\n desiredDelayWithJitterMs - delaySoFarMs\n );\n\n if (remainingDelayMs > 0) {\n logDebug(\n LOG_TAG,\n `Backing off for ${remainingDelayMs} ms ` +\n `(base delay: ${this.currentBaseMs} ms, ` +\n `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +\n `last attempt: ${delaySoFarMs} ms ago)`\n );\n }\n\n this.timerPromise = this.queue.enqueueAfterDelay(\n this.timerId,\n remainingDelayMs,\n () => {\n this.lastAttemptTime = Date.now();\n return op();\n }\n );\n\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n }\n\n skipBackoff(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.skipDelay();\n this.timerPromise = null;\n }\n }\n\n cancel(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n }\n\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n private jitterDelayMs(): number {\n return (Math.random() - 0.5) * this.currentBaseMs;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { Aggregate } from '../core/aggregate';\nimport { DatabaseId } from '../core/database_info';\nimport { queryToAggregateTarget, Query, queryToTarget } from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport {\n ApiClientObjectMap,\n BatchGetDocumentsRequest as ProtoBatchGetDocumentsRequest,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n RunAggregationQueryResponse as ProtoRunAggregationQueryResponse,\n RunQueryRequest as ProtoRunQueryRequest,\n RunQueryResponse as ProtoRunQueryResponse,\n Value\n} from '../protos/firestore_proto_api';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Connection } from './connection';\nimport {\n PersistentListenStream,\n PersistentWriteStream,\n WatchStreamListener,\n WriteStreamListener\n} from './persistent_stream';\nimport {\n fromDocument,\n fromBatchGetDocumentsResponse,\n JsonProtoSerializer,\n toMutation,\n toName,\n toQueryTarget,\n toResourcePath,\n toRunAggregationQueryRequest\n} from './serializer';\n\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\nexport abstract class Datastore {\n abstract terminate(): void;\n abstract serializer: JsonProtoSerializer;\n}\n\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass DatastoreImpl extends Datastore {\n terminated = false;\n\n constructor(\n readonly authCredentials: CredentialsProvider,\n readonly appCheckCredentials: CredentialsProvider,\n readonly connection: Connection,\n readonly serializer: JsonProtoSerializer\n ) {\n super();\n }\n\n verifyInitialized(): void {\n debugAssert(!!this.connection, 'Datastore.start() not called');\n if (this.terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n /** Invokes the provided RPC with auth and AppCheck tokens. */\n invokeRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */\n invokeStreamingRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req,\n expectedResponseCount?: number\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeStreamingRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken,\n expectedResponseCount\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n terminate(): void {\n this.terminated = true;\n this.connection.terminate();\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nexport function newDatastore(\n authCredentials: CredentialsProvider,\n appCheckCredentials: CredentialsProvider,\n connection: Connection,\n serializer: JsonProtoSerializer\n): Datastore {\n return new DatastoreImpl(\n authCredentials,\n appCheckCredentials,\n connection,\n serializer\n );\n}\n\nexport async function invokeCommitRpc(\n datastore: Datastore,\n mutations: Mutation[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))\n };\n await datastoreImpl.invokeRPC(\n 'Commit',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request\n );\n}\n\nexport async function invokeBatchGetDocumentsRpc(\n datastore: Datastore,\n keys: DocumentKey[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n documents: keys.map(k => toName(datastoreImpl.serializer, k))\n };\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoBatchGetDocumentsRequest,\n ProtoBatchGetDocumentsResponse\n >(\n 'BatchGetDocuments',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request,\n keys.length\n );\n\n const docs = new Map();\n response.forEach(proto => {\n const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);\n docs.set(doc.key.toString(), doc);\n });\n const result: Document[] = [];\n keys.forEach(key => {\n const doc = docs.get(key.toString());\n hardAssert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n}\n\nexport async function invokeRunQueryRpc(\n datastore: Datastore,\n query: Query\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { queryTarget, parent } = toQueryTarget(\n datastoreImpl.serializer,\n queryToTarget(query)\n );\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunQueryRequest,\n ProtoRunQueryResponse\n >('RunQuery', datastoreImpl.serializer.databaseId, parent, {\n structuredQuery: queryTarget.structuredQuery\n });\n return (\n response\n // Omit RunQueryResponses that only contain readTimes.\n .filter(proto => !!proto.document)\n .map(proto =>\n fromDocument(datastoreImpl.serializer, proto.document!, undefined)\n )\n );\n}\n\nexport async function invokeRunAggregationQueryRpc(\n datastore: Datastore,\n query: Query,\n aggregates: Aggregate[]\n): Promise> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { request, aliasMap, parent } = toRunAggregationQueryRequest(\n datastoreImpl.serializer,\n queryToAggregateTarget(query),\n aggregates\n );\n\n if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {\n delete request.parent;\n }\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunAggregationQueryRequest,\n ProtoRunAggregationQueryResponse\n >(\n 'RunAggregationQuery',\n datastoreImpl.serializer.databaseId,\n parent,\n request,\n /*expectedResponseCount=*/ 1\n );\n\n // Omit RunAggregationQueryResponse that only contain readTimes.\n const filteredResult = response.filter(proto => !!proto.result);\n\n hardAssert(\n filteredResult.length === 1,\n 'Aggregation fields are missing from result.'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result),\n 'aggregationQueryResponse.result'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result.aggregateFields),\n 'aggregationQueryResponse.result.aggregateFields'\n );\n\n // Remap the short-form aliases that were sent to the server\n // to the client-side aliases. Users will access the results\n // using the client-side alias.\n const unmappedAggregateFields = filteredResult[0].result?.aggregateFields;\n const remappedFields = Object.keys(unmappedAggregateFields).reduce<\n ApiClientObjectMap\n >((accumulator, key) => {\n debugAssert(\n !isNullOrUndefined(aliasMap[key]),\n `'${key}' not present in aliasMap result`\n );\n accumulator[aliasMap[key]] = unmappedAggregateFields[key]!;\n return accumulator;\n }, {});\n\n return remappedFields;\n}\n\nexport function newPersistentWriteStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WriteStreamListener\n): PersistentWriteStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentWriteStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n\nexport function newPersistentWatchStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WatchStreamListener\n): PersistentListenStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentListenStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { _FirebaseService } from '@firebase/app';\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { cloneLongPollingOptions } from '../api/long_polling_options';\nimport { User } from '../auth/user';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { newConnection } from '../platform/connection';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { FirestoreSettingsImpl } from './settings';\n\nexport const LOG_TAG = 'ComponentProvider';\n\n// The components module manages the lifetime of dependencies of the Firestore\n// client. Dependencies can be lazily constructed and only one exists per\n// Firestore instance.\n\n/**\n * An interface implemented by FirebaseFirestore that provides compatibility\n * with the usage in this file.\n *\n * This interface mainly exists to remove a cyclic dependency.\n */\nexport interface FirestoreService extends _FirebaseService {\n _authCredentials: CredentialsProvider;\n _appCheckCredentials: CredentialsProvider;\n _persistenceKey: string;\n _databaseId: DatabaseId;\n _terminated: boolean;\n\n _freezeSettings(): FirestoreSettingsImpl;\n}\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\nconst datastoreInstances = new Map();\n\n/**\n * Returns an initialized and started Datastore for the given Firestore\n * instance. Callers must invoke removeComponents() when the Firestore\n * instance is terminated.\n */\nexport function getDatastore(firestore: FirestoreService): Datastore {\n if (firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n if (!datastoreInstances.has(firestore)) {\n logDebug(LOG_TAG, 'Initializing Datastore');\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore.app.options.appId || '',\n firestore._persistenceKey,\n firestore._freezeSettings()\n );\n const connection = newConnection(databaseInfo);\n const serializer = newSerializer(firestore._databaseId);\n const datastore = newDatastore(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n connection,\n serializer\n );\n\n datastoreInstances.set(firestore, datastore);\n }\n return datastoreInstances.get(firestore)!;\n}\n\n/**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\nexport function removeComponents(firestore: FirestoreService): void {\n const datastore = datastoreInstances.get(firestore);\n if (datastore) {\n logDebug(LOG_TAG, 'Removing Datastore');\n datastoreInstances.delete(firestore);\n datastore.terminate();\n }\n}\n\nexport function makeDatabaseInfo(\n databaseId: DatabaseId,\n appId: string,\n persistenceKey: string,\n settings: FirestoreSettingsImpl\n): DatabaseInfo {\n return new DatabaseInfo(\n databaseId,\n appId,\n persistenceKey,\n settings.host,\n settings.ssl,\n settings.experimentalForceLongPolling,\n settings.experimentalAutoDetectLongPolling,\n cloneLongPollingOptions(settings.experimentalLongPollingOptions),\n settings.useFetchStreams\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Connection } from '../../remote/connection';\n\nimport { FetchConnection } from './fetch_connection';\n\nexport { newConnectivityMonitor } from '../browser/connection';\n\n/** Initializes the HTTP connection for the REST API. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new FetchConnection(databaseInfo, fetch.bind(null));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreLocalCache } from '../api/cache_config';\nimport { CredentialsSettings } from '../api/credentials';\nimport {\n ExperimentalLongPollingOptions,\n cloneLongPollingOptions,\n longPollingOptionsEqual\n} from '../api/long_polling_options';\nimport {\n LRU_COLLECTION_DISABLED,\n LRU_DEFAULT_CACHE_SIZE_BYTES\n} from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { validateIsNotUsedTogether } from '../util/input_validation';\n\n// settings() defaults:\nexport const DEFAULT_HOST = 'firestore.googleapis.com';\nexport const DEFAULT_SSL = true;\n\n// The minimum long-polling timeout is hardcoded on the server. The value here\n// should be kept in sync with the value used by the server, as the server will\n// silently ignore a value below the minimum and fall back to the default.\n// Googlers see b/266868871 for relevant discussion.\nconst MIN_LONG_POLLING_TIMEOUT_SECONDS = 5;\n\n// No maximum long-polling timeout is configured in the server, and defaults to\n// 30 seconds, which is what Watch appears to use.\n// Googlers see b/266868871 for relevant discussion.\nconst MAX_LONG_POLLING_TIMEOUT_SECONDS = 30;\n\n// Whether long-polling auto-detected is enabled by default.\nconst DEFAULT_AUTO_DETECT_LONG_POLLING = true;\n\n/**\n * Specifies custom configurations for your Cloud Firestore instance.\n * You must set these before invoking any other methods.\n */\nexport interface FirestoreSettings {\n /** The hostname to connect to. */\n host?: string;\n\n /** Whether to use SSL when connecting. */\n ssl?: boolean;\n\n /**\n * Whether to skip nested properties that are set to `undefined` during\n * object serialization. If set to `true`, these properties are skipped\n * and not written to Firestore. If set to `false` or omitted, the SDK\n * throws an exception when it encounters properties of type `undefined`.\n */\n ignoreUndefinedProperties?: boolean;\n}\n\n/**\n * @internal\n * Undocumented, private additional settings not exposed in our public API.\n */\nexport interface PrivateSettings extends FirestoreSettings {\n // Can be a google-auth-library or gapi client.\n credentials?: CredentialsSettings;\n cacheSizeBytes?: number;\n experimentalForceLongPolling?: boolean;\n experimentalAutoDetectLongPolling?: boolean;\n experimentalLongPollingOptions?: ExperimentalLongPollingOptions;\n useFetchStreams?: boolean;\n\n localCache?: FirestoreLocalCache;\n}\n\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nexport class FirestoreSettingsImpl {\n /** The hostname to connect to. */\n readonly host: string;\n\n /** Whether to use SSL when connecting. */\n readonly ssl: boolean;\n\n readonly cacheSizeBytes: number;\n\n readonly experimentalForceLongPolling: boolean;\n\n readonly experimentalAutoDetectLongPolling: boolean;\n\n readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions;\n\n readonly ignoreUndefinedProperties: boolean;\n\n readonly useFetchStreams: boolean;\n readonly localCache?: FirestoreLocalCache;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/**\n * Describes a map whose keys are active target ids. We do not care about the type of the\n * values.\n */\nexport type ActiveTargets = SortedMap;\n\nexport const GC_DID_NOT_RUN: LruResults = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nexport const LRU_COLLECTION_DISABLED = -1;\nexport const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n\nexport class LruParams {\n private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n static withCacheSize(cacheSize: number): LruParams {\n return new LruParams(\n cacheSize,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n }\n\n static readonly DEFAULT: LruParams = new LruParams(\n LRU_DEFAULT_CACHE_SIZE_BYTES,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n\n static readonly DISABLED: LruParams = new LruParams(\n LRU_COLLECTION_DISABLED,\n 0,\n 0\n );\n\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n readonly cacheSizeCollectionThreshold: number,\n // The percentage of sequence numbers that we will attempt to collect\n readonly percentileToCollect: number,\n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n readonly maximumSequenceNumbersToCollect: number\n ) {}\n}\n\nexport interface LruGarbageCollector {\n readonly params: LruParams;\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /** Given a percentile of target to collect, returns the number of targets to collect. */\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise;\n\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise;\n\n /**\n * Removes documents that have a sequence number equal to or less than the\n * upper bound and are not otherwise pinned.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\n\n /**\n * Removes targets with a sequence number equal to or less than the given\n * upper bound, and removes document associations with those targets.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n}\n\n/**\n * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n readonly didRun: boolean;\n readonly sequenceNumbersCollected: number;\n readonly targetsRemoved: number;\n readonly documentsRemoved: number;\n}\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have\n * reference delegates that implement this interface. This interface defines the\n * operations that the LRU garbage collector needs from the persistence layer.\n */\nexport interface LruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n /** Enumerates all the targets in the TargetCache. */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (target: TargetData) => void\n ): PersistencePromise;\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise;\n\n /**\n * Enumerates sequence numbers for documents not associated with a target.\n * Note that this may include duplicate sequence numbers.\n */\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise;\n\n /**\n * Removes all targets that have a sequence number less than or equal to\n * `upperBound`, and are not present in the `activeTargetIds` set.\n *\n * @returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /**\n * Removes all unreferenced documents from the cache that have a sequence\n * number less than or equal to the given `upperBound`.\n *\n * @returns the number of documents removed.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet = new SortedSet(\n bufferEntryComparator\n );\n\n private previousIndex = 0;\n\n constructor(private readonly maxElements: number) {}\n\n private nextIndex(): number {\n return ++this.previousIndex;\n }\n\n addElement(sequenceNumber: ListenSequenceNumber): void {\n const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n if (this.buffer.size < this.maxElements) {\n this.buffer = this.buffer.add(entry);\n } else {\n const highestValue = this.buffer.last()!;\n if (bufferEntryComparator(entry, highestValue) < 0) {\n this.buffer = this.buffer.delete(highestValue).add(entry);\n }\n }\n }\n\n get maxValue(): ListenSequenceNumber {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()![0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */\nexport class LruScheduler implements Scheduler {\n private gcTask: DelayedOperation | null;\n\n constructor(\n private readonly garbageCollector: LruGarbageCollector,\n private readonly asyncQueue: AsyncQueue,\n private readonly localStore: LocalStore\n ) {\n this.gcTask = null;\n }\n\n start(): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot start an already started LruScheduler'\n );\n if (\n this.garbageCollector.params.cacheSizeCollectionThreshold !==\n LRU_COLLECTION_DISABLED\n ) {\n this.scheduleGC(INITIAL_GC_DELAY_MS);\n }\n }\n\n stop(): void {\n if (this.gcTask) {\n this.gcTask.cancel();\n this.gcTask = null;\n }\n }\n\n get started(): boolean {\n return this.gcTask !== null;\n }\n\n private scheduleGC(delay: number): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot schedule GC while a task is pending'\n );\n logDebug(LOG_TAG, `Garbage collection scheduled in ${delay}ms`);\n this.gcTask = this.asyncQueue.enqueueAfterDelay(\n TimerId.LruGarbageCollection,\n delay,\n async () => {\n this.gcTask = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during garbage collection: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.scheduleGC(REGULAR_GC_DELAY_MS);\n }\n );\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */\nclass LruGarbageCollectorImpl implements LruGarbageCollector {\n constructor(\n private readonly delegate: LruDelegate,\n readonly params: LruParams\n ) {}\n\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise {\n return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n return Math.floor((percentile / 100.0) * targetCount);\n });\n }\n\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise {\n if (n === 0) {\n return PersistencePromise.resolve(ListenSequence.INVALID);\n }\n\n const buffer = new RollingSequenceNumberBuffer(n);\n return this.delegate\n .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n .next(() => {\n return this.delegate.forEachOrphanedDocumentSequenceNumber(\n txn,\n sequenceNumber => buffer.addElement(sequenceNumber)\n );\n })\n .next(() => buffer.maxValue);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n }\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) {\n logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\n }\n\n return this.getCacheSize(txn).next(cacheSize => {\n if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n logDebug(\n 'LruGarbageCollector',\n `Garbage collection skipped; Cache size ${cacheSize} ` +\n `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n );\n return GC_DID_NOT_RUN;\n } else {\n return this.runGarbageCollection(txn, activeTargetIds);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.delegate.getCacheSize(txn);\n }\n\n private runGarbageCollection(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let upperBoundSequenceNumber: number;\n let sequenceNumbersToCollect: number, targetsRemoved: number;\n // Timestamps for various pieces of the process\n let countedTargetsTs: number,\n foundUpperBoundTs: number,\n removedTargetsTs: number,\n removedDocumentsTs: number;\n const startTs = Date.now();\n return this.calculateTargetCount(txn, this.params.percentileToCollect)\n .next(sequenceNumbers => {\n // Cap at the configured max\n if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n logDebug(\n 'LruGarbageCollector',\n 'Capping sequence numbers to collect down ' +\n `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n `from ${sequenceNumbers}`\n );\n sequenceNumbersToCollect =\n this.params.maximumSequenceNumbersToCollect;\n } else {\n sequenceNumbersToCollect = sequenceNumbers;\n }\n countedTargetsTs = Date.now();\n\n return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n })\n .next(upperBound => {\n upperBoundSequenceNumber = upperBound;\n foundUpperBoundTs = Date.now();\n\n return this.removeTargets(\n txn,\n upperBoundSequenceNumber,\n activeTargetIds\n );\n })\n .next(numTargetsRemoved => {\n targetsRemoved = numTargetsRemoved;\n removedTargetsTs = Date.now();\n\n return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n })\n .next(documentsRemoved => {\n removedDocumentsTs = Date.now();\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n const desc =\n 'LRU Garbage Collection\\n' +\n `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n `\\tRemoved ${targetsRemoved} targets in ` +\n `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n `\\tRemoved ${documentsRemoved} documents in ` +\n `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n `Total Duration: ${removedDocumentsTs - startTs}ms`;\n logDebug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved,\n documentsRemoved\n });\n });\n }\n}\n\nexport function newLruGarbageCollector(\n delegate: LruDelegate,\n params: LruParams\n): LruGarbageCollector {\n return new LruGarbageCollectorImpl(delegate, params);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\n\nimport {\n CredentialsProvider,\n EmulatorAuthCredentialsProvider,\n makeAuthCredentialsProvider,\n OAuthToken\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { FirestoreService, removeComponents } from './components';\nimport {\n DEFAULT_HOST,\n FirestoreSettingsImpl,\n PrivateSettings,\n FirestoreSettings\n} from './settings';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore implements FirestoreService {\n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore-lite';\n\n readonly _persistenceKey: string = '(lite)';\n\n private _settings = new FirestoreSettingsImpl({});\n private _settingsFrozen = false;\n\n // A task that is assigned when the terminate() is invoked and resolved when\n // all components have shut down.\n private _terminateTask?: Promise;\n\n /** @hideconstructor */\n constructor(\n public _authCredentials: CredentialsProvider,\n public _appCheckCredentials: CredentialsProvider,\n readonly _databaseId: DatabaseId,\n readonly _app?: FirebaseApp\n ) {}\n\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */\n get app(): FirebaseApp {\n if (!this._app) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._app;\n }\n\n get _initialized(): boolean {\n return this._settingsFrozen;\n }\n\n get _terminated(): boolean {\n return this._terminateTask !== undefined;\n }\n\n _setSettings(settings: PrivateSettings): void {\n if (this._settingsFrozen) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only modify settings before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n this._settings = new FirestoreSettingsImpl(settings);\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _freezeSettings(): FirestoreSettingsImpl {\n this._settingsFrozen = true;\n return this._settings;\n }\n\n _delete(): Promise {\n if (!this._terminateTask) {\n this._terminateTask = this._terminate();\n }\n return this._terminateTask;\n }\n\n /** Returns a JSON-serializable representation of this `Firestore` instance. */\n toJSON(): object {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */\n protected _terminate(): Promise {\n removeComponents(this);\n return Promise.resolve();\n }\n}\n\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @returns A newly initialized `Firestore` instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings\n): Firestore;\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized `Firestore` instance.\n * @beta\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore;\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore/lite');\n\n if (provider.isInitialized(databaseId)) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore can only be initialized once per app.'\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || '(default)';\n const db = _getProvider(app, 'firestore/lite').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */\nexport function connectFirestoreEmulator(\n firestore: Firestore,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n firestore = cast(firestore, Firestore);\n const settings = firestore._getSettings();\n const newHostSetting = `${host}:${port}`;\n\n if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {\n logWarn(\n 'Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +\n 'will be used.'\n );\n }\n\n firestore._setSettings({\n ...settings,\n host: newHostSetting,\n ssl: false\n });\n\n if (options.mockUserToken) {\n let token: string;\n let user: User;\n if (typeof options.mockUserToken === 'string') {\n token = options.mockUserToken;\n user = User.MOCK_USER;\n } else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n token = createMockUserToken(\n options.mockUserToken,\n firestore._app?.options.projectId\n );\n const uid = options.mockUserToken.sub || options.mockUserToken.user_id;\n if (!uid) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"mockUserToken must contain 'sub' or 'user_id' field!\"\n );\n }\n user = new User(uid);\n }\n\n firestore._authCredentials = new EmulatorAuthCredentialsProvider(\n new OAuthToken(token, user)\n );\n }\n}\n\n/**\n * Terminates the provided `Firestore` instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` functions\n * may be used. Any other function will throw a `FirestoreError`. Termination\n * does not cancel any pending writes, and any promises that are awaiting a\n * response from the server will not be resolved.\n *\n * To restart after termination, create a new instance of `Firestore` with\n * {@link (getFirestore:1)}.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all of\n * its resources or in combination with {@link clearIndexedDbPersistence} to\n * ensure that all local state is destroyed between test runs.\n *\n * @param firestore - The `Firestore` instance to terminate.\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise {\n firestore = cast(firestore, Firestore);\n _removeServiceInstance(firestore.app, 'firestore/lite');\n return firestore._delete();\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n newQueryForCollectionGroup,\n newQueryForPath,\n Query as InternalQuery,\n queryEquals\n} from '../core/query';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n cast,\n validateCollectionPath,\n validateDocumentPath,\n validateNonEmptyArgument\n} from '../util/input_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { FirestoreDataConverter } from './snapshot';\nimport { NestedUpdateFields, Primitive } from './types';\n\n/**\n * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to\n * values.\n */\nexport interface DocumentData {\n /** A mapping between a field and its value. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [field: string]: any;\n}\n\n/**\n * Similar to Typescript's `Partial`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue =\n | Partial\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: PartialWithFieldValue | FieldValue }\n : never);\n\n/**\n * Allows FieldValues to be passed in as a property value while maintaining\n * type safety.\n */\nexport type WithFieldValue =\n | T\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]: WithFieldValue | FieldValue }\n : never);\n\n/**\n * Update data (for use with {@link (updateDoc:1)}) that consists of field paths\n * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots\n * reference nested fields within the document. FieldValues can be passed in\n * as property values.\n */\nexport type UpdateData = T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: UpdateData | FieldValue } & NestedUpdateFields\n : Partial;\n/**\n * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link\n * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a `SetOptions` with `merge: true`.\n *\n * @param merge - Changes the behavior of a `setDoc()` call to only replace the\n * values specified in its data argument. Fields omitted from the `setDoc()`\n * call remain untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace\n * the specified field paths. Any field path that is not specified is ignored\n * and remains untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n */\nexport type SetOptions =\n | {\n readonly merge?: boolean;\n }\n | {\n readonly mergeFields?: Array;\n };\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */\nexport class Query<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type: 'query' | 'collection' = 'query';\n\n /**\n * The `Firestore` instance for the Firestore database (useful for performing\n * transactions, etc.).\n */\n readonly firestore: Firestore;\n\n // This is the lite version of the Query class in the main SDK.\n\n /** @hideconstructor protected */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _query: InternalQuery\n ) {\n this.firestore = firestore;\n }\n\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `Query` that does not use a\n * converter.\n */\n withConverter(converter: null): Query;\n /**\n * Applies a custom data converter to this query, allowing you to use your own\n * custom model objects with Firestore. When you call {@link getDocs} with\n * the returned query, the provided converter will convert between Firestore\n * data of type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `Query` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): Query;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): Query {\n return new Query(\n this.firestore,\n converter,\n this._query\n );\n }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */\nexport class DocumentReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type = 'document';\n\n /**\n * The {@link Firestore} instance the document is in.\n * This is useful for performing transactions, for example.\n */\n readonly firestore: Firestore;\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _key: DocumentKey\n ) {\n this.firestore = firestore;\n }\n\n get _path(): ResourcePath {\n return this._key.path;\n }\n\n /**\n * The document's identifier within its collection.\n */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n get path(): string {\n return this._key.path.canonicalString();\n }\n\n /**\n * The collection this `DocumentReference` belongs to.\n */\n get parent(): CollectionReference {\n return new CollectionReference(\n this.firestore,\n this.converter,\n this._key.path.popLast()\n );\n }\n\n /**\n * Applies a custom data converter to this `DocumentReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`\n * instance, the provided converter will convert between Firestore data of\n * type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `DocumentReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): DocumentReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `DocumentReference` that does not\n * use a converter.\n */\n withConverter(converter: null): DocumentReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): DocumentReference {\n return new DocumentReference(\n this.firestore,\n converter,\n this._key\n );\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */\nexport class CollectionReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends Query {\n /** The type of this Firestore reference. */\n readonly type = 'collection';\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n converter: FirestoreDataConverter | null,\n readonly _path: ResourcePath\n ) {\n super(firestore, converter, newQueryForPath(_path));\n }\n\n /** The collection's identifier. */\n get id(): string {\n return this._query.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */\n get path(): string {\n return this._query.path.canonicalString();\n }\n\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */\n get parent(): DocumentReference | null {\n const parentPath = this._path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference(\n this.firestore,\n /* converter= */ null,\n new DocumentKey(parentPath)\n );\n }\n }\n\n /**\n * Applies a custom data converter to this `CollectionReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * addDoc} with the returned `CollectionReference` instance, the provided\n * converter will convert between Firestore data of type `NewDbModelType` and\n * your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `CollectionReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): CollectionReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `CollectionReference` that does not\n * use a converter.\n */\n withConverter(\n converter: null\n ): CollectionReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): CollectionReference {\n return new CollectionReference(\n this.firestore,\n converter,\n this._path\n );\n }\n}\n\n/**\n * Gets a `CollectionReference` instance that refers to the collection at\n * the specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the the specified relative path.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\nexport function collection(\n parent:\n | Firestore\n | DocumentReference\n | CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference {\n parent = getModularInstance(parent);\n\n validateNonEmptyArgument('collection', 'path', path);\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateCollectionPath(absolutePath);\n return new CollectionReference(parent, /* converter= */ null, absolutePath);\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateCollectionPath(absolutePath);\n return new CollectionReference(\n parent.firestore,\n /* converter= */ null,\n absolutePath\n );\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */\nexport function collectionGroup(\n firestore: Firestore,\n collectionId: string\n): Query {\n firestore = cast(firestore, Firestore);\n\n validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);\n if (collectionId.indexOf('/') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection ID '${collectionId}' passed to function ` +\n `collectionGroup(). Collection IDs must not contain '/'.`\n );\n }\n\n return new Query(\n firestore,\n /* converter= */ null,\n newQueryForCollectionGroup(collectionId)\n );\n}\n\n/**\n * Gets a `DocumentReference` instance that refers to the document at the\n * specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path. If no path is specified, an\n * automatically-generated unique ID will be used for the returned\n * `DocumentReference`.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a document. Has to be omitted to use\n * auto-genrated IDs.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: CollectionReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\nexport function doc(\n parent:\n | Firestore\n | CollectionReference\n | DocumentReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference {\n parent = getModularInstance(parent);\n\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 1) {\n path = AutoId.newId();\n }\n validateNonEmptyArgument('doc', 'path', path);\n\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent,\n /* converter= */ null,\n new DocumentKey(absolutePath)\n );\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent.firestore,\n parent instanceof CollectionReference ? parent.converter : null,\n new DocumentKey(absolutePath)\n );\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function refEqual(\n left:\n | DocumentReference\n | CollectionReference,\n right:\n | DocumentReference\n | CollectionReference\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (\n (left instanceof DocumentReference ||\n left instanceof CollectionReference) &&\n (right instanceof DocumentReference || right instanceof CollectionReference)\n ) {\n return (\n left.firestore === right.firestore &&\n left.path === right.path &&\n left.converter === right.converter\n );\n }\n return false;\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function queryEqual(\n left: Query,\n right: Query\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof Query && right instanceof Query) {\n return (\n left.firestore === right.firestore &&\n queryEquals(left._query, right._query) &&\n left.converter === right.converter\n );\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * An immutable object representing an array of bytes.\n */\nexport class Bytes {\n _byteString: ByteString;\n\n /** @hideconstructor */\n constructor(byteString: ByteString) {\n this._byteString = byteString;\n }\n\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */\n static fromBase64String(base64: string): Bytes {\n try {\n return new Bytes(ByteString.fromBase64String(base64));\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to construct data from Base64 string: ' + e\n );\n }\n }\n\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */\n static fromUint8Array(array: Uint8Array): Bytes {\n return new Bytes(ByteString.fromUint8Array(array));\n }\n\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */\n toBase64(): string {\n return this._byteString.toBase64();\n }\n\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */\n toUint8Array(): Uint8Array {\n return this._byteString.toUint8Array();\n }\n\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */\n toString(): string {\n return 'Bytes(base64: ' + this.toBase64() + ')';\n }\n\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */\n isEqual(other: Bytes): boolean {\n return this._byteString.isEqual(other._byteString);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DOCUMENT_KEY_NAME,\n FieldPath as InternalFieldPath\n} from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */\nexport class FieldPath {\n /** Internal representation of a Firestore field path. */\n readonly _internalPath: InternalFieldPath;\n\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...fieldNames: string[]) {\n for (let i = 0; i < fieldNames.length; ++i) {\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field name at argument $(i + 1). ` +\n 'Field names must not be empty.'\n );\n }\n }\n\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */\n isEqual(other: FieldPath): boolean {\n return this._internalPath.isEqual(other._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */\nexport function documentId(): FieldPath {\n return new FieldPath(DOCUMENT_KEY_NAME);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport { FieldTransform } from '../model/mutation';\n\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */\nexport abstract class FieldValue {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(public _methodName: string) {}\n\n /** Compares `FieldValue`s for equality. */\n abstract isEqual(other: FieldValue): boolean;\n abstract _toFieldTransform(context: ParseContext): FieldTransform | null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */\nexport class GeoPoint {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion when typing latitude or longitude.\n private _lat: number;\n private _long: number;\n\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(latitude: number, longitude: number) {\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Latitude must be a number between -90 and 90, but was: ' + latitude\n );\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Longitude must be a number between -180 and 180, but was: ' + longitude\n );\n }\n\n this._lat = latitude;\n this._long = longitude;\n }\n\n /**\n * The latitude of this `GeoPoint` instance.\n */\n get latitude(): number {\n return this._lat;\n }\n\n /**\n * The longitude of this `GeoPoint` instance.\n */\n get longitude(): number {\n return this._long;\n }\n\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */\n isEqual(other: GeoPoint): boolean {\n return this._lat === other._lat && this._long === other._long;\n }\n\n /** Returns a JSON-serializable representation of this GeoPoint. */\n toJSON(): { latitude: number; longitude: number } {\n return { latitude: this._lat, longitude: this._long };\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: GeoPoint): number {\n return (\n primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport { newSerializer } from '../platform/serializer';\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { toNumber } from '../remote/number_serializer';\nimport {\n JsonProtoSerializer,\n toBytes,\n toResourceName,\n toTimestamp\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { Dict, forEach, isEmpty } from '../util/obj';\n\nimport { Bytes } from './bytes';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { GeoPoint } from './geo_point';\nimport {\n DocumentReference,\n PartialWithFieldValue,\n WithFieldValue\n} from './reference';\nimport { Timestamp } from './timestamp';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/**\n * An untyped Firestore Data Converter interface that is shared between the\n * lite, firestore-exp and classic SDK.\n */\nexport interface UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n fromFirestore(snapshot: unknown, options?: unknown): AppModelType;\n}\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask | null,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n if (this.fieldMask !== null) {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n } else {\n return new SetMutation(\n key,\n this.data,\n precondition,\n this.fieldTransforms\n );\n }\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n constructor(\n readonly data: ObjectValue,\n // The fieldMask does not include document transforms.\n readonly fieldMask: FieldMask,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nexport const enum UserDataSource {\n Set,\n Update,\n MergeSet,\n /**\n * Indicates the source is a where clause, cursor bound, arrayUnion()\n * element, etc. Of note, isWrite(source) will return false.\n */\n Argument,\n /**\n * Indicates that the source is an Argument that may directly contain nested\n * arrays (e.g. the operand of an `in` query).\n */\n ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.Argument:\n case UserDataSource.ArrayArgument:\n return false;\n default:\n throw fail(`Unexpected case for UserDataSource: ${dataSource}`);\n }\n}\n\n/** Contains the settings that are mutated as we parse user data. */\ninterface ContextSettings {\n /** Indicates what kind of API method this data came from. */\n readonly dataSource: UserDataSource;\n /** The name of the method the user called to create the ParseContext. */\n readonly methodName: string;\n /** The document the user is attempting to modify, if that applies. */\n readonly targetDoc?: DocumentKey;\n /**\n * A path within the object being parsed. This could be an empty path (in\n * which case the context represents the root of the data being parsed), or a\n * nonempty path (indicating the context represents a nested location within\n * the data).\n */\n readonly path?: InternalFieldPath;\n /**\n * Whether or not this context corresponds to an element of an array.\n * If not set, elements are treated as if they were outside of arrays.\n */\n readonly arrayElement?: boolean;\n /**\n * Whether or not a converter was specified in this context. If true, error\n * messages will reference the converter when invalid data is provided.\n */\n readonly hasConverter?: boolean;\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContextImpl implements ParseContext {\n readonly fieldTransforms: FieldTransform[];\n readonly fieldMask: InternalFieldPath[];\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(\n readonly settings: ContextSettings,\n readonly databaseId: DatabaseId,\n readonly serializer: JsonProtoSerializer,\n readonly ignoreUndefinedProperties: boolean,\n fieldTransforms?: FieldTransform[],\n fieldMask?: InternalFieldPath[]\n ) {\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n get path(): InternalFieldPath | undefined {\n return this.settings.path;\n }\n\n get dataSource(): UserDataSource {\n return this.settings.dataSource;\n }\n\n /** Returns a new context with the specified settings overwritten. */\n contextWith(configuration: Partial): ParseContextImpl {\n return new ParseContextImpl(\n { ...this.settings, ...configuration },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties,\n this.fieldTransforms,\n this.fieldMask\n );\n }\n\n childContextForField(field: string): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePathSegment(field);\n return context;\n }\n\n childContextForFieldPath(field: InternalFieldPath): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePath();\n return context;\n }\n\n childContextForArray(index: number): ParseContextImpl {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.contextWith({ path: undefined, arrayElement: true });\n }\n\n createError(reason: string): FirestoreError {\n return createError(\n reason,\n this.settings.methodName,\n this.settings.hasConverter || false,\n this.path,\n this.settings.targetDoc\n );\n }\n\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n contains(fieldPath: InternalFieldPath): boolean {\n return (\n this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n this.fieldTransforms.find(transform =>\n fieldPath.isPrefixOf(transform.field)\n ) !== undefined\n );\n }\n\n private validatePath(): void {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (!this.path) {\n return;\n }\n for (let i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n }\n\n private validatePathSegment(segment: string): void {\n if (segment.length === 0) {\n throw this.createError('Document fields must not be empty');\n }\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with \"__\"');\n }\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataReader {\n private readonly serializer: JsonProtoSerializer;\n\n constructor(\n private readonly databaseId: DatabaseId,\n private readonly ignoreUndefinedProperties: boolean,\n serializer?: JsonProtoSerializer\n ) {\n this.serializer = serializer || newSerializer(databaseId);\n }\n\n /** Creates a new top-level parse context. */\n createContext(\n dataSource: UserDataSource,\n methodName: string,\n targetDoc?: DocumentKey,\n hasConverter = false\n ): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource,\n methodName,\n targetDoc,\n path: InternalFieldPath.emptyPath(),\n arrayElement: false,\n hasConverter\n },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties\n );\n }\n}\n\nexport function newUserDataReader(firestore: Firestore): UserDataReader {\n const settings = firestore._freezeSettings();\n const serializer = newSerializer(firestore._databaseId);\n return new UserDataReader(\n firestore._databaseId,\n !!settings.ignoreUndefinedProperties,\n serializer\n );\n}\n\n/** Parse document data from a set() call. */\nexport function parseSetData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown,\n hasConverter: boolean,\n options: SetOptions = {}\n): ParsedSetData {\n const context = userDataReader.createContext(\n options.merge || options.mergeFields\n ? UserDataSource.MergeSet\n : UserDataSource.Set,\n methodName,\n targetDoc,\n hasConverter\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n const updateData = parseObject(input, context)!;\n\n let fieldMask: FieldMask | null;\n let fieldTransforms: FieldTransform[];\n\n if (options.merge) {\n fieldMask = new FieldMask(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else if (options.mergeFields) {\n const validatedFieldPaths: InternalFieldPath[] = [];\n\n for (const stringOrFieldPath of options.mergeFields) {\n const fieldPath = fieldPathFromArgument(\n methodName,\n stringOrFieldPath,\n targetDoc\n );\n if (!context.contains(fieldPath)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Field '${fieldPath}' is specified in your field mask but missing from your input data.`\n );\n }\n\n if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {\n validatedFieldPaths.push(fieldPath);\n }\n }\n\n fieldMask = new FieldMask(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(transform =>\n fieldMask!.covers(transform.field)\n );\n } else {\n fieldMask = null;\n fieldTransforms = context.fieldTransforms;\n }\n\n return new ParsedSetData(\n new ObjectValue(updateData),\n fieldMask,\n fieldTransforms\n );\n}\n\nexport class DeleteFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): null {\n if (context.dataSource === UserDataSource.MergeSet) {\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n context.fieldMask.push(context.path!);\n } else if (context.dataSource === UserDataSource.Update) {\n debugAssert(\n context.path!.length > 0,\n `${this._methodName}() at the top level should have already ` +\n 'been handled.'\n );\n throw context.createError(\n `${this._methodName}() can only appear at the top level ` +\n 'of your update data'\n );\n } else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError(\n `${this._methodName}() cannot be used with set() unless you pass ` +\n '{merge:true}'\n );\n }\n return null;\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof DeleteFieldValueImpl;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */\nfunction createSentinelChildContext(\n fieldValue: FieldValue,\n context: ParseContextImpl,\n arrayElement: boolean\n): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource: UserDataSource.Argument,\n targetDoc: context.settings.targetDoc,\n methodName: fieldValue._methodName,\n arrayElement\n },\n context.databaseId,\n context.serializer,\n context.ignoreUndefinedProperties\n );\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n return new FieldTransform(context.path!, new ServerTimestampTransform());\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof ServerTimestampFieldValueImpl;\n }\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayUnionFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayRemoveFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _operand: number) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const numericIncrement = new NumericIncrementTransformOperation(\n context.serializer,\n toNumber(context.serializer, this._operand)\n );\n return new FieldTransform(context.path!, numericIncrement);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof NumericIncrementFieldValueImpl &&\n this._operand === other._operand\n );\n }\n}\n\n/** Parse update data from an update() call. */\nexport function parseUpdateData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n forEach(input as Dict, (key, value) => {\n const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */\nexport function parseUpdateVarargs(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n field: string | PublicFieldPath | Compat,\n value: unknown,\n moreFieldsAndValues: unknown[]\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n const keys = [fieldPathFromArgument(methodName, field, targetDoc)];\n const values = [value];\n\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() needs to be called with an even number ` +\n 'of arguments that alternate between field names and values.'\n );\n }\n\n for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(\n fieldPathFromArgument(\n methodName,\n moreFieldsAndValues[i] as string | PublicFieldPath\n )\n );\n values.push(moreFieldsAndValues[i + 1]);\n }\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let i = keys.length - 1; i >= 0; --i) {\n if (!fieldMaskContains(fieldMaskPaths, keys[i])) {\n const path = keys[i];\n let value = values[i];\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n }\n }\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */\nexport function parseQueryValue(\n userDataReader: UserDataReader,\n methodName: string,\n input: unknown,\n allowArrays = false\n): ProtoValue {\n const context = userDataReader.createContext(\n allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n methodName\n );\n const parsed = parseData(input, context);\n debugAssert(parsed != null, 'Parsed data should not be null.');\n debugAssert(\n context.fieldTransforms.length === 0,\n 'Field transforms should have been disallowed.'\n );\n return parsed;\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\nexport function parseData(\n input: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n input = getModularInstance(input);\n\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return parseObject(input, context);\n } else if (input instanceof FieldValue) {\n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n parseSentinelFieldValue(input, context);\n return null;\n } else if (input === undefined && context.ignoreUndefinedProperties) {\n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n } else {\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (\n context.settings.arrayElement &&\n context.dataSource !== UserDataSource.ArrayArgument\n ) {\n throw context.createError('Nested arrays are not supported');\n }\n return parseArray(input as unknown[], context);\n } else {\n return parseScalarValue(input, context);\n }\n }\n}\n\nfunction parseObject(\n obj: Dict,\n context: ParseContextImpl\n): { mapValue: ProtoMapValue } {\n const fields: Dict = {};\n\n if (isEmpty(obj)) {\n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n if (context.path && context.path.length > 0) {\n context.fieldMask.push(context.path);\n }\n } else {\n forEach(obj, (key: string, val: unknown) => {\n const parsedValue = parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n fields[key] = parsedValue;\n }\n });\n }\n\n return { mapValue: { fields } };\n}\n\nfunction parseArray(array: unknown[], context: ParseContextImpl): ProtoValue {\n const values: ProtoValue[] = [];\n let entryIndex = 0;\n for (const entry of array) {\n let parsedEntry = parseData(\n entry,\n context.childContextForArray(entryIndex)\n );\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = { nullValue: 'NULL_VALUE' };\n }\n values.push(parsedEntry);\n entryIndex++;\n }\n return { arrayValue: { values } };\n}\n\n/**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\nfunction parseSentinelFieldValue(\n value: FieldValue,\n context: ParseContextImpl\n): void {\n // Sentinels are only supported with writes, and not within arrays.\n if (!isWrite(context.dataSource)) {\n throw context.createError(\n `${value._methodName}() can only be used with update() and set()`\n );\n }\n if (!context.path) {\n throw context.createError(\n `${value._methodName}() is not currently supported inside arrays`\n );\n }\n\n const fieldTransform = value._toFieldTransform(context);\n if (fieldTransform) {\n context.fieldTransforms.push(fieldTransform);\n }\n}\n\n/**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */\nfunction parseScalarValue(\n value: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n value = getModularInstance(value);\n\n if (value === null) {\n return { nullValue: 'NULL_VALUE' };\n } else if (typeof value === 'number') {\n return toNumber(context.serializer, value);\n } else if (typeof value === 'boolean') {\n return { booleanValue: value };\n } else if (typeof value === 'string') {\n return { stringValue: value };\n } else if (value instanceof Date) {\n const timestamp = Timestamp.fromDate(value);\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof Timestamp) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const timestamp = new Timestamp(\n value.seconds,\n Math.floor(value.nanoseconds / 1000) * 1000\n );\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof GeoPoint) {\n return {\n geoPointValue: {\n latitude: value.latitude,\n longitude: value.longitude\n }\n };\n } else if (value instanceof Bytes) {\n return { bytesValue: toBytes(context.serializer, value._byteString) };\n } else if (value instanceof DocumentReference) {\n const thisDb = context.databaseId;\n const otherDb = value.firestore._databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw context.createError(\n 'Document reference is for database ' +\n `${otherDb.projectId}/${otherDb.database} but should be ` +\n `for database ${thisDb.projectId}/${thisDb.database}`\n );\n }\n return {\n referenceValue: toResourceName(\n value.firestore._databaseId || context.databaseId,\n value._key.path\n )\n };\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\n );\n }\n}\n\n/**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */\nfunction looksLikeJsonObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof Timestamp) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Bytes) &&\n !(input instanceof DocumentReference) &&\n !(input instanceof FieldValue)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContextImpl,\n input: unknown\n): asserts input is Dict {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n const description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n } else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n path: string | PublicFieldPath | Compat,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n // If required, replace the FieldPath Compat class with with the firestore-exp\n // FieldPath.\n path = getModularInstance(path);\n\n if (path instanceof FieldPath) {\n return path._internalPath;\n } else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n } else {\n const message = 'Field path arguments must be of type string or ';\n throw createError(\n message,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst FIELD_PATH_RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */\nexport function fieldPathFromDotSeparatedString(\n methodName: string,\n path: string,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n const found = path.search(FIELD_PATH_RESERVED);\n if (found >= 0) {\n throw createError(\n `Invalid field path (${path}). Paths must not contain ` +\n `'~', '*', '/', '[', or ']'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n\n try {\n return new FieldPath(...path.split('.'))._internalPath;\n } catch (e) {\n throw createError(\n `Invalid field path (${path}). Paths must not be empty, ` +\n `begin with '.', end with '.', or contain '..'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\nfunction createError(\n reason: string,\n methodName: string,\n hasConverter: boolean,\n path?: InternalFieldPath,\n targetDoc?: DocumentKey\n): FirestoreError {\n const hasPath = path && !path.isEmpty();\n const hasDocument = targetDoc !== undefined;\n let message = `Function ${methodName}() called with invalid data`;\n if (hasConverter) {\n message += ' (via `toFirestore()`)';\n }\n message += '. ';\n\n let description = '';\n if (hasPath || hasDocument) {\n description += ' (found';\n\n if (hasPath) {\n description += ` in field ${path}`;\n }\n if (hasDocument) {\n description += ` in document ${targetDoc}`;\n }\n description += ')';\n }\n\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n message + reason + description\n );\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */\nfunction fieldMaskContains(\n haystack: InternalFieldPath[],\n needle: InternalFieldPath\n): boolean {\n return haystack.some(v => v.isEqual(needle));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { arrayEquals } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from './reference';\nimport {\n fieldPathFromDotSeparatedString,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n * toFirestore(value: WithFieldValue) {\n * return { value };\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n * return snapshot.data(options).value as number;\n * }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise {\n * const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n * // converters are used with `setDoc`, `addDoc`, and `getDoc`\n * await setDoc(documentRef, 42);\n * const snapshot1 = await getDoc(documentRef);\n * assertEqual(snapshot1.data(), 42);\n *\n * // converters are not used when writing data with `updateDoc`\n * await updateDoc(documentRef, { value: 999 });\n * const snapshot2 = await getDoc(documentRef);\n * assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n * constructor(\n * readonly title: string,\n * readonly author: string,\n * readonly lastUpdatedMillis: number\n * ) {}\n * toString(): string {\n * return `${this.title} by ${this.author}`;\n * }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n * ttl: string;\n * aut: { firstName: string; lastName: string };\n * lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter {\n * toFirestore(post: WithFieldValue): WithFieldValue {\n * return {\n * ttl: post.title,\n * aut: this._autFromAuthor(post.author),\n * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n * };\n * }\n *\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * const author = `${data.aut.firstName} ${data.aut.lastName}`;\n * return new Post(data.ttl, author, data.lut.toMillis());\n * }\n *\n * _autFromAuthor(\n * author: string | FieldValue\n * ): { firstName: string; lastName: string } | FieldValue {\n * if (typeof author !== 'string') {\n * // `author` is a FieldValue, so just return it.\n * return author;\n * }\n * const [firstName, lastName] = author.split(' ');\n * return {firstName, lastName};\n * }\n *\n * _lutFromLastUpdatedMillis(\n * lastUpdatedMillis: number | FieldValue\n * ): Timestamp | FieldValue {\n * if (typeof lastUpdatedMillis !== 'number') {\n * // `lastUpdatedMillis` must be a FieldValue, so just return it.\n * return lastUpdatedMillis;\n * }\n * return Timestamp.fromMillis(lastUpdatedMillis);\n * }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise {\n * // Create a `DocumentReference` with a `FirestoreDataConverter`.\n * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n * // The `data` argument specified to `setDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `Post`. Since the `data`\n * // argument is typed as `WithFieldValue` rather than just `Post`,\n * // this allows properties of the `data` argument to also be special\n * // Firestore values that perform server-side mutations, such as\n * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n * await setDoc(documentRef, {\n * title: 'My Life',\n * author: 'Foo Bar',\n * lastUpdatedMillis: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `setDoc()` is _not_ compatible with `WithFieldValue`. This\n * // type checking prevents the caller from specifying objects with incorrect\n * // properties or property values.\n * // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await setDoc(documentRef, { ttl: 'The Title' });\n *\n * // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n * // object's `data()` method returns a `Post`, rather than a generic object,\n * // which would have been returned if the `DocumentReference` did _not_ have a\n * // `FirestoreDataConverter` attached to it.\n * const snapshot1: DocumentSnapshot = await getDoc(documentRef);\n * const post1: Post = snapshot1.data()!;\n * if (post1) {\n * assertEqual(post1.title, 'My Life');\n * assertEqual(post1.author, 'Foo Bar');\n * }\n *\n * // The `data` argument specified to `updateDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `PostDbModel`. Note that\n * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n * // the `data` argument to `updateDoc()` must be compatible with\n * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n * // as `WithFieldValue` rather than just `PostDbModel`, this\n * // allows properties of the `data` argument to also be those special\n * // Firestore values, like `arrayRemove()`, `deleteField()`, and\n * // `serverTimestamp()`.\n * await updateDoc(documentRef, {\n * 'aut.firstName': 'NewFirstName',\n * lut: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `updateDoc()` is _not_ compatible with `WithFieldValue`.\n * // This type checking prevents the caller from specifying objects with\n * // incorrect properties or property values.\n * // @ts-expect-error \"Argument of type { title: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot = await getDoc(documentRef);\n * const post2: Post = snapshot2.data()!;\n * if (post2) {\n * assertEqual(post2.title, 'My Life');\n * assertEqual(post2.author, 'NewFirstName Bar');\n * }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain Javascript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)}.\n *\n * The `WithFieldValue` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain Javascript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true`\n * or `mergeFields`.\n *\n * The `PartialWithFieldValue` type extends `Partial` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data()`.\n *\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed because Firestore does not\n * enforce a schema on the database. For example, writes from a previous\n * version of the application or writes from another client that did not use a\n * type converter could have written data with different properties and/or\n * property types. The implementation will need to choose whether to\n * gracefully recover from non-conforming data or throw an error.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and\n * metadata.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot\n ): AppModelType;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n\n /** @hideconstructor protected */\n constructor(\n public _firestore: Firestore,\n public _userDataWriter: AbstractUserDataWriter,\n public _key: DocumentKey,\n public _document: Document | null,\n public _converter: UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null\n ) {}\n\n /** Property of the `DocumentSnapshot` that provides the document's ID. */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */\n get ref(): DocumentReference {\n return new DocumentReference(\n this._firestore,\n this._converter,\n this._key\n );\n }\n\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */\n exists(): this is QueryDocumentSnapshot {\n return this._document !== null;\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */\n data(): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(value);\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data(): AppModelType {\n return super.data() as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * The query on which you called {@link getDocs} in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n _query: Query,\n readonly _docs: Array>\n ) {\n this.query = _query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array> {\n return [...this._docs];\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this.docs.length;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.docs.length === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot\n ) => void,\n thisArg?: unknown\n ): void {\n this._docs.forEach(callback, thisArg);\n }\n}\n\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual(\n left:\n | DocumentSnapshot\n | QuerySnapshot,\n right:\n | DocumentSnapshot\n | QuerySnapshot\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n queryEqual(left.query, right.query) &&\n arrayEquals(left.docs, right.docs, snapshotEqual)\n );\n }\n\n return false;\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n arg: string | FieldPath | Compat\n): InternalFieldPath {\n if (typeof arg === 'string') {\n return fieldPathFromDotSeparatedString(methodName, arg);\n } else if (arg instanceof FieldPath) {\n return arg._internalPath;\n } else {\n return arg._delegate._internalPath;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n isCollectionGroupQuery,\n LimitType,\n Query as InternalQuery,\n queryNormalizedOrderBy,\n queryWithAddedFilter,\n queryWithAddedOrderBy,\n queryWithEndAt,\n queryWithLimit,\n queryWithStartAt\n} from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath, ResourcePath } from '../model/path';\nimport { isServerTimestamp } from '../model/server_timestamps';\nimport { refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n validatePositiveNumber,\n valueDescription\n} from '../util/input_validation';\n\nimport { FieldPath } from './field_path';\nimport { DocumentData, DocumentReference, Query } from './reference';\nimport { DocumentSnapshot, fieldPathFromArgument } from './snapshot';\nimport {\n newUserDataReader,\n parseQueryValue,\n UserDataReader\n} from './user_data_reader';\n\nexport function validateHasExplicitOrderByForLimitToLast(\n query: InternalQuery\n): void {\n if (\n query.limitType === LimitType.Last &&\n query.explicitOrderBy.length === 0\n ) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'limitToLast() queries require specifying at least one orderBy() clause'\n );\n }\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'where'\n | 'orderBy'\n | 'limit'\n | 'limitToLast'\n | 'startAt'\n | 'startAfter'\n | 'endAt'\n | 'endBefore';\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */\nexport abstract class AppliableConstraint {\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint extends AppliableConstraint {\n /** The type of this query constraint */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to\n * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or\n * {@link or}.\n * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to\n * apply (e.g. {@link orderBy}, {@link limit}).\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n compositeFilter: QueryCompositeFilterConstraint,\n ...queryConstraints: QueryNonFilterConstraint[]\n): Query;\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param queryConstraints - The list of {@link QueryConstraint}s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n ...queryConstraints: QueryConstraint[]\n): Query;\n\nexport function query(\n query: Query,\n queryConstraint: QueryCompositeFilterConstraint | QueryConstraint | undefined,\n ...additionalQueryConstraints: Array<\n QueryConstraint | QueryNonFilterConstraint\n >\n): Query {\n let queryConstraints: AppliableConstraint[] = [];\n\n if (queryConstraint instanceof AppliableConstraint) {\n queryConstraints.push(queryConstraint);\n }\n\n queryConstraints = queryConstraints.concat(additionalQueryConstraints);\n\n validateQueryConstraintArray(queryConstraints);\n\n for (const constraint of queryConstraints) {\n query = constraint._apply(query);\n }\n return query;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */\nexport class QueryFieldFilterConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'where';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _op: Operator,\n private _value: unknown\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _op: Operator,\n _value: unknown\n ): QueryFieldFilterConstraint {\n return new QueryFieldFilterConstraint(_field, _op, _value);\n }\n\n _apply(\n query: Query\n ): Query {\n const filter = this._parse(query);\n validateNewFieldFilter(query._query, filter);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, filter)\n );\n }\n\n _parse(\n query: Query\n ): FieldFilter {\n const reader = newUserDataReader(query.firestore);\n const filter = newQueryFilter(\n query._query,\n 'where',\n reader,\n query.firestore._databaseId,\n this._field,\n this._op,\n this._value\n );\n return filter;\n }\n}\n\n/**\n * Filter conditions in a {@link where} clause are specified using the\n * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in',\n * 'array-contains-any', and 'not-in'.\n */\nexport type WhereFilterOp =\n | '<'\n | '<='\n | '=='\n | '!='\n | '>='\n | '>'\n | 'array-contains'\n | 'in'\n | 'array-contains-any'\n | 'not-in';\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */\nexport function where(\n fieldPath: string | FieldPath,\n opStr: WhereFilterOp,\n value: unknown\n): QueryFieldFilterConstraint {\n const op = opStr as Operator;\n const field = fieldPathFromArgument('where', fieldPath);\n return QueryFieldFilterConstraint._create(field, op, value);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */\nexport class QueryCompositeFilterConstraint extends AppliableConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'or' | 'and',\n private readonly _queryConstraints: QueryFilterConstraint[]\n ) {\n super();\n }\n\n static _create(\n type: 'or' | 'and',\n _queryConstraints: QueryFilterConstraint[]\n ): QueryCompositeFilterConstraint {\n return new QueryCompositeFilterConstraint(type, _queryConstraints);\n }\n\n _parse(\n query: Query\n ): Filter {\n const parsedFilters = this._queryConstraints\n .map(queryConstraint => {\n return queryConstraint._parse(query);\n })\n .filter(parsedFilter => parsedFilter.getFilters().length > 0);\n\n if (parsedFilters.length === 1) {\n return parsedFilters[0];\n }\n\n return CompositeFilter.create(parsedFilters, this._getOperator());\n }\n\n _apply(\n query: Query\n ): Query {\n const parsedFilter = this._parse(query);\n if (parsedFilter.getFilters().length === 0) {\n // Return the existing query if not adding any more filters (e.g. an empty\n // composite filter).\n return query;\n }\n validateNewFilter(query._query, parsedFilter);\n\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, parsedFilter)\n );\n }\n\n _getQueryConstraints(): readonly AppliableConstraint[] {\n return this._queryConstraints;\n }\n\n _getOperator(): CompositeOperator {\n return this.type === 'and' ? CompositeOperator.AND : CompositeOperator.OR;\n }\n}\n\n/**\n * `QueryNonFilterConstraint` is a helper union type that represents\n * QueryConstraints which are used to narrow or order the set of documents,\n * but that do not explicitly filter on a document field.\n * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},\n * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)},\n * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)}\n * to create a new query instance that also contains the `QueryConstraint`.\n */\nexport type QueryNonFilterConstraint =\n | QueryOrderByConstraint\n | QueryLimitConstraint\n | QueryStartAtConstraint\n | QueryEndAtConstraint;\n\n/**\n * `QueryFilterConstraint` is a helper union type that represents\n * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.\n */\nexport type QueryFilterConstraint =\n | QueryFieldFilterConstraint\n | QueryCompositeFilterConstraint;\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function or(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('or', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.OR,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function and(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('and', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.AND,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */\nexport class QueryOrderByConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'orderBy';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _direction: Direction\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _direction: Direction\n ): QueryOrderByConstraint {\n return new QueryOrderByConstraint(_field, _direction);\n }\n\n _apply(\n query: Query\n ): Query {\n const orderBy = newQueryOrderBy(query._query, this._field, this._direction);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedOrderBy(query._query, orderBy)\n );\n }\n}\n\n/**\n * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'\n * (descending or ascending).\n */\nexport type OrderByDirection = 'desc' | 'asc';\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */\nexport function orderBy(\n fieldPath: string | FieldPath,\n directionStr: OrderByDirection = 'asc'\n): QueryOrderByConstraint {\n const direction = directionStr as Direction;\n const path = fieldPathFromArgument('orderBy', fieldPath);\n return QueryOrderByConstraint._create(path, direction);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */\nexport class QueryLimitConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'limit' | 'limitToLast',\n private readonly _limit: number,\n private readonly _limitType: LimitType\n ) {\n super();\n }\n\n static _create(\n type: 'limit' | 'limitToLast',\n _limit: number,\n _limitType: LimitType\n ): QueryLimitConstraint {\n return new QueryLimitConstraint(type, _limit, _limitType);\n }\n\n _apply(\n query: Query\n ): Query {\n return new Query(\n query.firestore,\n query.converter,\n queryWithLimit(query._query, this._limit, this._limitType)\n );\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limit(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limit', limit);\n return QueryLimitConstraint._create('limit', limit, LimitType.First);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limitToLast(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limitToLast', limit);\n return QueryLimitConstraint._create('limitToLast', limit, LimitType.Last);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */\nexport class QueryStartAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'startAt' | 'startAfter',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'startAt' | 'startAfter',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryStartAtConstraint {\n return new QueryStartAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithStartAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided document (inclusive). The starting position is relative\n * to the order of the query. The document must contain all of the fields\n * provided in the `orderBy` of this query.\n *\n * @param snapshot - The snapshot of the document to start at.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query at, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAt(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided document (exclusive). The starting position is\n * relative to the order of the query. The document must contain all of the\n * fields provided in the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to start after.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided fields relative to the order of the query. The order\n * of the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query after, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAfter(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAfter',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */\nexport class QueryEndAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'endBefore' | 'endAt',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'endBefore' | 'endAt',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryEndAtConstraint {\n return new QueryEndAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithEndAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided document (exclusive). The end position is relative to the\n * order of the query. The document must contain all of the fields provided in\n * the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end before.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query before, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endBefore(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endBefore',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided document (inclusive). The end position is relative to the order\n * of the query. The document must contain all of the fields provided in the\n * orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end at.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided fields relative to the order of the query. The order of the field\n * values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query at, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endAt(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/** Helper function to create a bound from a document or fields */\nfunction newQueryBoundFromDocOrFields<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n methodName: string,\n docOrFields: Array>,\n inclusive: boolean\n): Bound {\n docOrFields[0] = getModularInstance(docOrFields[0]);\n\n if (docOrFields[0] instanceof DocumentSnapshot) {\n return newQueryBoundFromDocument(\n query._query,\n query.firestore._databaseId,\n methodName,\n docOrFields[0]._document,\n inclusive\n );\n } else {\n const reader = newUserDataReader(query.firestore);\n return newQueryBoundFromFields(\n query._query,\n query.firestore._databaseId,\n reader,\n methodName,\n docOrFields,\n inclusive\n );\n }\n}\n\nexport function newQueryFilter(\n query: InternalQuery,\n methodName: string,\n dataReader: UserDataReader,\n databaseId: DatabaseId,\n fieldPath: InternalFieldPath,\n op: Operator,\n value: unknown\n): FieldFilter {\n let fieldValue: ProtoValue;\n if (fieldPath.isKeyField()) {\n if (op === Operator.ARRAY_CONTAINS || op === Operator.ARRAY_CONTAINS_ANY) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. You can't perform '${op}' queries on documentId().`\n );\n } else if (op === Operator.IN || op === Operator.NOT_IN) {\n validateDisjunctiveFilterElements(value, op);\n const referenceList: ProtoValue[] = [];\n for (const arrayValue of value as ProtoValue[]) {\n referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));\n }\n fieldValue = { arrayValue: { values: referenceList } };\n } else {\n fieldValue = parseDocumentIdValue(databaseId, query, value);\n }\n } else {\n if (\n op === Operator.IN ||\n op === Operator.NOT_IN ||\n op === Operator.ARRAY_CONTAINS_ANY\n ) {\n validateDisjunctiveFilterElements(value, op);\n }\n fieldValue = parseQueryValue(\n dataReader,\n methodName,\n value,\n /* allowArrays= */ op === Operator.IN || op === Operator.NOT_IN\n );\n }\n const filter = FieldFilter.create(fieldPath, op, fieldValue);\n return filter;\n}\n\nexport function newQueryOrderBy(\n query: InternalQuery,\n fieldPath: InternalFieldPath,\n direction: Direction\n): OrderBy {\n if (query.startAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call startAt() or startAfter() before ' +\n 'calling orderBy().'\n );\n }\n if (query.endAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call endAt() or endBefore() before ' +\n 'calling orderBy().'\n );\n }\n const orderBy = new OrderBy(fieldPath, direction);\n return orderBy;\n}\n\n/**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */\nexport function newQueryBoundFromDocument(\n query: InternalQuery,\n databaseId: DatabaseId,\n methodName: string,\n doc: Document | null,\n inclusive: boolean\n): Bound {\n if (!doc) {\n throw new FirestoreError(\n Code.NOT_FOUND,\n `Can't use a DocumentSnapshot that doesn't exist for ` +\n `${methodName}().`\n );\n }\n\n const components: ProtoValue[] = [];\n\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n if (orderBy.field.isKeyField()) {\n components.push(refValue(databaseId, doc.key));\n } else {\n const value = doc.data.field(orderBy.field);\n if (isServerTimestamp(value)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You are trying to start or end a query using a ' +\n 'document for which the field \"' +\n orderBy.field +\n '\" is an uncommitted server timestamp. (Since the value of ' +\n 'this field is unknown, you cannot start/end a query with it.)'\n );\n } else if (value !== null) {\n components.push(value);\n } else {\n const field = orderBy.field.canonicalString();\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You are trying to start or end a query using a ` +\n `document for which the field '${field}' (used as the ` +\n `orderBy) does not exist.`\n );\n }\n }\n }\n return new Bound(components, inclusive);\n}\n\n/**\n * Converts a list of field values to a `Bound` for the given query.\n */\nexport function newQueryBoundFromFields(\n query: InternalQuery,\n databaseId: DatabaseId,\n dataReader: UserDataReader,\n methodName: string,\n values: unknown[],\n inclusive: boolean\n): Bound {\n // Use explicit order by's because it has to match the query the user made\n const orderBy = query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}(). ` +\n `The number of arguments must be less than or equal to the ` +\n `number of orderBy() clauses`\n );\n }\n\n const components: ProtoValue[] = [];\n for (let i = 0; i < values.length; i++) {\n const rawValue = values[i];\n const orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. Expected a string for document ID in ` +\n `${methodName}(), but got a ${typeof rawValue}`\n );\n }\n if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection and ordering by documentId(), ` +\n `the value passed to ${methodName}() must be a plain document ID, but ` +\n `'${rawValue}' contains a slash.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(rawValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group and ordering by ` +\n `documentId(), the value passed to ${methodName}() must result in a ` +\n `valid document path, but '${path}' is not because it contains an odd number ` +\n `of segments.`\n );\n }\n const key = new DocumentKey(path);\n components.push(refValue(databaseId, key));\n } else {\n const wrapped = parseQueryValue(dataReader, methodName, rawValue);\n components.push(wrapped);\n }\n }\n\n return new Bound(components, inclusive);\n}\n\n/**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */\nfunction parseDocumentIdValue(\n databaseId: DatabaseId,\n query: InternalQuery,\n documentIdValue: unknown\n): ProtoValue {\n documentIdValue = getModularInstance(documentIdValue);\n\n if (typeof documentIdValue === 'string') {\n if (documentIdValue === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. When querying with documentId(), you ' +\n 'must provide a valid document ID, but it was an empty string.'\n );\n }\n if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection by ` +\n `documentId(), you must provide a plain document ID, but ` +\n `'${documentIdValue}' contains a '/' character.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(documentIdValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group by ` +\n `documentId(), the value provided must result in a valid document path, ` +\n `but '${path}' is not because it has an odd number of segments (${path.length}).`\n );\n }\n return refValue(databaseId, new DocumentKey(path));\n } else if (documentIdValue instanceof DocumentReference) {\n return refValue(databaseId, documentIdValue._key);\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying with documentId(), you must provide a valid ` +\n `string or a DocumentReference, but it was: ` +\n `${valueDescription(documentIdValue)}.`\n );\n }\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */\nfunction validateDisjunctiveFilterElements(\n value: unknown,\n operator: Operator\n): void {\n if (!Array.isArray(value) || value.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid Query. A non-empty array is required for ' +\n `'${operator.toString()}' filters.`\n );\n }\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */\nfunction conflictingOps(op: Operator): Operator[] {\n switch (op) {\n case Operator.NOT_EQUAL:\n return [Operator.NOT_EQUAL, Operator.NOT_IN];\n case Operator.ARRAY_CONTAINS_ANY:\n case Operator.IN:\n return [Operator.NOT_IN];\n case Operator.NOT_IN:\n return [\n Operator.ARRAY_CONTAINS_ANY,\n Operator.IN,\n Operator.NOT_IN,\n Operator.NOT_EQUAL\n ];\n default:\n return [];\n }\n}\n\nfunction validateNewFieldFilter(\n query: InternalQuery,\n fieldFilter: FieldFilter\n): void {\n const conflictingOp = findOpInsideFilters(\n query.filters,\n conflictingOps(fieldFilter.op)\n );\n if (conflictingOp !== null) {\n // Special case when it's a duplicate op to give a slightly clearer error message.\n if (conflictingOp === fieldFilter.op) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You cannot use more than one ' +\n `'${fieldFilter.op.toString()}' filter.`\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +\n `with '${conflictingOp.toString()}' filters.`\n );\n }\n }\n}\n\nfunction validateNewFilter(query: InternalQuery, filter: Filter): void {\n let testQuery = query;\n const subFilters = filter.getFlattenedFilters();\n for (const subFilter of subFilters) {\n validateNewFieldFilter(testQuery, subFilter);\n testQuery = queryWithAddedFilter(testQuery, subFilter);\n }\n}\n\n// Checks if any of the provided filter operators are included in the given list of filters and\n// returns the first one that is, or null if none are.\nfunction findOpInsideFilters(\n filters: Filter[],\n operators: Operator[]\n): Operator | null {\n for (const filter of filters) {\n for (const fieldFilter of filter.getFlattenedFilters()) {\n if (operators.indexOf(fieldFilter.op) >= 0) {\n return fieldFilter.op;\n }\n }\n }\n return null;\n}\n\nexport function validateQueryFilterConstraint(\n functionName: string,\n queryConstraint: AppliableConstraint\n): void {\n if (\n !(queryConstraint instanceof QueryFieldFilterConstraint) &&\n !(queryConstraint instanceof QueryCompositeFilterConstraint)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`\n );\n }\n}\n\nfunction validateQueryConstraintArray(\n queryConstraint: AppliableConstraint[]\n): void {\n const compositeFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryCompositeFilterConstraint\n ).length;\n const fieldFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryFieldFilterConstraint\n ).length;\n\n if (\n compositeFilterCount > 1 ||\n (compositeFilterCount > 0 && fieldFilterCount > 0)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'InvalidQuery. When using composite filters, you cannot use ' +\n 'more than one filter at the top level. Consider nesting the multiple ' +\n 'filters within an `and(...)` statement. For example: ' +\n 'change `query(query, where(...), or(...))` to ' +\n '`query(query, and(where(...), or(...)))`.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(result.length === 1, 'Expected a single document result');\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: WithFieldValue\n): Promise;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n): Promise;\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options?: SetOptions\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n data: UpdateData\n): Promise;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise;\nexport function updateDoc(\n reference: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentData } from '@firebase/firestore-types';\n\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport { ResourcePath } from '../model/path';\nimport {\n getLocalWriteTime,\n getPreviousValue\n} from '../model/server_timestamps';\nimport { TypeOrder } from '../model/type_order';\nimport { typeOrder } from '../model/values';\nimport {\n ApiClientObjectMap,\n ArrayValue as ProtoArrayValue,\n LatLng as ProtoLatLng,\n MapValue as ProtoMapValue,\n Timestamp as ProtoTimestamp,\n Value,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { isValidResourceName } from '../remote/serializer';\nimport { fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logError } from '../util/log';\nimport { forEach } from '../util/obj';\n\nimport { GeoPoint } from './geo_point';\nimport { Timestamp } from './timestamp';\n\nexport type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';\n\n/**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */\nexport abstract class AbstractUserDataWriter {\n convertValue(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): unknown {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return null;\n case TypeOrder.BooleanValue:\n return value.booleanValue!;\n case TypeOrder.NumberValue:\n return normalizeNumber(value.integerValue || value.doubleValue);\n case TypeOrder.TimestampValue:\n return this.convertTimestamp(value.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return this.convertServerTimestamp(value, serverTimestampBehavior);\n case TypeOrder.StringValue:\n return value.stringValue!;\n case TypeOrder.BlobValue:\n return this.convertBytes(normalizeByteString(value.bytesValue!));\n case TypeOrder.RefValue:\n return this.convertReference(value.referenceValue!);\n case TypeOrder.GeoPointValue:\n return this.convertGeoPoint(value.geoPointValue!);\n case TypeOrder.ArrayValue:\n return this.convertArray(value.arrayValue!, serverTimestampBehavior);\n case TypeOrder.ObjectValue:\n return this.convertObject(value.mapValue!, serverTimestampBehavior);\n default:\n throw fail('Invalid value type: ' + JSON.stringify(value));\n }\n }\n\n private convertObject(\n mapValue: ProtoMapValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): DocumentData {\n return this.convertObjectMap(mapValue.fields, serverTimestampBehavior);\n }\n\n /**\n * @internal\n */\n convertObjectMap(\n fields: ApiClientObjectMap | undefined,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): DocumentData {\n const result: DocumentData = {};\n forEach(fields, (key, value) => {\n result[key] = this.convertValue(value, serverTimestampBehavior);\n });\n return result;\n }\n\n private convertGeoPoint(value: ProtoLatLng): GeoPoint {\n return new GeoPoint(\n normalizeNumber(value.latitude),\n normalizeNumber(value.longitude)\n );\n }\n\n private convertArray(\n arrayValue: ProtoArrayValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown[] {\n return (arrayValue.values || []).map(value =>\n this.convertValue(value, serverTimestampBehavior)\n );\n }\n\n private convertServerTimestamp(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown {\n switch (serverTimestampBehavior) {\n case 'previous':\n const previousValue = getPreviousValue(value);\n if (previousValue == null) {\n return null;\n }\n return this.convertValue(previousValue, serverTimestampBehavior);\n case 'estimate':\n return this.convertTimestamp(getLocalWriteTime(value));\n default:\n return null;\n }\n }\n\n private convertTimestamp(value: ProtoTimestamp): Timestamp {\n const normalizedValue = normalizeTimestamp(value);\n return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);\n }\n\n protected convertDocumentKey(\n name: string,\n expectedDatabaseId: DatabaseId\n ): DocumentKey {\n const resourcePath = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resourcePath),\n 'ReferenceValue is not valid ' + name\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail('Document in a transaction was a ' + doc.constructor.name);\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error): boolean {\n if (error.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The Platform's 'window' implementation or null if not available. */\nexport function getWindow(): Window | null {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */\nexport function getDocument(): Document | null {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof document !== 'undefined' ? document : null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\n\nimport { Code, FirestoreError } from './error';\nimport { logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TimerHandle = any;\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport const enum TimerId {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n All = 'all',\n\n /**\n * The following 5 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed. The health check is used to mark\n * a stream healthy if it has not received an error during its initial setup.\n */\n ListenStreamIdle = 'listen_stream_idle',\n ListenStreamConnectionBackoff = 'listen_stream_connection_backoff',\n WriteStreamIdle = 'write_stream_idle',\n WriteStreamConnectionBackoff = 'write_stream_connection_backoff',\n HealthCheckTimeout = 'health_check_timeout',\n\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n OnlineStateTimeout = 'online_state_timeout',\n\n /**\n * A timer used to update the client metadata in IndexedDb, which is used\n * to determine the primary leaseholder.\n */\n ClientMetadataRefresh = 'client_metadata_refresh',\n\n /** A timer used to periodically attempt LRU Garbage collection */\n LruGarbageCollection = 'lru_garbage_collection',\n\n /**\n * A timer used to retry transactions. Since there can be multiple concurrent\n * transactions, multiple of these may be in the queue at a given time.\n */\n TransactionRetry = 'transaction_retry',\n\n /**\n * A timer used to retry operations scheduled via retryable AsyncQueue\n * operations.\n */\n AsyncQueueRetry = 'async_queue_retry',\n\n /**\n * A timer used to periodically attempt index backfill.\n */\n IndexBackfill = 'index_backfill'\n}\n\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nexport class DelayedOperation implements PromiseLike {\n // handle for use with clearTimeout(), or null if the operation has been\n // executed or canceled already.\n private timerHandle: TimerHandle | null;\n\n private readonly deferred = new Deferred();\n\n private constructor(\n private readonly asyncQueue: AsyncQueue,\n readonly timerId: TimerId,\n readonly targetTimeMs: number,\n private readonly op: () => Promise,\n private readonly removalCallback: (op: DelayedOperation) => void\n ) {\n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch(err => {});\n }\n\n get promise(): Promise {\n return this.deferred.promise;\n }\n\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */\n static createAndSchedule(\n asyncQueue: AsyncQueue,\n timerId: TimerId,\n delayMs: number,\n op: () => Promise,\n removalCallback: (op: DelayedOperation) => void\n ): DelayedOperation {\n const targetTime = Date.now() + delayMs;\n const delayedOp = new DelayedOperation(\n asyncQueue,\n timerId,\n targetTime,\n op,\n removalCallback\n );\n delayedOp.start(delayMs);\n return delayedOp;\n }\n\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n private start(delayMs: number): void {\n this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);\n }\n\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n skipDelay(): void {\n return this.handleDelayElapsed();\n }\n\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */\n cancel(reason?: string): void {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(\n new FirestoreError(\n Code.CANCELLED,\n 'Operation cancelled' + (reason ? ': ' + reason : '')\n )\n );\n }\n }\n\n then = this.deferred.promise.then.bind(this.deferred.promise);\n\n private handleDelayElapsed(): void {\n this.asyncQueue.enqueueAndForget(() => {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n return this.op().then(result => {\n return this.deferred.resolve(result);\n });\n } else {\n return Promise.resolve();\n }\n });\n }\n\n private clearTimeout(): void {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n }\n}\n\nexport interface AsyncQueue {\n // Is this AsyncQueue being shut down? If true, this instance will not enqueue\n // any new operations, Promises from enqueue requests will not resolve.\n readonly isShuttingDown: boolean;\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void;\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue without waiting for it to complete (i.e. we ignore the Promise result).\n */\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void;\n\n /**\n * Initialize the shutdown of this queue. Once this method is called, the\n * only possible way to request running an operation is through\n * `enqueueEvenWhileRestricted()`.\n *\n * @param purgeExistingTasks Whether already enqueued tasked should be\n * rejected (unless enqueued wih `enqueueEvenWhileRestricted()`). Defaults\n * to false.\n */\n enterRestrictedMode(purgeExistingTasks?: boolean): void;\n\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n enqueue(op: () => Promise): Promise;\n\n /**\n * Enqueue a retryable operation.\n *\n * A retryable operation is rescheduled with backoff if it fails with a\n * IndexedDbTransactionError (the error type used by SimpleDb). All\n * retryable operations are executed in order and only run if all prior\n * operations were retried successfully.\n */\n enqueueRetryable(op: () => Promise): void;\n\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel\n * or fast-forward the operation prior to its running.\n */\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation;\n\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n verifyOperationInProgress(): void;\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */\nexport function wrapInUserErrorIfRecoverable(\n e: Error,\n msg: string\n): FirestoreError {\n logError(LOG_TAG, `${msg}: ${e}`);\n if (isIndexedDbTransactionError(e)) {\n return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`);\n } else {\n throw e;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { getDocument } from '../platform/dom';\nimport { ExponentialBackoff } from '../remote/backoff';\n\nimport { debugAssert, fail } from './assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from './async_queue';\nimport { FirestoreError } from './error';\nimport { logDebug, logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\nexport class AsyncQueueImpl implements AsyncQueue {\n // The last promise in the queue.\n private tail: Promise = Promise.resolve();\n\n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n private retryableOps: Array<() => Promise> = [];\n\n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n private _isShuttingDown: boolean = false;\n\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n private delayedOperations: Array> = [];\n\n // visible for testing\n failure: FirestoreError | null = null;\n\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n private operationInProgress = false;\n\n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n private skipNonRestrictedTasks = false;\n\n // List of TimerIds to fast-forward delays for.\n private timerIdsToSkip: TimerId[] = [];\n\n // Backoff timer used to schedule retries for retryable operations\n private backoff = new ExponentialBackoff(this, TimerId.AsyncQueueRetry);\n\n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n private visibilityHandler: () => void = () => {\n const document = getDocument();\n if (document) {\n logDebug(\n LOG_TAG,\n 'Visibility state changed to ' + document.visibilityState\n );\n }\n this.backoff.skipBackoff();\n };\n\n constructor() {\n const document = getDocument();\n if (document && typeof document.addEventListener === 'function') {\n document.addEventListener('visibilitychange', this.visibilityHandler);\n }\n }\n\n get isShuttingDown(): boolean {\n return this._isShuttingDown;\n }\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(op);\n }\n\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void {\n this.verifyNotFailed();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueueInternal(op);\n }\n\n enterRestrictedMode(purgeExistingTasks?: boolean): void {\n if (!this._isShuttingDown) {\n this._isShuttingDown = true;\n this.skipNonRestrictedTasks = purgeExistingTasks || false;\n const document = getDocument();\n if (document && typeof document.removeEventListener === 'function') {\n document.removeEventListener(\n 'visibilitychange',\n this.visibilityHandler\n );\n }\n }\n }\n\n enqueue(op: () => Promise): Promise {\n this.verifyNotFailed();\n if (this._isShuttingDown) {\n // Return a Promise which never resolves.\n return new Promise(() => {});\n }\n\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const task = new Deferred();\n return this.enqueueInternal(() => {\n if (this._isShuttingDown && this.skipNonRestrictedTasks) {\n // We do not resolve 'task'\n return Promise.resolve();\n }\n\n op().then(task.resolve, task.reject);\n return task.promise;\n }).then(() => task.promise);\n }\n\n enqueueRetryable(op: () => Promise): void {\n this.enqueueAndForget(() => {\n this.retryableOps.push(op);\n return this.retryNextOp();\n });\n }\n\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */\n private async retryNextOp(): Promise {\n if (this.retryableOps.length === 0) {\n return;\n }\n\n try {\n await this.retryableOps[0]();\n this.retryableOps.shift();\n this.backoff.reset();\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);\n } else {\n throw e; // Failure will be handled by AsyncQueue\n }\n }\n\n if (this.retryableOps.length > 0) {\n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.backoff.backoffAndRun(() => this.retryNextOp());\n }\n }\n\n private enqueueInternal(op: () => Promise): Promise {\n const newTail = this.tail.then(() => {\n this.operationInProgress = true;\n return op()\n .catch((error: FirestoreError) => {\n this.failure = error;\n this.operationInProgress = false;\n const message = getMessageOrStack(error);\n logError('INTERNAL UNHANDLED ERROR: ', message);\n\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw error;\n })\n .then(result => {\n this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n }\n\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation {\n this.verifyNotFailed();\n\n debugAssert(\n delayMs >= 0,\n `Attempted to schedule an operation with a negative delay of ${delayMs}`\n );\n\n // Fast-forward delays for timerIds that have been overriden.\n if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n delayMs = 0;\n }\n\n const delayedOp = DelayedOperation.createAndSchedule(\n this,\n timerId,\n delayMs,\n op,\n removedOp =>\n this.removeDelayedOperation(removedOp as DelayedOperation)\n );\n this.delayedOperations.push(delayedOp as DelayedOperation);\n return delayedOp;\n }\n\n private verifyNotFailed(): void {\n if (this.failure) {\n fail('AsyncQueue is already failed: ' + getMessageOrStack(this.failure));\n }\n }\n\n verifyOperationInProgress(): void {\n debugAssert(\n this.operationInProgress,\n 'verifyOpInProgress() called when no op in progress on this queue.'\n );\n }\n\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n async drain(): Promise {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let currentTail: Promise;\n do {\n currentTail = this.tail;\n await currentTail;\n } while (currentTail !== this.tail);\n }\n\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n containsDelayedOperation(timerId: TimerId): boolean {\n for (const op of this.delayedOperations) {\n if (op.timerId === timerId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(() => {\n // Run ops in the same order they'd run if they ran naturally.\n this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);\n\n for (const op of this.delayedOperations) {\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n\n return this.drain();\n });\n }\n\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */\n skipDelaysForTimerId(timerId: TimerId): void {\n this.timerIdsToSkip.push(timerId);\n }\n\n /** Called once a DelayedOperation is run or canceled. */\n private removeDelayedOperation(op: DelayedOperation): void {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const index = this.delayedOperations.indexOf(op);\n debugAssert(index >= 0, 'Delayed operation not found.');\n this.delayedOperations.splice(index, 1);\n }\n}\n\nexport function newAsyncQueue(): AsyncQueue {\n return new AsyncQueueImpl();\n}\n\n/**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\nfunction getMessageOrStack(error: Error): string {\n let message = error.message || '';\n if (error.stack) {\n if (error.stack.includes(error.message)) {\n message = error.stack;\n } else {\n message = error.message + '\\n' + error.stack;\n }\n }\n return message;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getUA, isIndexedDBAvailable } from '@firebase/util';\n\nimport { debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { PersistencePromise } from './persistence_promise';\n\n// References to `window` are guarded by SimpleDb.isAvailable()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'SimpleDb';\n\n/**\n * The maximum number of retry attempts for an IndexedDb transaction that fails\n * with a DOMException.\n */\nconst TRANSACTION_RETRY_COUNT = 3;\n\n// The different modes supported by `SimpleDb.runTransaction()`\ntype SimpleDbTransactionMode = 'readonly' | 'readwrite';\n\nexport interface SimpleDbSchemaConverter {\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise;\n}\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nexport class SimpleDbTransaction {\n private aborted = false;\n\n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n private readonly completionDeferred = new Deferred();\n\n static open(\n db: IDBDatabase,\n action: string,\n mode: IDBTransactionMode,\n objectStoreNames: string[]\n ): SimpleDbTransaction {\n try {\n return new SimpleDbTransaction(\n action,\n db.transaction(objectStoreNames, mode)\n );\n } catch (e) {\n throw new IndexedDbTransactionError(action, e as Error);\n }\n }\n\n constructor(\n private readonly action: string,\n private readonly transaction: IDBTransaction\n ) {\n this.transaction.oncomplete = () => {\n this.completionDeferred.resolve();\n };\n this.transaction.onabort = () => {\n if (transaction.error) {\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, transaction.error)\n );\n } else {\n this.completionDeferred.resolve();\n }\n };\n this.transaction.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, error)\n );\n };\n }\n\n get completionPromise(): Promise {\n return this.completionDeferred.promise;\n }\n\n abort(error?: Error): void {\n if (error) {\n this.completionDeferred.reject(error);\n }\n\n if (!this.aborted) {\n logDebug(\n LOG_TAG,\n 'Aborting transaction:',\n error ? error.message : 'Client-initiated abort'\n );\n this.aborted = true;\n this.transaction.abort();\n }\n }\n\n maybeCommit(): void {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const maybeV3IndexedDb = this.transaction as any;\n if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') {\n maybeV3IndexedDb.commit();\n }\n }\n\n /**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */\n store(\n storeName: string\n ): SimpleDbStore {\n const store = this.transaction.objectStore(storeName);\n debugAssert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore(store);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nexport class SimpleDb {\n private db?: IDBDatabase;\n private versionchangelistener?: (event: IDBVersionChangeEvent) => void;\n\n /** Deletes the specified database. */\n static delete(name: string): Promise {\n logDebug(LOG_TAG, 'Removing database:', name);\n return wrapRequest(window.indexedDB.deleteDatabase(name)).toPromise();\n }\n\n /** Returns true if IndexedDB is available in the current environment. */\n static isAvailable(): boolean {\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n if (SimpleDb.isMockPersistence()) {\n return true;\n }\n\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n\n // Check the UA string to find out the browser.\n const ua = getUA();\n\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n\n // iOS Safari: Disable for users running iOS version < 10.\n const iOSVersion = SimpleDb.getIOSVersion(ua);\n const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10;\n\n // Android browser: Disable for userse running version < 4.5.\n const androidVersion = SimpleDb.getAndroidVersion(ua);\n const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5;\n\n if (\n ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0 ||\n isUnsupportedIOS ||\n isUnsupportedAndroid\n ) {\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */\n static isMockPersistence(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.env?.USE_MOCK_PERSISTENCE === 'YES'\n );\n }\n\n /** Helper to get a typed SimpleDbStore from a transaction. */\n static getStore(\n txn: SimpleDbTransaction,\n store: string\n ): SimpleDbStore {\n return txn.store(store);\n }\n\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static getIOSVersion(ua: string): number {\n const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\n const version = iOSVersionRegex\n ? iOSVersionRegex[1].split('_').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\n // visible for testing\n /** Parse User Agent to determine Android version. Returns -1 if not found. */\n static getAndroidVersion(ua: string): number {\n const androidVersionRegex = ua.match(/Android ([\\d.]+)/i);\n const version = androidVersionRegex\n ? androidVersionRegex[1].split('.').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(\n private readonly name: string,\n private readonly version: number,\n private readonly schemaConverter: SimpleDbSchemaConverter\n ) {\n debugAssert(\n SimpleDb.isAvailable(),\n 'IndexedDB not supported in current environment.'\n );\n\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n if (iOSVersion === 12.2) {\n logError(\n 'Firestore persistence suffers from a bug in iOS 12.2 ' +\n 'Safari that may cause your app to stop working. See ' +\n 'https://stackoverflow.com/q/56496296/110915 for details ' +\n 'and a potential workaround.'\n );\n }\n }\n\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */\n async ensureDb(action: string): Promise {\n if (!this.db) {\n logDebug(LOG_TAG, 'Opening database:', this.name);\n this.db = await new Promise((resolve, reject) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const request = indexedDB.open(this.name, this.version);\n\n request.onsuccess = (event: Event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n resolve(db);\n };\n\n request.onblocked = () => {\n reject(\n new IndexedDbTransactionError(\n action,\n 'Cannot upgrade IndexedDB schema while another tab is open. ' +\n 'Close all tabs that access Firestore and reload this page to proceed.'\n )\n );\n };\n\n request.onerror = (event: Event) => {\n const error: DOMException = (event.target as IDBOpenDBRequest).error!;\n if (error.name === 'VersionError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A newer version of the Firestore SDK was previously used and so the persisted ' +\n 'data is not compatible with the version of the SDK you are now using. The SDK ' +\n 'will operate with persistence disabled. If you need persistence, please ' +\n 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\n 'data for your app to start fresh.'\n )\n );\n } else if (error.name === 'InvalidStateError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Unable to open an IndexedDB connection. This could be due to running in a ' +\n 'private browsing session on a browser whose private browsing sessions do not ' +\n 'support IndexedDB: ' +\n error\n )\n );\n } else {\n reject(new IndexedDbTransactionError(action, error));\n }\n };\n\n request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n logDebug(\n LOG_TAG,\n 'Database \"' + this.name + '\" requires upgrade from version:',\n event.oldVersion\n );\n const db = (event.target as IDBOpenDBRequest).result;\n this.schemaConverter\n .createOrUpgrade(\n db,\n request.transaction!,\n event.oldVersion,\n this.version\n )\n .next(() => {\n logDebug(\n LOG_TAG,\n 'Database upgrade to version ' + this.version + ' complete'\n );\n });\n };\n });\n }\n\n if (this.versionchangelistener) {\n this.db.onversionchange = event => this.versionchangelistener!(event);\n }\n return this.db;\n }\n\n setVersionChangeListener(\n versionChangeListener: (event: IDBVersionChangeEvent) => void\n ): void {\n this.versionchangelistener = versionChangeListener;\n if (this.db) {\n this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n return versionChangeListener(event);\n };\n }\n }\n\n async runTransaction(\n action: string,\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise\n ): Promise {\n const readonly = mode === 'readonly';\n let attemptNumber = 0;\n\n while (true) {\n ++attemptNumber;\n\n try {\n this.db = await this.ensureDb(action);\n\n const transaction = SimpleDbTransaction.open(\n this.db,\n action,\n readonly ? 'readonly' : 'readwrite',\n objectStores\n );\n const transactionFnResult = transactionFn(transaction)\n .next(result => {\n transaction.maybeCommit();\n return result;\n })\n .catch(error => {\n // Abort the transaction if there was an error.\n transaction.abort(error);\n // We cannot actually recover, and calling `abort()` will cause the transaction's\n // completion promise to be rejected. This in turn means that we won't use\n // `transactionFnResult` below. We return a rejection here so that we don't add the\n // possibility of returning `void` to the type of `transactionFnResult`.\n return PersistencePromise.reject(error);\n })\n .toPromise();\n\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n transactionFnResult.catch(() => {});\n\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await transaction.completionPromise;\n return transactionFnResult;\n } catch (e) {\n const error = e as Error;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n const retryable =\n error.name !== 'FirebaseError' &&\n attemptNumber < TRANSACTION_RETRY_COUNT;\n logDebug(\n LOG_TAG,\n 'Transaction failed with error:',\n error.message,\n 'Retrying:',\n retryable\n );\n\n this.close();\n\n if (!retryable) {\n return Promise.reject(error);\n }\n }\n }\n }\n\n close(): void {\n if (this.db) {\n this.db.close();\n }\n this.db = undefined;\n }\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */\nexport class IterationController {\n private shouldStop = false;\n private nextKey: IDBValidKey | null = null;\n\n constructor(private dbCursor: IDBCursorWithValue) {}\n\n get isDone(): boolean {\n return this.shouldStop;\n }\n\n get skipToKey(): IDBValidKey | null {\n return this.nextKey;\n }\n\n set cursor(value: IDBCursorWithValue) {\n this.dbCursor = value;\n }\n\n /**\n * This function can be called to stop iteration at any point.\n */\n done(): void {\n this.shouldStop = true;\n }\n\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */\n skip(key: IDBValidKey): void {\n this.nextKey = key;\n }\n\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n delete(): PersistencePromise {\n return wrapRequest(this.dbCursor.delete());\n }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback = (\n key: KeyType,\n value: ValueType,\n control: IterationController\n) => void | PersistencePromise;\n\n/** Options available to the iterate() method. */\nexport interface IterateOptions {\n /** Index to iterate over (else primary keys will be iterated) */\n index?: string;\n\n /** IndxedDB Range to iterate over (else entire store will be iterated) */\n range?: IDBKeyRange;\n\n /** If true, values aren't read while iterating. */\n keysOnly?: boolean;\n\n /** If true, iterate over the store in reverse. */\n reverse?: boolean;\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */\nexport class IndexedDbTransactionError extends FirestoreError {\n name = 'IndexedDbTransactionError';\n\n constructor(actionName: string, cause: Error | string) {\n super(\n Code.UNAVAILABLE,\n `IndexedDB transaction '${actionName}' failed: ${cause}`\n );\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */\nexport function isIndexedDbTransactionError(e: Error): boolean {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return e.name === 'IndexedDbTransactionError';\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */\nexport class SimpleDbStore<\n KeyType extends IDBValidKey,\n ValueType extends unknown\n> {\n constructor(private store: IDBObjectStore) {}\n\n /**\n * Writes a value into the Object Store.\n *\n * @param key - Optional explicit key to use when writing the object, else the\n * key will be auto-assigned (e.g. via the defined keyPath for the store).\n * @param value - The object to write.\n */\n put(value: ValueType): PersistencePromise;\n put(key: KeyType, value: ValueType): PersistencePromise;\n put(\n keyOrValue: KeyType | ValueType,\n value?: ValueType\n ): PersistencePromise {\n let request;\n if (value !== undefined) {\n logDebug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue as KeyType);\n } else {\n logDebug(LOG_TAG, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue as ValueType);\n }\n return wrapRequest(request);\n }\n\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */\n add(value: ValueType): PersistencePromise {\n logDebug(LOG_TAG, 'ADD', this.store.name, value, value);\n const request = this.store.add(value as ValueType);\n return wrapRequest(request);\n }\n\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */\n get(key: KeyType): PersistencePromise {\n const request = this.store.get(key);\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return wrapRequest(request).next(result => {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n logDebug(LOG_TAG, 'GET', this.store.name, key, result);\n return result;\n });\n }\n\n delete(key: KeyType | IDBKeyRange): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE', this.store.name, key);\n const request = this.store.delete(key);\n return wrapRequest(request);\n }\n\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */\n count(): PersistencePromise {\n logDebug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest(request);\n }\n\n /** Loads all elements from the object store. */\n loadAll(): PersistencePromise;\n /** Loads all elements for the index range from the object store. */\n loadAll(range: IDBKeyRange): PersistencePromise;\n /** Loads all elements ordered by the given index. */\n loadAll(index: string): PersistencePromise;\n /**\n * Loads all elements from the object store that fall into the provided in the\n * index range for the given index.\n */\n loadAll(index: string, range: IDBKeyRange): PersistencePromise;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n const iterateOptions = this.options(indexOrRange, range);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster.\n const store = iterateOptions.index\n ? this.store.index(iterateOptions.index)\n : this.store;\n if (typeof store.getAll === 'function') {\n const request = store.getAll(iterateOptions.range);\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n } else {\n const cursor = this.cursor(iterateOptions);\n const results: ValueType[] = [];\n return this.iterateCursor(cursor, (key, value) => {\n results.push(value);\n }).next(() => {\n return results;\n });\n }\n }\n\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */\n loadFirst(\n range: IDBKeyRange,\n count: number | null\n ): PersistencePromise {\n const request = this.store.getAll(\n range,\n count === null ? undefined : count\n );\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n }\n\n deleteAll(): PersistencePromise;\n deleteAll(range: IDBKeyRange): PersistencePromise;\n deleteAll(index: string, range: IDBKeyRange): PersistencePromise;\n deleteAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE ALL', this.store.name);\n const options = this.options(indexOrRange, range);\n options.keysOnly = false;\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, (key, value, control) => {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n }\n\n /**\n * Iterates over keys and values in an object store.\n *\n * @param options - Options specifying how to iterate the objects in the\n * store.\n * @param callback - will be called for each iterated object. Iteration can be\n * canceled at any point by calling the doneFn passed to the callback.\n * The callback can return a PersistencePromise if it performs async\n * operations but note that iteration will continue without waiting for them\n * to complete.\n * @returns A PersistencePromise that resolves once all PersistencePromises\n * returned by callbacks resolve.\n */\n iterate(\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n options: IterateOptions,\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n optionsOrCallback: IterateOptions | IterateCallback,\n callback?: IterateCallback\n ): PersistencePromise {\n let options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback as IterateCallback;\n } else {\n options = optionsOrCallback as IterateOptions;\n }\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n }\n\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */\n iterateSerial(\n callback: (k: KeyType, v: ValueType) => PersistencePromise\n ): PersistencePromise {\n const cursorRequest = this.cursor({});\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n callback(cursor.primaryKey as KeyType, cursor.value).next(\n shouldContinue => {\n if (shouldContinue) {\n cursor.continue();\n } else {\n resolve();\n }\n }\n );\n };\n });\n }\n\n private iterateCursor(\n cursorRequest: IDBRequest,\n fn: IterateCallback\n ): PersistencePromise {\n const results: Array> = [];\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n const controller = new IterationController(cursor);\n const userResult = fn(\n cursor.primaryKey as KeyType,\n cursor.value,\n controller\n );\n if (userResult instanceof PersistencePromise) {\n const userPromise: PersistencePromise = userResult.catch(\n err => {\n controller.done();\n return PersistencePromise.reject(err);\n }\n );\n results.push(userPromise);\n }\n if (controller.isDone) {\n resolve();\n } else if (controller.skipToKey === null) {\n cursor.continue();\n } else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(() => PersistencePromise.waitFor(results));\n }\n\n private options(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): IterateOptions {\n let indexName: string | undefined = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n } else {\n debugAssert(\n range === undefined,\n '3rd argument must not be defined if 2nd is a range.'\n );\n range = indexOrRange;\n }\n }\n return { index: indexName, range };\n }\n\n private cursor(options: IterateOptions): IDBRequest {\n let direction: IDBCursorDirection = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n const index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n } else {\n return index.openCursor(options.range, direction);\n }\n } else {\n return this.store.openCursor(options.range, direction);\n }\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest(request: IDBRequest): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n request.onsuccess = (event: Event) => {\n const result = (event.target as IDBRequest).result;\n resolve(result);\n };\n\n request.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n });\n}\n\n// Guard so we only report the error once.\nlet reportedIOSError = false;\nfunction checkForAndReportiOSError(error: DOMException): Error {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n if (iOSVersion >= 12.2 && iOSVersion < 13) {\n const IOS_ERROR =\n 'An internal error was encountered in the Indexed Database server';\n if (error.message.indexOf(IOS_ERROR) >= 0) {\n // Wrap error in a more descriptive one.\n const newError = new FirestoreError(\n 'internal',\n `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` +\n `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` +\n `for details and a potential workaround.`\n );\n if (!reportedIOSError) {\n reportedIOSError = true;\n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout(() => {\n throw newError;\n }, 0);\n }\n return newError;\n }\n }\n return error;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TranasactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail('Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n `BatchGetDocumentsRequest returned unexpected document: ${doc}`\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TranasactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { version } from '../package.json';\nimport {\n LiteAppCheckTokenProvider,\n LiteAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { databaseIdFromApp } from '../src/core/database_info';\nimport { setSDKVersion } from '../src/core/version';\nimport { Firestore } from '../src/lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\nexport function registerFirestore(): void {\n setSDKVersion(`${SDK_VERSION}_lite`);\n _registerComponent(\n new Component(\n 'firestore/lite',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new LiteAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new LiteAppCheckTokenProvider(\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n if (settings) {\n firestoreInstance._setSettings(settings);\n }\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation\n registerVersion('firestore-lite', version, '__RUNTIME_ENV__');\n registerVersion('firestore-lite', version, '__BUILD_TARGET__');\n}\n","/**\n * Firestore Lite\n *\n * @remarks Firestore Lite is a small online-only SDK that allows read\n * and write access to your Firestore database. All operations connect\n * directly to the backend, and `onSnapshot()` APIs are not supported.\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerFirestore } from './register';\nregisterFirestore();\n\nexport {\n aggregateQuerySnapshotEqual,\n getCount,\n getAggregate,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../src/lite-api/aggregate';\n\nexport {\n AggregateField,\n AggregateFieldType,\n AggregateSpec,\n AggregateSpecData,\n AggregateQuerySnapshot,\n AggregateType\n} from '../src/lite-api/aggregate_types';\n\nexport { FirestoreSettings as Settings } from '../src/lite-api/settings';\n\nexport {\n Firestore as Firestore,\n EmulatorMockTokenOptions,\n initializeFirestore,\n getFirestore,\n terminate,\n connectFirestoreEmulator\n} from '../src/lite-api/database';\n\nexport {\n DocumentData,\n UpdateData,\n WithFieldValue,\n PartialWithFieldValue,\n SetOptions,\n DocumentReference,\n Query,\n CollectionReference,\n collection,\n collectionGroup,\n doc,\n refEqual,\n queryEqual\n} from '../src/lite-api/reference';\n\nexport {\n and,\n endAt,\n endBefore,\n startAt,\n startAfter,\n limit,\n limitToLast,\n where,\n or,\n orderBy,\n query,\n QueryConstraint,\n QueryConstraintType,\n QueryCompositeFilterConstraint,\n QueryFilterConstraint,\n QueryFieldFilterConstraint,\n QueryOrderByConstraint,\n QueryLimitConstraint,\n QueryNonFilterConstraint,\n QueryStartAtConstraint,\n QueryEndAtConstraint,\n OrderByDirection,\n WhereFilterOp\n} from '../src/lite-api/query';\n\nexport {\n addDoc,\n deleteDoc,\n updateDoc,\n setDoc,\n getDoc,\n getDocs\n} from '../src/lite-api/reference_impl';\n\nexport {\n Primitive,\n NestedUpdateFields,\n ChildUpdateFields,\n AddPrefixToKeys,\n UnionToIntersection\n} from '../src/lite-api/types';\n\n// TOOD(firestorelite): Add tests when Queries are usable\nexport { FieldPath, documentId } from '../src/lite-api/field_path';\n\n// TOOD(firestorelite): Add tests when setDoc() is available\nexport { FieldValue } from '../src/lite-api/field_value';\n\nexport {\n increment,\n arrayRemove,\n arrayUnion,\n serverTimestamp,\n deleteField\n} from '../src/lite-api/field_value_impl';\n\nexport {\n FirestoreDataConverter,\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot,\n snapshotEqual\n} from '../src/lite-api/snapshot';\n\nexport { WriteBatch, writeBatch } from '../src/lite-api/write_batch';\n\nexport { TransactionOptions } from '../src/lite-api/transaction_options';\n\nexport { Transaction, runTransaction } from '../src/lite-api/transaction';\n\nexport { setLogLevel, LogLevelString as LogLevel } from '../src/util/log';\n\nexport { Bytes } from '../src/lite-api/bytes';\n\nexport { GeoPoint } from '../src/lite-api/geo_point';\n\nexport { Timestamp } from '../src/lite-api/timestamp';\n\nexport { FirestoreErrorCode, FirestoreError } from '../src/util/error';\n"],"names":["User","constructor","uid","this","isAuthenticated","toKey","isEqual","otherUser","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","SDK_VERSION","__PRIVATE_logClient","Logger","setLogLevel","logLevel","__PRIVATE_logDebug","msg","obj","LogLevel","DEBUG","args","map","__PRIVATE_argToString","debug","__PRIVATE_logError","ERROR","error","__PRIVATE_logWarn","WARN","warn","__PRIVATE_formatJSON","value","JSON","stringify","e","fail","__PRIVATE_failure","message","Error","__PRIVATE_hardAssert","assertion","__PRIVATE_debugCast","Code","FirestoreError","FirebaseError","code","super","toString","name","__PRIVATE_Deferred","promise","Promise","resolve","reject","__PRIVATE_OAuthToken","user","type","headers","Map","set","__PRIVATE_EmptyAuthCredentialsProvider","getToken","invalidateToken","start","asyncQueue","changeListener","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","token","__PRIVATE_LiteAuthCredentialsProvider","__PRIVATE_authProvider","auth","onInit","then","__PRIVATE_tokenData","accessToken","getUid","__PRIVATE_FirstPartyToken","__PRIVATE_sessionIndex","__PRIVATE_iamToken","__PRIVATE_authTokenFactory","__PRIVATE__headers","__PRIVATE_getAuthToken","__PRIVATE_authHeaderTokenValue","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","length","__PRIVATE_LiteAppCheckTokenProvider","__PRIVATE_appCheckProvider","appCheck","tokenResult","DatabaseInfo","databaseId","appId","persistenceKey","host","ssl","forceLongPolling","autoDetectLongPolling","longPollingOptions","useFetchStreams","DatabaseId","projectId","database","static","isDefaultDatabase","other","BasePath","segments","offset","undefined","len","comparator","child","nameOrPath","slice","limit","forEach","segment","push","construct","popFirst","size","popLast","firstSegment","lastSegment","get","index","isEmpty","isPrefixOf","__PRIVATE_i","isImmediateParentOf","potentialChild","fn","end","toArray","p1","p2","Math","min","left","right","ResourcePath","canonicalString","join","toUriEncodedString","encodeURIComponent","pathComponents","path","indexOf","split","filter","__PRIVATE_identifierRegExp","FieldPath","test","str","replace","isValidIdentifier","isKeyField","current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","c","next","DocumentKey","fromString","emptyPath","collectionGroup","hasCollectionId","collectionId","getCollectionGroup","getCollectionPath","k1","k2","__PRIVATE_validateNonEmptyArgument","__PRIVATE_functionName","__PRIVATE_argumentName","__PRIVATE_argument","__PRIVATE_validateDocumentPath","isDocumentKey","__PRIVATE_validateCollectionPath","__PRIVATE_valueDescription","input","substring","Array","__PRIVATE_customObjectName","__PRIVATE_tryGetCustomObjectType","__PRIVATE_cast","_delegate","description","__PRIVATE_validatePositiveNumber","n","__PRIVATE_cloneLongPollingOptions","options","clone","timeoutSeconds","__PRIVATE_lastUniqueDebugId","__PRIVATE_generateUniqueDebugId","__PRIVATE_generateInitialUniqueDebugId","round","__PRIVATE_maxResult","random","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","__PRIVATE_RPC_NAME_URL_MAPPING","__PRIVATE_RpcCode","RpcCode","__PRIVATE_mapCodeFromHttpStatus","status","__PRIVATE_FetchConnection","__PRIVATE_RestConnection","databaseInfo","proto","__PRIVATE_baseUrl","__PRIVATE_databasePath","__PRIVATE_requestParams","__PRIVATE_shouldResourcePathBeIncludedInRequest","__PRIVATE_invokeRPC","__PRIVATE_rpcName","__PRIVATE_req","__PRIVATE_authToken","appCheckToken","streamId","url","__PRIVATE_makeUrl","__PRIVATE_modifyHeadersForRequest","__PRIVATE_performRPCRequest","response","err","__PRIVATE_invokeStreamingRPC","request","__PRIVATE_expectedResponseCount","__PRIVATE_getGoogApiClientValue","key","__PRIVATE_urlRpcName","terminate","__PRIVATE_fetchImpl","__PRIVATE_openStream","async","body","__PRIVATE_requestJson","method","statusText","ok","__PRIVATE_errorResponse","json","isArray","__PRIVATE_errorMessage","_a","__PRIVATE_AggregateImpl","alias","aggregateType","fieldPath","__PRIVATE_randomBytes","__PRIVATE_nBytes","crypto","self","bytes","Uint8Array","getRandomValues","floor","__PRIVATE_AutoId","__PRIVATE_chars","__PRIVATE_maxMultiple","__PRIVATE_autoId","charAt","__PRIVATE_primitiveComparator","__PRIVATE_arrayEquals","every","__PRIVATE_objectSize","count","Object","prototype","hasOwnProperty","call","__PRIVATE_Base64DecodeError","ByteString","binaryString","base64","__PRIVATE_decodeBase64","__PRIVATE_encoded","atob","DOMException","array","__PRIVATE_binaryStringFromUint8Array","String","fromCharCode","Symbol","iterator","charCodeAt","done","toBase64","__PRIVATE_encodeBase64","raw","btoa","toUint8Array","__PRIVATE_uint8ArrayFromBinaryString","buffer","approximateByteSize","compareTo","EMPTY_BYTE_STRING","__PRIVATE_ISO_TIMESTAMP_REG_EXP","RegExp","__PRIVATE_normalizeTimestamp","date","nanos","__PRIVATE_fraction","exec","__PRIVATE_nanoStr","substr","Number","__PRIVATE_parsedDate","Date","seconds","getTime","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","blob","fromBase64String","fromUint8Array","Timestamp","nanoseconds","fromMillis","now","milliseconds","toDate","toMillis","_compareTo","toJSON","valueOf","__PRIVATE_adjustedSeconds","padStart","__PRIVATE_isServerTimestamp","_b","mapValue","fields","stringValue","__PRIVATE_getPreviousValue","previousValue","__PRIVATE_getLocalWriteTime","localWriteTime","timestampValue","MAX_VALUE","__type__","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_valueEquals","__PRIVATE_leftType","booleanValue","__PRIVATE_timestampEquals","__PRIVATE_leftTimestamp","__PRIVATE_rightTimestamp","__PRIVATE_blobEquals","bytesValue","referenceValue","__PRIVATE_geoPointEquals","geoPointValue","latitude","longitude","__PRIVATE_numberEquals","integerValue","__PRIVATE_n1","doubleValue","__PRIVATE_n2","isNaN","arrayValue","values","__PRIVATE_objectEquals","__PRIVATE_leftMap","__PRIVATE_rightMap","__PRIVATE_arrayValueContains","__PRIVATE_haystack","__PRIVATE_needle","find","v","__PRIVATE_valueCompare","__PRIVATE_rightType","__PRIVATE_compareNumbers","__PRIVATE_leftNumber","__PRIVATE_rightNumber","__PRIVATE_compareTimestamps","__PRIVATE_compareBlobs","__PRIVATE_leftBytes","__PRIVATE_rightBytes","__PRIVATE_compareReferences","__PRIVATE_leftPath","__PRIVATE_rightPath","__PRIVATE_leftSegments","__PRIVATE_rightSegments","comparison","__PRIVATE_compareGeoPoints","__PRIVATE_compareArrays","__PRIVATE_leftArray","__PRIVATE_rightArray","compare","__PRIVATE_compareMaps","__PRIVATE_leftKeys","keys","__PRIVATE_rightKeys","sort","__PRIVATE_keyCompare","__PRIVATE_refValue","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","source","assign","target","val","Bound","position","inclusive","__PRIVATE_boundEquals","Filter","FieldFilter","field","op","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matches","doc","data","matchesComparison","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_memoizedFlattenedFilters","__PRIVATE_compositeFilterIsConjunction","compositeFilter","reduce","result","__PRIVATE_subfilter","concat","__PRIVATE_filterEquals","__PRIVATE_f1","__PRIVATE_f2","__PRIVATE_fieldFilterEquals","__PRIVATE_compositeFilterEquals","__PRIVATE_f1Filter","fromName","__PRIVATE_extractDocumentKeysFromArrayValue","some","nullValue","OrderBy","dir","__PRIVATE_orderByEquals","SnapshotVersion","timestamp","toMicroseconds","toTimestamp","SortedMap","root","LLRBNode","EMPTY","insert","copy","BLACK","remove","node","cmp","__PRIVATE_prunedNodes","minKey","maxKey","inorderTraversal","action","k","__PRIVATE_descriptions","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","startKey","isReverse","nodeStack","getNext","pop","hasNext","peek","color","RED","fixUp","removeMin","isRed","moveRedLeft","__PRIVATE_smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","__PRIVATE_nl","__PRIVATE_nr","checkMaxDepth","__PRIVATE_blackDepth","check","pow","LLRBEmptyNode","SortedSet","has","elem","first","last","cb","forEachInRange","range","iter","forEachWhile","firstAfterOrEqual","SortedSetIterator","add","delete","unionWith","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","__PRIVATE_res","targetId","FieldMask","extraFields","__PRIVATE_mergedMaskSet","covers","__PRIVATE_fieldMaskPath","l","r","ObjectValue","__PRIVATE_currentLevel","getFieldsMap","setAll","parent","__PRIVATE_upserts","__PRIVATE_deletes","__PRIVATE_fieldsMap","applyChanges","__PRIVATE_nestedValue","__PRIVATE_inserts","MutableDocument","documentType","version","readTime","createTime","documentState","documentKey","empty","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","__PRIVATE_TargetImpl","orderBy","startAt","endAt","__PRIVATE_memoizedCanonicalId","__PRIVATE_newTarget","__PRIVATE_QueryImpl","explicitOrderBy","limitType","__PRIVATE_memoizedNormalizedOrderBy","__PRIVATE_memoizedTarget","__PRIVATE_memoizedAggregateTarget","__PRIVATE_isCollectionGroupQuery","query","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryImpl","__PRIVATE_fieldsNormalized","Set","__PRIVATE_lastDirection","__PRIVATE_inequalityFields","__PRIVATE_getInequalityFilterFields","keyField","__PRIVATE_queryToTarget","__PRIVATE__queryToTarget","__PRIVATE_orderBys","__PRIVATE_queryWithAddedFilter","__PRIVATE_newFilters","__PRIVATE_queryEquals","__PRIVATE_targetEquals","toNumber","serializer","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_toInteger","__PRIVATE_toDouble","useProto3Json","Infinity","TransformOperation","_","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","elements","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_operand","FieldTransform","transform","Precondition","updateTime","exists","isNone","Mutation","__PRIVATE_SetMutation","precondition","fieldTransforms","getFieldMask","__PRIVATE_PatchMutation","fieldMask","__PRIVATE_DeleteMutation","__PRIVATE_VerifyMutation","__PRIVATE_DIRECTIONS","__PRIVATE_dirs","__PRIVATE_OPERATORS","__PRIVATE_ops","__PRIVATE_COMPOSITE_OPERATORS","JsonProtoSerializer","toISOString","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","fromTimestamp","__PRIVATE_toResourceName","__PRIVATE_toResourcePath","__PRIVATE_resourcePath","__PRIVATE_fullyQualifiedPrefixPath","__PRIVATE_toName","__PRIVATE_resource","__PRIVATE_fromResourceName","__PRIVATE_isValidResourceName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_resourceName","__PRIVATE_toMutationDocument","__PRIVATE_fromBatchGetDocumentsResponse","__PRIVATE_fromFound","found","newFoundDocument","__PRIVATE_fromMissing","missing","newNoDocument","toMutation","mutation","update","updateMask","__PRIVATE_toDocumentMask","verify","updateTransforms","__PRIVATE_toFieldTransform","__PRIVATE_fieldTransform","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","__PRIVATE_toPrecondition","__PRIVATE_toQueryTarget","__PRIVATE_queryTarget","structuredQuery","from","allDescendants","__PRIVATE_toQueryPath","where","__PRIVATE_toFilters","__PRIVATE_toFilter","create","__PRIVATE_toOrder","order","__PRIVATE_toPropertyOrder","__PRIVATE_toFieldPathReference","direction","__PRIVATE_toDirection","__PRIVATE_toInt32Proto","__PRIVATE_toStartAtCursor","cursor","before","__PRIVATE_toEndAtCursor","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","__PRIVATE_toUnaryOrFieldFilter","unaryFilter","fieldFilter","__PRIVATE_toCompositeFilter","__PRIVATE_protos","__PRIVATE_canonicalFields","fieldPaths","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","__PRIVATE_queue","timerId","__PRIVATE_initialDelayMs","__PRIVATE_backoffFactor","__PRIVATE_maxDelayMs","__PRIVATE_currentBaseMs","__PRIVATE_timerPromise","__PRIVATE_lastAttemptTime","reset","__PRIVATE_resetToMax","__PRIVATE_backoffAndRun","cancel","__PRIVATE_desiredDelayWithJitterMs","__PRIVATE_jitterDelayMs","__PRIVATE_delaySoFarMs","max","__PRIVATE_remainingDelayMs","enqueueAfterDelay","__PRIVATE_skipBackoff","skipDelay","__PRIVATE_DatastoreImpl","Datastore","authCredentials","appCheckCredentials","connection","__PRIVATE_terminated","__PRIVATE_verifyInitialized","all","catch","__PRIVATE_invokeCommitRpc","datastore","mutations","__PRIVATE_datastoreImpl","writes","m","__PRIVATE_invokeBatchGetDocumentsRpc","documents","docs","__PRIVATE_invokeRunQueryRpc","B","document","__PRIVATE_fromDocument","__PRIVATE_invokeRunAggregationQueryRpc","__PRIVATE_aggregates","X","__PRIVATE_aliasMap","__PRIVATE_toRunAggregationQueryRequest","aggregations","__PRIVATE_aggregationNum","__PRIVATE_aggregate","__PRIVATE_serverAlias","avg","sum","structuredAggregationQuery","__PRIVATE_queryToAggregateTarget","__PRIVATE_filteredResult","__PRIVATE_unmappedAggregateFields","aggregateFields","__PRIVATE_accumulator","__PRIVATE_datastoreInstances","__PRIVATE_getDatastore","firestore","_terminated","__PRIVATE_newConnection","fetch","bind","__PRIVATE_makeDatabaseInfo","settings","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","_databaseId","app","_persistenceKey","_freezeSettings","__PRIVATE_newDatastore","_authCredentials","_appCheckCredentials","FirestoreSettingsImpl","credentials","ignoreUndefinedProperties","localCache","cacheSizeBytes","__PRIVATE_validateIsNotUsedTogether","optionName1","argument1","optionName2","argument2","__PRIVATE_validateLongPollingOptions","__PRIVATE_longPollingOptionsEqual","__PRIVATE_options1","__PRIVATE_options2","Firestore","_app","_settings","_settingsFrozen","_initialized","_terminateTask","_setSettings","__PRIVATE_makeAuthCredentialsProvider","_getSettings","_delete","_terminate","__PRIVATE_removeComponents","initializeFirestore","provider","_getProvider","isInitialized","initialize","instanceIdentifier","getFirestore","__PRIVATE_appOrDatabaseId","__PRIVATE_optionalDatabaseId","getApp","db","getImmediate","identifier","__PRIVATE_emulator","getDefaultEmulatorHostnameAndPort","connectFirestoreEmulator","port","__PRIVATE_newHostSetting","mockUserToken","createMockUserToken","sub","user_id","_removeServiceInstance","AggregateField","_internalFieldPath","AggregateQuerySnapshot","_userDataWriter","_data","convertObjectMap","Query","converter","_query","withConverter","DocumentReference","_key","_path","id","CollectionReference","__PRIVATE_newQueryForPath","parentPath","collection","pathSegments","getModularInstance","__PRIVATE_absolutePath","__PRIVATE_newQueryForCollectionGroup","arguments","newId","refEqual","queryEqual","Bytes","byteString","_byteString","fieldNames","_internalPath","__PRIVATE_InternalFieldPath","documentId","FieldValue","_methodName","GeoPoint","isFinite","_lat","_long","__PRIVATE_RESERVED_FIELD_REGEX","ParsedSetData","ParsedUpdateData","__PRIVATE_isWrite","__PRIVATE_dataSource","__PRIVATE_ParseContextImpl","__PRIVATE_validatePath","__PRIVATE_contextWith","configuration","__PRIVATE_childContextForField","__PRIVATE_childPath","context","__PRIVATE_arrayElement","__PRIVATE_validatePathSegment","__PRIVATE_childContextForFieldPath","__PRIVATE_childContextForArray","__PRIVATE_createError","reason","methodName","__PRIVATE_hasConverter","__PRIVATE_targetDoc","contains","__PRIVATE_UserDataReader","__PRIVATE_createContext","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","__PRIVATE_userDataReader","merge","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_updateData","__PRIVATE_parseObject","__PRIVATE_validatedFieldPaths","__PRIVATE_stringOrFieldPath","__PRIVATE_fieldPathFromArgument","__PRIVATE_fieldMaskContains","__PRIVATE_DeleteFieldValueImpl","_toFieldTransform","__PRIVATE_createSentinelChildContext","__PRIVATE_fieldValue","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_ArrayUnionFieldValueImpl","__PRIVATE__elements","__PRIVATE_parseContext","__PRIVATE_parsedElements","element","__PRIVATE_parseData","arrayUnion","deepEqual","__PRIVATE_ArrayRemoveFieldValueImpl","__PRIVATE_NumericIncrementFieldValueImpl","__PRIVATE__operand","__PRIVATE_numericIncrement","__PRIVATE_parseUpdateData","__PRIVATE_fieldMaskPaths","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_childContext","__PRIVATE_parsedValue","mask","__PRIVATE_parseUpdateVarargs","moreFieldsAndValues","__PRIVATE_parseQueryValue","__PRIVATE_allowArrays","__PRIVATE_looksLikeJsonObject","__PRIVATE_parseSentinelFieldValue","__PRIVATE_parseArray","__PRIVATE_entryIndex","entry","__PRIVATE_parsedEntry","__PRIVATE_parseScalarValue","fromDate","__PRIVATE_thisDb","__PRIVATE_otherDb","__PRIVATE_isPlainObject","getPrototypeOf","__PRIVATE_FIELD_PATH_RESERVED","search","__PRIVATE_hasPath","__PRIVATE_hasDocument","DocumentSnapshot","_firestore","_document","_converter","ref","snapshot","QueryDocumentSnapshot","fromFirestore","convertValue","QuerySnapshot","_docs","callback","thisArg","snapshotEqual","arg","AppliableConstraint","QueryConstraint","__PRIVATE_queryConstraint","__PRIVATE_additionalQueryConstraints","queryConstraints","__PRIVATE_validateQueryConstraintArray","__PRIVATE_compositeFilterCount","QueryCompositeFilterConstraint","__PRIVATE_fieldFilterCount","QueryFieldFilterConstraint","constraint","_apply","_field","_op","_value","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_reader","__PRIVATE_newQueryFilter","__PRIVATE_dataReader","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_referenceList","__PRIVATE_parseDocumentIdValue","opStr","_create","_queryConstraints","__PRIVATE_parsedFilters","__PRIVATE_parsedFilter","_getOperator","__PRIVATE_validateNewFilter","__PRIVATE_testQuery","__PRIVATE_subFilters","__PRIVATE_subFilter","_getQueryConstraints","or","__PRIVATE_validateQueryFilterConstraint","and","QueryOrderByConstraint","_direction","__PRIVATE_newQueryOrderBy","__PRIVATE_queryWithAddedOrderBy","__PRIVATE_newOrderBy","directionStr","QueryLimitConstraint","_limit","_limitType","__PRIVATE_queryWithLimit","limitToLast","QueryStartAtConstraint","_docOrFields","_inclusive","bound","__PRIVATE_newQueryBoundFromDocOrFields","__PRIVATE_queryWithStartAt","__PRIVATE_docOrFields","startAfter","QueryEndAtConstraint","__PRIVATE_queryWithEndAt","endBefore","__PRIVATE_newQueryBoundFromDocument","components","__PRIVATE_newQueryBoundFromFields","__PRIVATE_rawValue","__PRIVATE_wrapped","__PRIVATE_documentIdValue","operator","__PRIVATE_conflictingOp","__PRIVATE_findOpInsideFilters","__PRIVATE_operators","__PRIVATE_conflictingOps","__PRIVATE_applyFirestoreDataConverter","__PRIVATE_convertedValue","toFirestore","__PRIVATE_LiteUserDataWriter","AbstractUserDataWriter","serverTimestampBehavior","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","__PRIVATE_normalizedValue","convertDocumentKey","expectedDatabaseId","getDoc","reference","userDataWriter","getDocs","__PRIVATE_validateHasExplicitOrderByForLimitToLast","reverse","setDoc","__PRIVATE_parsed","none","updateDoc","__PRIVATE_fieldOrUpdateData","deleteDoc","addDoc","__PRIVATE_docRef","getCount","getAggregate","aggregateSpec","__PRIVATE_internalAggregates","__PRIVATE_mapToArray","__PRIVATE_aggregateResult","__PRIVATE_convertToAggregateQuerySnapshot","average","aggregateFieldEqual","aggregateQuerySnapshotEqual","deleteField","serverTimestamp","arrayRemove","WriteBatch","_commitHandler","_mutations","_committed","_dataReader","documentRef","_verifyNotCommitted","__PRIVATE_validateReference","commit","writeBatch","Transaction","readVersions","committed","lastTransactionError","writtenDocs","ensureCommitNotCalled","recordVersion","write","preconditionForUpdate","__PRIVATE_unwritten","fromPath","__PRIVATE_docVersion","__PRIVATE_existingVersion","__PRIVATE_DEFAULT_TRANSACTION_OPTIONS","maxAttempts","__PRIVATE_TransactionRunner","updateFunction","deferred","__PRIVATE_attemptsRemaining","__PRIVATE_backoff","__PRIVATE_run","__PRIVATE_runWithBackOff","transaction","__PRIVATE_userPromise","__PRIVATE_tryRunUpdateFunction","enqueueAndForget","__PRIVATE_commitError","__PRIVATE_handleTransactionError","__PRIVATE_userPromiseError","__PRIVATE_isRetryableTransactionError","__PRIVATE_isPermanentError","getDocument","DelayedOperation","targetTimeMs","removalCallback","delayMs","__PRIVATE_targetTime","__PRIVATE_delayedOp","timerHandle","setTimeout","handleDelayElapsed","clearTimeout","__PRIVATE_AsyncQueueImpl","__PRIVATE_tail","__PRIVATE_retryableOps","__PRIVATE__isShuttingDown","__PRIVATE_delayedOperations","__PRIVATE_operationInProgress","__PRIVATE_skipNonRestrictedTasks","__PRIVATE_timerIdsToSkip","__PRIVATE_visibilityHandler","visibilityState","addEventListener","isShuttingDown","enqueue","enqueueAndForgetEvenWhileRestricted","__PRIVATE_verifyNotFailed","__PRIVATE_enqueueInternal","enterRestrictedMode","purgeExistingTasks","removeEventListener","task","__PRIVATE_retryNextOp","shift","__PRIVATE_isIndexedDbTransactionError","__PRIVATE_newTail","__PRIVATE_getMessageOrStack","stack","includes","createAndSchedule","__PRIVATE_removedOp","__PRIVATE_removeDelayedOperation","verifyOperationInProgress","__PRIVATE_currentTail","__PRIVATE_containsDelayedOperation","__PRIVATE_runAllDelayedOperationsUntil","__PRIVATE_lastTimerId","__PRIVATE_drain","a","b","__PRIVATE_skipDelaysForTimerId","splice","_transaction","lookup","runTransaction","__PRIVATE_optionsWithDefaults","__PRIVATE_validateTransactionOptions","__PRIVATE_newAsyncQueue","__PRIVATE_internalTransaction","__PRIVATE_registerFirestore","__PRIVATE_setSDKVersion","_registerComponent","Component","container","getProvider","__PRIVATE_firestoreInstance","__PRIVATE_databaseIdFromApp","apply","setMultipleInstances","registerVersion"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqBaA,MAAAA,IAAAA,CAAAA;IAUXC,WAAqBC,CAAAA,CAAAA,EAAAA;AAAAC,QAAAA,IAAAA,CAAGD,GAAHA,GAAAA,CAAAA,CAAAA;;AAErBE,IAAAA,eAAAA,GAAAA;AACE,QAAA,OAAmB,QAAZD,IAAKD,CAAAA,GAAAA,CAAAA;;;;;AAOdG,WAAAA,KAAAA,GAAAA;AACE,QAAA,OAAIF,IAAKC,CAAAA,eAAAA,EAAAA,GACA,MAASD,GAAAA,IAAAA,CAAKD,GAEd,GAAA,gBAAA,CAAA;;IAIXI,OAAQC,CAAAA,CAAAA,EAAAA;QACN,OAAOA,CAAAA,CAAUL,QAAQC,IAAKD,CAAAA,GAAAA,CAAAA;;;;+BA3BhBM,IAAAA,CAAAA,eAAAA,GAAkB,IAAIR,IAAK,CAAA,IAAA,CAAA;;;AAI3BA,IAAAA,CAAAS,qBAAqB,IAAIT,IAAAA,CAAK,2BAC9BA,IAAAU,CAAAA,WAAAA,GAAc,IAAIV,IAAK,CAAA,iBAAA,CAAA;AACvBA,IAAAW,CAAAA,SAAAA,GAAY,IAAIX,IAAK,CAAA,WAAA,CAAA,CAAA;;;;;;;;;;;;;;;;;;ACVhC,IAAIY,CAAAA,GAAAA,QAAAA,CAAAA;;;;;;;;;;;;;;;;;;ACKX,MAAMC,CAAAA,GAAY,IAAIC,MAAO,CAAA,qBAAA,CAAA,CAAA;;;;;;;;;;;;;;AAoBvB,IAAA,SAAUC,WAAYC,CAAAA,CAAAA,EAAAA;AAC1BH,IAAAA,CAAAA,CAAUE,WAAYC,CAAAA,CAAAA,CAAAA,CAAAA;;;AAGRC,SAAAA,kBAAAA,CAASC,CAAgBC,EAAAA,GAAAA,CAAAA,EAAAA;IACvC,IAAIN,CAAAA,CAA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