import { base64 as t, getUA as e, isMobileCordova as n, isReactNative as s, isElectron as i, isIE as r, isUWP as o, isBrowserExtension as c } from "@firebase/util";

import { Logger as a, LogLevel as u } from "@firebase/logger";

import { XhrIo as h, EventType as l, ErrorCode as _, createWebChannelTransport as f, getStatEventTarget as d, WebChannel as w, Event as E, Stat as T } from "@firebase/webchannel-wrapper";

/** Converts a Base64 encoded string to a binary string. */
function I(e) {
    return String.fromCharCode.apply(null, 
    // We use `decodeStringToByteArray()` instead of `decodeString()` since
    // `decodeString()` returns Unicode strings, which doesn't match the values
    // returned by `atob()`'s Latin1 representation.
    t.decodeStringToByteArray(e, false));
}

/** Converts a binary string to a Base64 encoded string. */
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const m = new a("@firebase/firestore");

// Helper methods are needed because variables can't be exported as read/write
function A() {
    return m.logLevel;
}

/**
 * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
 *
 * @param logLevel - The verbosity you set for activity and error logging. Can
 *   be any of the following values:
 *
 *   <ul>
 *     <li>`debug` for the most verbose logging level, primarily for
 *     debugging.</li>
 *     <li>`error` to log errors only.</li>
 *     <li><code>`silent` to turn off logging.</li>
 *   </ul>
 */ function R(t, ...e) {
    if (m.logLevel <= u.DEBUG) {
        const n = e.map(g);
        m.debug("Firestore (8.2.2): " + t, ...n);
    }
}

function P(t, ...e) {
    if (m.logLevel <= u.ERROR) {
        const n = e.map(g);
        m.error("Firestore (8.2.2): " + t, ...n);
    }
}

function y(t, ...e) {
    if (m.logLevel <= u.WARN) {
        const n = e.map(g);
        m.warn("Firestore (8.2.2): " + t, ...n);
    }
}

/**
 * Converts an additional log parameter to a string representation.
 */ function g(t) {
    if ("string" == typeof t) return t;
    try {
        return e = t, JSON.stringify(e);
    } catch (e) {
        // Converting to JSON failed, just log the object directly
        return t;
    }
    /**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
    /** Formats an object as a JSON string, suitable for logging. */
    var e;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Unconditionally fails, throwing an Error with the given message.
 * Messages are stripped in production builds.
 *
 * Returns `never` and can be used in expressions:
 * @example
 * let futureVar = fail('not implemented yet');
 */ function V(t = "Unexpected state") {
    // Log the failure in addition to throw an exception, just in case the
    // exception is swallowed.
    const e = "FIRESTORE (8.2.2) INTERNAL ASSERTION FAILED: " + t;
    // NOTE: We don't use FirestoreError here because these are internal failures
    // that cannot be handled by the user. (Also it would create a circular
    // dependency between the error and assert modules which doesn't work.)
    throw P(e), new Error(e);
}

/**
 * Fails if the given assertion condition is false, throwing an Error with the
 * given message if it did.
 *
 * Messages are stripped in production builds.
 */ function p(t, e) {
    t || V();
}

/**
 * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
 * instance of `T` before casting.
 */ function b(t, 
// eslint-disable-next-line @typescript-eslint/no-explicit-any
e) {
    return t;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Generates `nBytes` of random bytes.
 *
 * If `nBytes < 0` , an error will be thrown.
 */ function v(t) {
    // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.
    const e = 
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);
    if (e && "function" == typeof e.getRandomValues) e.getRandomValues(n); else 
    // Falls back to Math.random
    for (let e = 0; e < t; e++) n[e] = Math.floor(256 * Math.random());
    return n;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class S {
    static t() {
        // Alphanumeric characters
        const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length;
        // The largest byte value that is a multiple of `char.length`.
                let n = "";
        for (;n.length < 20; ) {
            const s = v(40);
            for (let i = 0; i < s.length; ++i) 
            // Only accept values that are [0, maxMultiple), this ensures they can
            // be evenly mapped to indices of `chars` via a modulo operation.
            n.length < 20 && s[i] < e && (n += t.charAt(s[i] % t.length));
        }
        return n;
    }
}

function D(t, e) {
    return t < e ? -1 : t > e ? 1 : 0;
}

/** Helper to compare arrays using isEqual(). */ function C(t, e, n) {
    return t.length === e.length && t.every(((t, s) => n(t, e[s])));
}

/**
 * Returns the immediate lexicographically-following string. This is useful to
 * construct an inclusive range for indexeddb iterators.
 */ function x(t) {
    // Return the input string, with an additional NUL byte appended.
    return t + "\0";
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Immutable class that represents a "proto" byte string.
 *
 * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
 * sent on the wire. This class abstracts away this differentiation by holding
 * the proto byte string in a common class that must be converted into a string
 * before being sent as a proto.
 */ class N {
    constructor(t) {
        this.i = t;
    }
    static fromBase64String(t) {
        const e = I(t);
        return new N(e);
    }
    static fromUint8Array(t) {
        const e = 
        /**
 * Helper function to convert an Uint8array to a binary string.
 */
        function(t) {
            let e = "";
            for (let n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]);
            return e;
        }
        /**
 * Helper function to convert a binary string to an Uint8Array.
 */ (t);
        return new N(e);
    }
    toBase64() {
        return function(e) {
            const n = [];
            for (let t = 0; t < e.length; t++) n[t] = e.charCodeAt(t);
            return t.encodeByteArray(n, !1);
        }(this.i);
    }
    toUint8Array() {
        return function(t) {
            const e = new Uint8Array(t.length);
            for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);
            return e;
        }
        /**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ (this.i);
    }
    o() {
        return 2 * this.i.length;
    }
    u(t) {
        return D(this.i, t.i);
    }
    isEqual(t) {
        return this.i === t.i;
    }
}

N.h = new N("");

const O = {
    // Causes are copied from:
    // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
    /** Not an error; returned on success. */
    OK: "ok",
    /** The operation was cancelled (typically by the caller). */
    CANCELLED: "cancelled",
    /** Unknown error or an error from a different error domain. */
    UNKNOWN: "unknown",
    /**
     * Client specified an invalid argument. Note that this differs from
     * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
     * problematic regardless of the state of the system (e.g., a malformed file
     * name).
     */
    INVALID_ARGUMENT: "invalid-argument",
    /**
     * Deadline expired before operation could complete. For operations that
     * change the state of the system, this error may be returned even if the
     * operation has completed successfully. For example, a successful response
     * from a server could have been delayed long enough for the deadline to
     * expire.
     */
    DEADLINE_EXCEEDED: "deadline-exceeded",
    /** Some requested entity (e.g., file or directory) was not found. */
    NOT_FOUND: "not-found",
    /**
     * Some entity that we attempted to create (e.g., file or directory) already
     * exists.
     */
    ALREADY_EXISTS: "already-exists",
    /**
     * The caller does not have permission to execute the specified operation.
     * PERMISSION_DENIED must not be used for rejections caused by exhausting
     * some resource (use RESOURCE_EXHAUSTED instead for those errors).
     * PERMISSION_DENIED must not be used if the caller can not be identified
     * (use UNAUTHENTICATED instead for those errors).
     */
    PERMISSION_DENIED: "permission-denied",
    /**
     * The request does not have valid authentication credentials for the
     * operation.
     */
    UNAUTHENTICATED: "unauthenticated",
    /**
     * Some resource has been exhausted, perhaps a per-user quota, or perhaps the
     * entire file system is out of space.
     */
    RESOURCE_EXHAUSTED: "resource-exhausted",
    /**
     * Operation was rejected because the system is not in a state required for
     * the operation's execution. For example, directory to be deleted may be
     * non-empty, an rmdir operation is applied to a non-directory, etc.
     *
     * A litmus test that may help a service implementor in deciding
     * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
     *  (a) Use UNAVAILABLE if the client can retry just the failing call.
     *  (b) Use ABORTED if the client should retry at a higher-level
     *      (e.g., restarting a read-modify-write sequence).
     *  (c) Use FAILED_PRECONDITION if the client should not retry until
     *      the system state has been explicitly fixed. E.g., if an "rmdir"
     *      fails because the directory is non-empty, FAILED_PRECONDITION
     *      should be returned since the client should not retry unless
     *      they have first fixed up the directory by deleting files from it.
     *  (d) Use FAILED_PRECONDITION if the client performs conditional
     *      REST Get/Update/Delete on a resource and the resource on the
     *      server does not match the condition. E.g., conflicting
     *      read-modify-write on the same resource.
     */
    FAILED_PRECONDITION: "failed-precondition",
    /**
     * The operation was aborted, typically due to a concurrency issue like
     * sequencer check failures, transaction aborts, etc.
     *
     * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
     * and UNAVAILABLE.
     */
    ABORTED: "aborted",
    /**
     * Operation was attempted past the valid range. E.g., seeking or reading
     * past end of file.
     *
     * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
     * if the system state changes. For example, a 32-bit file system will
     * generate INVALID_ARGUMENT if asked to read at an offset that is not in the
     * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
     * an offset past the current file size.
     *
     * There is a fair bit of overlap between FAILED_PRECONDITION and
     * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
     * when it applies so that callers who are iterating through a space can
     * easily look for an OUT_OF_RANGE error to detect when they are done.
     */
    OUT_OF_RANGE: "out-of-range",
    /** Operation is not implemented or not supported/enabled in this service. */
    UNIMPLEMENTED: "unimplemented",
    /**
     * Internal errors. Means some invariants expected by underlying System has
     * been broken. If you see one of these errors, Something is very broken.
     */
    INTERNAL: "internal",
    /**
     * The service is currently unavailable. This is a most likely a transient
     * condition and may be corrected by retrying with a backoff.
     *
     * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
     * and UNAVAILABLE.
     */
    UNAVAILABLE: "unavailable",
    /** Unrecoverable data loss or corruption. */
    DATA_LOSS: "data-loss"
};

/** An error returned by a Firestore operation. */ class F extends Error {
    /** @hideconstructor */
    constructor(t, e) {
        super(e), this.code = t, this.message = e, this.name = "FirebaseError", 
        // HACK: We write a toString property directly because Error is not a real
        // class and so inheritance does not work correctly. We could alternatively
        // do the same "back-door inheritance" trick that FirebaseError does.
        this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An immutable object representing an array of bytes.
 */ class k {
    /** @hideconstructor */
    constructor(t) {
        this.l = t;
    }
    /**
     * Creates a new `Bytes` object from the given Base64 string, converting it to
     * bytes.
     *
     * @param base64 - The Base64 string used to create the `Bytes` object.
     */    static fromBase64String(t) {
        try {
            return new k(N.fromBase64String(t));
        } catch (t) {
            throw new F(O.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + t);
        }
    }
    /**
     * Creates a new `Bytes` object from the given Uint8Array.
     *
     * @param array - The Uint8Array used to create the `Bytes` object.
     */    static fromUint8Array(t) {
        return new k(N.fromUint8Array(t));
    }
    /**
     * Returns the underlying bytes as a Base64-encoded string.
     *
     * @returns The Base64-encoded string created from the `Bytes` object.
     */    toBase64() {
        return this.l.toBase64();
    }
    /**
     * Returns the underlying bytes in a new `Uint8Array`.
     *
     * @returns The Uint8Array created from the `Bytes` object.
     */    toUint8Array() {
        return this.l.toUint8Array();
    }
    /**
     * Returns a string representation of the `Bytes` object.
     *
     * @returns A string representation of the `Bytes` object.
     */    toString() {
        return "Bytes(base64: " + this.toBase64() + ")";
    }
    /**
     * Returns true if this `Bytes` object is equal to the provided one.
     *
     * @param other - The `Bytes` object to compare against.
     * @returns true if this `Bytes` object is equal to the provided one.
     */    isEqual(t) {
        return this.l.isEqual(t.l);
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A class implemented by all API types of the legacy Firestore API which
 * contains a reference to the API type in the firestore-exp API. All internal
 * code unwraps these references, which allows us to only use firestore-exp
 * types in the SDK.
 */ class M {
    constructor(t) {
        this._ = t;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Helper function to assert Uint8Array is available at runtime. */ function L() {
    if ("undefined" == typeof Uint8Array) throw new F(O.UNIMPLEMENTED, "Uint8Arrays are not available in this environment.");
}

/** Immutable class holding a blob (binary data) */ class $ extends M {
    static fromBase64String(t) {
        return new $(k.fromBase64String(t));
    }
    static fromUint8Array(t) {
        return L(), new $(k.fromUint8Array(t));
    }
    toBase64() {
        return this._.toBase64();
    }
    toUint8Array() {
        return L(), this._.toUint8Array();
    }
    isEqual(t) {
        return this._.isEqual(t._);
    }
    toString() {
        return "Blob(base64: " + this.toBase64() + ")";
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class B {
    /**
     * Constructs a DatabaseInfo using the provided host, databaseId and
     * persistenceKey.
     *
     * @param databaseId - The database to use.
     * @param persistenceKey - A unique identifier for this Firestore's local
     * storage (used in conjunction with the databaseId).
     * @param host - The Firestore backend host to connect to.
     * @param ssl - Whether to use SSL when connecting.
     * @param forceLongPolling - Whether to use the forceLongPolling option
     * when using WebChannel as the network transport.
     * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
     * option when using WebChannel as the network transport.
     */
    constructor(t, e, n, s, i, r) {
        this.T = t, this.persistenceKey = e, this.host = n, this.ssl = s, this.forceLongPolling = i, 
        this.I = r;
    }
}

/** The default database name for a project. */
/** Represents the database ID a Firestore client is associated with. */
class q {
    constructor(t, e) {
        this.projectId = t, this.database = e || "(default)";
    }
    get m() {
        return "(default)" === this.database;
    }
    isEqual(t) {
        return t instanceof q && t.projectId === this.projectId && t.database === this.database;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Simple wrapper around a nullable UID. Mostly exists to make code more
 * readable.
 */ class U {
    constructor(t) {
        this.uid = t;
    }
    A() {
        return null != this.uid;
    }
    /**
     * Returns a key representing this user, suitable for inclusion in a
     * dictionary.
     */    R() {
        return this.A() ? "uid:" + this.uid : "anonymous-user";
    }
    isEqual(t) {
        return t.uid === this.uid;
    }
}

/** A user with a null UID. */ U.UNAUTHENTICATED = new U(null), 
// TODO(mikelehen): Look into getting a proper uid-equivalent for
// non-FirebaseAuth providers.
U.P = new U("google-credentials-uid"), U.g = new U("first-party-uid");

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class Q {
    constructor(t, e) {
        this.user = e, this.type = "OAuth", this.V = {}, 
        // Set the headers using Object Literal notation to avoid minification
        this.V.Authorization = "Bearer " + t;
    }
}

/** A CredentialsProvider that always yields an empty token. */ class K {
    constructor() {
        /**
         * Stores the listener registered with setChangeListener()
         * This isn't actually necessary since the UID never changes, but we use this
         * to verify the listen contract is adhered to in tests.
         */
        this.p = null;
    }
    getToken() {
        return Promise.resolve(null);
    }
    v() {}
    S(t) {
        this.p = t, 
        // Fire with initial user.
        t(U.UNAUTHENTICATED);
    }
    D() {
        this.p = null;
    }
}

class j {
    constructor(t) {
        /**
         * The auth token listener registered with FirebaseApp, retained here so we
         * can unregister it.
         */
        this.C = null, 
        /** Tracks the current User. */
        this.currentUser = U.UNAUTHENTICATED, this.N = !1, 
        /**
         * Counter used to detect if the token changed while a getToken request was
         * outstanding.
         */
        this.O = 0, 
        /** The listener registered with setChangeListener(). */
        this.p = null, this.forceRefresh = !1, this.C = () => {
            this.O++, this.currentUser = this.F(), this.N = !0, this.p && this.p(this.currentUser);
        }, this.O = 0, this.auth = t.getImmediate({
            optional: !0
        }), this.auth ? this.auth.addAuthTokenListener(this.C) : (
        // if auth is not available, invoke tokenListener once with null token
        this.C(null), t.get().then((t => {
            this.auth = t, this.C && 
            // tokenListener can be removed by removeChangeListener()
            this.auth.addAuthTokenListener(this.C);
        }), (() => {})));
    }
    getToken() {
        // Take note of the current value of the tokenCounter so that this method
        // can fail (with an ABORTED error) if there is a token change while the
        // request is outstanding.
        const t = this.O, e = this.forceRefresh;
        return this.forceRefresh = !1, this.auth ? this.auth.getToken(e).then((e => 
        // Cancel the request since the token changed while the request was
        // outstanding so the response is potentially for a previous user (which
        // user, we can't be sure).
        this.O !== t ? (R("FirebaseCredentialsProvider", "getToken aborted due to token change."), 
        this.getToken()) : e ? (p("string" == typeof e.accessToken), new Q(e.accessToken, this.currentUser)) : null)) : Promise.resolve(null);
    }
    v() {
        this.forceRefresh = !0;
    }
    S(t) {
        this.p = t, 
        // Fire the initial event
        this.N && t(this.currentUser);
    }
    D() {
        this.auth && this.auth.removeAuthTokenListener(this.C), this.C = null, this.p = null;
    }
    // Auth.getUid() can return null even with a user logged in. It is because
    // getUid() is synchronous, but the auth code populating Uid is asynchronous.
    // This method should only be called in the AuthTokenListener callback
    // to guarantee to get the actual user.
    F() {
        const t = this.auth && this.auth.getUid();
        return p(null === t || "string" == typeof t), new U(t);
    }
}

/*
 * FirstPartyToken provides a fresh token each time its value
 * is requested, because if the token is too old, requests will be rejected.
 * Technically this may no longer be necessary since the SDK should gracefully
 * recover from unauthenticated errors (see b/33147818 for context), but it's
 * safer to keep the implementation as-is.
 */ class W {
    constructor(t, e) {
        this.k = t, this.M = e, this.type = "FirstParty", this.user = U.g;
    }
    get V() {
        const t = {
            "X-Goog-AuthUser": this.M
        }, e = this.k.auth.getAuthHeaderValueForFirstParty([]);
        // Use array notation to prevent minification
                return e && (t.Authorization = e), t;
    }
}

/*
 * Provides user credentials required for the Firestore JavaScript SDK
 * to authenticate the user, using technique that is only available
 * to applications hosted by Google.
 */ class G {
    constructor(t, e) {
        this.k = t, this.M = e;
    }
    getToken() {
        return Promise.resolve(new W(this.k, this.M));
    }
    S(t) {
        // Fire with initial uid.
        t(U.g);
    }
    D() {}
    v() {}
}

/**
 * Builds a CredentialsProvider depending on the type of
 * the credentials passed in.
 */
/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to
 * exceed. All subsequent calls to next will return increasing values. If provided with a
 * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as
 * well as write out sequence numbers that it produces via `next()`.
 */
class z {
    constructor(t, e) {
        this.previousValue = t, e && (e.L = t => this.$(t), this.B = t => e.q(t));
    }
    $(t) {
        return this.previousValue = Math.max(t, this.previousValue), this.previousValue;
    }
    next() {
        const t = ++this.previousValue;
        return this.B && this.B(t), t;
    }
}

z.U = -1;

/**
 * A `Timestamp` represents a point in time independent of any time zone or
 * calendar, represented as seconds and fractions of seconds at nanosecond
 * resolution in UTC Epoch time.
 *
 * It is encoded using the Proleptic Gregorian Calendar which extends the
 * Gregorian calendar backwards to year one. It is encoded assuming all minutes
 * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
 * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
 * 9999-12-31T23:59:59.999999999Z.
 *
 * @see https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto
 */
class H {
    /**
     * Creates a new timestamp.
     *
     * @param seconds - The number of seconds of UTC time since Unix epoch
     *     1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
     *     9999-12-31T23:59:59Z inclusive.
     * @param nanoseconds - The non-negative fractions of a second at nanosecond
     *     resolution. Negative second values with fractions must still have
     *     non-negative nanoseconds values that count forward in time. Must be
     *     from 0 to 999,999,999 inclusive.
     */
    constructor(t, e) {
        if (this.seconds = t, this.nanoseconds = e, e < 0) throw new F(O.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
        if (e >= 1e9) throw new F(O.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
        if (t < -62135596800) throw new F(O.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
        // This will break in the year 10,000.
                if (t >= 253402300800) throw new F(O.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
    }
    /**
     * Creates a new timestamp with the current date, with millisecond precision.
     *
     * @returns a new timestamp representing the current date.
     */    static now() {
        return H.fromMillis(Date.now());
    }
    /**
     * Creates a new timestamp from the given date.
     *
     * @param date - The date to initialize the `Timestamp` from.
     * @returns A new `Timestamp` representing the same point in time as the given
     *     date.
     */    static fromDate(t) {
        return H.fromMillis(t.getTime());
    }
    /**
     * Creates a new timestamp from the given number of milliseconds.
     *
     * @param milliseconds - Number of milliseconds since Unix epoch
     *     1970-01-01T00:00:00Z.
     * @returns A new `Timestamp` representing the same point in time as the given
     *     number of milliseconds.
     */    static fromMillis(t) {
        const e = Math.floor(t / 1e3);
        return new H(e, 1e6 * (t - 1e3 * e));
    }
    /**
     * Converts a `Timestamp` to a JavaScript `Date` object. This conversion causes
     * a loss of precision since `Date` objects only support millisecond precision.
     *
     * @returns JavaScript `Date` object representing the same point in time as
     *     this `Timestamp`, with millisecond precision.
     */    toDate() {
        return new Date(this.toMillis());
    }
    /**
     * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
     * epoch). This operation causes a loss of precision.
     *
     * @returns The point in time corresponding to this timestamp, represented as
     *     the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
     */    toMillis() {
        return 1e3 * this.seconds + this.nanoseconds / 1e6;
    }
    K(t) {
        return this.seconds === t.seconds ? D(this.nanoseconds, t.nanoseconds) : D(this.seconds, t.seconds);
    }
    /**
     * Returns true if this `Timestamp` is equal to the provided one.
     *
     * @param other - The `Timestamp` to compare against.
     * @returns true if this `Timestamp` is equal to the provided one.
     */    isEqual(t) {
        return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;
    }
    toString() {
        return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
    }
    toJSON() {
        return {
            seconds: this.seconds,
            nanoseconds: this.nanoseconds
        };
    }
    /**
     * Converts this object to a primitive string, which allows Timestamp objects to be compared
     * using the `>`, `<=`, `>=` and `>` operators.
     */    valueOf() {
        // This method returns a string of the form <seconds>.<nanoseconds> where <seconds> is
        // translated to have a non-negative value and both <seconds> and <nanoseconds> are left-padded
        // with zeroes to be a consistent length. Strings with this format then have a lexiographical
        // ordering that matches the expected ordering. The <seconds> translation is done to avoid
        // having a leading negative sign (i.e. a leading '-' character) in its string representation,
        // which would affect its lexiographical ordering.
        const t = this.seconds - -62135596800;
        // Note: Up to 12 decimal digits are required to represent all valid 'seconds' values.
                return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0");
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A version of a document in Firestore. This corresponds to the version
 * timestamp, such as update_time or read_time.
 */ class J {
    constructor(t) {
        this.timestamp = t;
    }
    static j(t) {
        return new J(t);
    }
    static min() {
        return new J(new H(0, 0));
    }
    u(t) {
        return this.timestamp.K(t.timestamp);
    }
    isEqual(t) {
        return this.timestamp.isEqual(t.timestamp);
    }
    /** Returns a number representation of the version for use in spec tests. */    W() {
        // Convert to microseconds.
        return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
    }
    toString() {
        return "SnapshotVersion(" + this.timestamp.toString() + ")";
    }
    G() {
        return this.timestamp;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Path represents an ordered sequence of string segments.
 */
class Y {
    constructor(t, e, n) {
        void 0 === e ? e = 0 : e > t.length && V(), void 0 === n ? n = t.length - e : n > t.length - e && V(), 
        this.segments = t, this.offset = e, this.H = n;
    }
    get length() {
        return this.H;
    }
    isEqual(t) {
        return 0 === Y.J(this, t);
    }
    child(t) {
        const e = this.segments.slice(this.offset, this.limit());
        return t instanceof Y ? t.forEach((t => {
            e.push(t);
        })) : e.push(t), this.Y(e);
    }
    /** The index of one past the last segment of the path. */    limit() {
        return this.offset + this.length;
    }
    X(t) {
        return t = void 0 === t ? 1 : t, this.Y(this.segments, this.offset + t, this.length - t);
    }
    Z() {
        return this.Y(this.segments, this.offset, this.length - 1);
    }
    tt() {
        return this.segments[this.offset];
    }
    et() {
        return this.get(this.length - 1);
    }
    get(t) {
        return this.segments[this.offset + t];
    }
    nt() {
        return 0 === this.length;
    }
    st(t) {
        if (t.length < this.length) return !1;
        for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
        return !0;
    }
    it(t) {
        if (this.length + 1 !== t.length) return !1;
        for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
        return !0;
    }
    forEach(t) {
        for (let e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);
    }
    rt() {
        return this.segments.slice(this.offset, this.limit());
    }
    static J(t, e) {
        const n = Math.min(t.length, e.length);
        for (let s = 0; s < n; s++) {
            const n = t.get(s), i = e.get(s);
            if (n < i) return -1;
            if (n > i) return 1;
        }
        return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;
    }
}

/**
 * A slash-separated path for navigating resources (documents and collections)
 * within Firestore.
 */ class X extends Y {
    Y(t, e, n) {
        return new X(t, e, n);
    }
    ot() {
        // NOTE: The client is ignorant of any path segments containing escape
        // sequences (e.g. __id123__) and just passes them through raw (they exist
        // for legacy reasons and should not be used frequently).
        return this.rt().join("/");
    }
    toString() {
        return this.ot();
    }
    /**
     * Creates a resource path from the given slash-delimited string. If multiple
     * arguments are provided, all components are combined. Leading and trailing
     * slashes from all components are ignored.
     */    static ct(...t) {
        // NOTE: The client is ignorant of any path segments containing escape
        // sequences (e.g. __id123__) and just passes them through raw (they exist
        // for legacy reasons and should not be used frequently).
        const e = [];
        for (const n of t) {
            if (n.indexOf("//") >= 0) throw new F(O.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);
            // Strip leading and traling slashed.
                        e.push(...n.split("/").filter((t => t.length > 0)));
        }
        return new X(e);
    }
    static at() {
        return new X([]);
    }
}

const Z = /^[_a-zA-Z][_a-zA-Z0-9]*$/;

/** A dot-separated path for navigating sub-objects within a document. */ class tt extends Y {
    Y(t, e, n) {
        return new tt(t, e, n);
    }
    /**
     * Returns true if the string could be used as a segment in a field path
     * without escaping.
     */    static ut(t) {
        return Z.test(t);
    }
    ot() {
        return this.rt().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), tt.ut(t) || (t = "`" + t + "`"), 
        t))).join(".");
    }
    toString() {
        return this.ot();
    }
    /**
     * Returns true if this field references the key of a document.
     */    ht() {
        return 1 === this.length && "__name__" === this.get(0);
    }
    /**
     * The field designating the key of a document.
     */    static lt() {
        return new tt([ "__name__" ]);
    }
    /**
     * Parses a field string from the given server-formatted string.
     *
     * - Splitting the empty string is not allowed (for now at least).
     * - Empty segments within the string (e.g. if there are two consecutive
     *   separators) are not allowed.
     *
     * TODO(b/37244157): we should make this more strict. Right now, it allows
     * non-identifier path components, even if they aren't escaped.
     */    static _t(t) {
        const e = [];
        let n = "", s = 0;
        const i = () => {
            if (0 === n.length) throw new F(O.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);
            e.push(n), n = "";
        };
        let r = !1;
        for (;s < t.length; ) {
            const e = t[s];
            if ("\\" === e) {
                if (s + 1 === t.length) throw new F(O.INVALID_ARGUMENT, "Path has trailing escape character: " + t);
                const e = t[s + 1];
                if ("\\" !== e && "." !== e && "`" !== e) throw new F(O.INVALID_ARGUMENT, "Path has invalid escape sequence: " + t);
                n += e, s += 2;
            } else "`" === e ? (r = !r, s++) : "." !== e || r ? (n += e, s++) : (i(), s++);
        }
        if (i(), r) throw new F(O.INVALID_ARGUMENT, "Unterminated ` in path: " + t);
        return new tt(e);
    }
    static at() {
        return new tt([]);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class et {
    constructor(t) {
        this.path = t;
    }
    static ft(t) {
        return new et(X.ct(t));
    }
    static dt(t) {
        return new et(X.ct(t).X(5));
    }
    /** Returns true if the document is in the specified collectionId. */    wt(t) {
        return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;
    }
    isEqual(t) {
        return null !== t && 0 === X.J(this.path, t.path);
    }
    toString() {
        return this.path.toString();
    }
    static J(t, e) {
        return X.J(t.path, e.path);
    }
    static Et(t) {
        return t.length % 2 == 0;
    }
    /**
     * Creates and returns a new document key with the given segments.
     *
     * @param segments - The segments of the path to the document
     * @returns A new instance of DocumentKey
     */    static Tt(t) {
        return new et(new X(t.slice()));
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ function nt(t) {
    let e = 0;
    for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e++;
    return e;
}

function st(t, e) {
    for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);
}

function it(t) {
    for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;
    return !0;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Provides a set of fields that can be used to partially patch a document.
 * FieldMask is used in conjunction with ObjectValue.
 * Examples:
 *   foo - Overwrites foo entirely with the provided value. If foo is not
 *         present in the companion ObjectValue, the field is deleted.
 *   foo.bar - Overwrites only the field bar of the object foo.
 *             If foo is not an object, foo is replaced with an object
 *             containing foo
 */ class rt {
    constructor(t) {
        this.fields = t, 
        // TODO(dimond): validation of FieldMask
        // Sort the field mask to support `FieldMask.isEqual()` and assert below.
        t.sort(tt.J);
    }
    /**
     * Verifies that `fieldPath` is included by at least one field in this field
     * mask.
     *
     * This is an O(n) operation, where `n` is the size of the field mask.
     */    It(t) {
        for (const e of this.fields) if (e.st(t)) return !0;
        return !1;
    }
    isEqual(t) {
        return C(this.fields, t.fields, ((t, e) => t.isEqual(e)));
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// A RegExp matching ISO 8601 UTC timestamps with optional fraction.
const ot = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);

/**
 * Converts the possible Proto values for a timestamp value into a "seconds and
 * nanos" representation.
 */ function ct(t) {
    // The json interface (for the browser) will return an iso timestamp string,
    // while the proto js library (for node) will return a
    // google.protobuf.Timestamp instance.
    if (p(!!t), "string" == typeof t) {
        // The date string can have higher precision (nanos) than the Date class
        // (millis), so we do some custom parsing here.
        // Parse the nanos right out of the string.
        let e = 0;
        const n = ot.exec(t);
        if (p(!!n), n[1]) {
            // Pad the fraction out to 9 digits (nanos).
            let t = n[1];
            t = (t + "000000000").substr(0, 9), e = Number(t);
        }
        // Parse the date to get the seconds.
                const s = new Date(t);
        return {
            seconds: Math.floor(s.getTime() / 1e3),
            nanos: e
        };
    }
    return {
        seconds: at(t.seconds),
        nanos: at(t.nanos)
    };
}

/**
 * Converts the possible Proto types for numbers into a JavaScript number.
 * Returns 0 if the value is not numeric.
 */ function at(t) {
    // TODO(bjornick): Handle int64 greater than 53 bits.
    return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0;
}

/** Converts the possible Proto types for Blobs into a ByteString. */ function ut(t) {
    return "string" == typeof t ? N.fromBase64String(t) : N.fromUint8Array(t);
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Represents a locally-applied ServerTimestamp.
 *
 * Server Timestamps are backed by MapValues that contain an internal field
 * `__type__` with a value of `server_timestamp`. The previous value and local
 * write time are stored in its `__previous_value__` and `__local_write_time__`
 * fields respectively.
 *
 * Notes:
 * - ServerTimestampValue instances are created as the result of applying a
 *   transform. They can only exist in the local view of a document. Therefore
 *   they do not need to be parsed or serialized.
 * - When evaluated locally (e.g. for snapshot.data()), they by default
 *   evaluate to `null`. This behavior can be configured by passing custom
 *   FieldValueOptions to value().
 * - With respect to other ServerTimestampValues, they sort by their
 *   localWriteTime.
 */ function ht(t) {
    var e, n;
    return "server_timestamp" === (null === (n = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue);
}

/**
 * Creates a new ServerTimestamp proto value (using the internal format).
 */
/**
 * Returns the value of the field before this ServerTimestamp was set.
 *
 * Preserving the previous values allows the user to display the last resoled
 * value until the backend responds with the timestamp.
 */
function lt(t) {
    const e = t.mapValue.fields.__previous_value__;
    return ht(e) ? lt(e) : e;
}

/**
 * Returns the local time at which this timestamp was first set.
 */ function _t(t) {
    const e = ct(t.mapValue.fields.__local_write_time__.timestampValue);
    return new H(e.seconds, e.nanos);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Sentinel value that sorts before any Mutation Batch ID. */
/**
 * Returns whether a variable is either undefined or null.
 */
function ft(t) {
    return null == t;
}

/** Returns whether the value represents -0. */ function dt(t) {
    // Detect if the value is -0.0. Based on polyfill from
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
    return 0 === t && 1 / t == -1 / 0;
}

/**
 * Returns whether a value is an integer and in the safe integer range
 * @param value - The value to test for being an integer and in the safe range
 */ function wt(t) {
    return "number" == typeof t && Number.isInteger(t) && !dt(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Extracts the backend's type order for the provided value. */ function Et(t) {
    return "nullValue" in t ? 0 /* NullValue */ : "booleanValue" in t ? 1 /* BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* NumberValue */ : "timestampValue" in t ? 3 /* TimestampValue */ : "stringValue" in t ? 5 /* StringValue */ : "bytesValue" in t ? 6 /* BlobValue */ : "referenceValue" in t ? 7 /* RefValue */ : "geoPointValue" in t ? 8 /* GeoPointValue */ : "arrayValue" in t ? 9 /* ArrayValue */ : "mapValue" in t ? ht(t) ? 4 /* ServerTimestampValue */ : 10 /* ObjectValue */ : V();
}

/** Tests `left` and `right` for equality based on the backend semantics. */ function Tt(t, e) {
    const n = Et(t);
    if (n !== Et(e)) return !1;
    switch (n) {
      case 0 /* NullValue */ :
        return !0;

      case 1 /* BooleanValue */ :
        return t.booleanValue === e.booleanValue;

      case 4 /* ServerTimestampValue */ :
        return _t(t).isEqual(_t(e));

      case 3 /* TimestampValue */ :
        return function(t, e) {
            if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length) 
            // Use string equality for ISO 8601 timestamps
            return t.timestampValue === e.timestampValue;
            const n = ct(t.timestampValue), s = ct(e.timestampValue);
            return n.seconds === s.seconds && n.nanos === s.nanos;
        }(t, e);

      case 5 /* StringValue */ :
        return t.stringValue === e.stringValue;

      case 6 /* BlobValue */ :
        return function(t, e) {
            return ut(t.bytesValue).isEqual(ut(e.bytesValue));
        }(t, e);

      case 7 /* RefValue */ :
        return t.referenceValue === e.referenceValue;

      case 8 /* GeoPointValue */ :
        return function(t, e) {
            return at(t.geoPointValue.latitude) === at(e.geoPointValue.latitude) && at(t.geoPointValue.longitude) === at(e.geoPointValue.longitude);
        }(t, e);

      case 2 /* NumberValue */ :
        return function(t, e) {
            if ("integerValue" in t && "integerValue" in e) return at(t.integerValue) === at(e.integerValue);
            if ("doubleValue" in t && "doubleValue" in e) {
                const n = at(t.doubleValue), s = at(e.doubleValue);
                return n === s ? dt(n) === dt(s) : isNaN(n) && isNaN(s);
            }
            return !1;
        }(t, e);

      case 9 /* ArrayValue */ :
        return C(t.arrayValue.values || [], e.arrayValue.values || [], Tt);

      case 10 /* ObjectValue */ :
        return function(t, e) {
            const n = t.mapValue.fields || {}, s = e.mapValue.fields || {};
            if (nt(n) !== nt(s)) return !1;
            for (const t in n) if (n.hasOwnProperty(t) && (void 0 === s[t] || !Tt(n[t], s[t]))) return !1;
            return !0;
        }
        /** Returns true if the ArrayValue contains the specified element. */ (t, e);

      default:
        return V();
    }
}

function It(t, e) {
    return void 0 !== (t.values || []).find((t => Tt(t, e)));
}

function mt(t, e) {
    const n = Et(t), s = Et(e);
    if (n !== s) return D(n, s);
    switch (n) {
      case 0 /* NullValue */ :
        return 0;

      case 1 /* BooleanValue */ :
        return D(t.booleanValue, e.booleanValue);

      case 2 /* NumberValue */ :
        return function(t, e) {
            const n = at(t.integerValue || t.doubleValue), s = at(e.integerValue || e.doubleValue);
            return n < s ? -1 : n > s ? 1 : n === s ? 0 : 
            // one or both are NaN.
            isNaN(n) ? isNaN(s) ? 0 : -1 : 1;
        }(t, e);

      case 3 /* TimestampValue */ :
        return At(t.timestampValue, e.timestampValue);

      case 4 /* ServerTimestampValue */ :
        return At(_t(t), _t(e));

      case 5 /* StringValue */ :
        return D(t.stringValue, e.stringValue);

      case 6 /* BlobValue */ :
        return function(t, e) {
            const n = ut(t), s = ut(e);
            return n.u(s);
        }(t.bytesValue, e.bytesValue);

      case 7 /* RefValue */ :
        return function(t, e) {
            const n = t.split("/"), s = e.split("/");
            for (let t = 0; t < n.length && t < s.length; t++) {
                const e = D(n[t], s[t]);
                if (0 !== e) return e;
            }
            return D(n.length, s.length);
        }(t.referenceValue, e.referenceValue);

      case 8 /* GeoPointValue */ :
        return function(t, e) {
            const n = D(at(t.latitude), at(e.latitude));
            if (0 !== n) return n;
            return D(at(t.longitude), at(e.longitude));
        }(t.geoPointValue, e.geoPointValue);

      case 9 /* ArrayValue */ :
        return function(t, e) {
            const n = t.values || [], s = e.values || [];
            for (let t = 0; t < n.length && t < s.length; ++t) {
                const e = mt(n[t], s[t]);
                if (e) return e;
            }
            return D(n.length, s.length);
        }(t.arrayValue, e.arrayValue);

      case 10 /* ObjectValue */ :
        return function(t, e) {
            const n = t.fields || {}, s = Object.keys(n), i = e.fields || {}, r = Object.keys(i);
            // Even though MapValues are likely sorted correctly based on their insertion
            // order (e.g. when received from the backend), local modifications can bring
            // elements out of order. We need to re-sort the elements to ensure that
            // canonical IDs are independent of insertion order.
            s.sort(), r.sort();
            for (let t = 0; t < s.length && t < r.length; ++t) {
                const e = D(s[t], r[t]);
                if (0 !== e) return e;
                const o = mt(n[s[t]], i[r[t]]);
                if (0 !== o) return o;
            }
            return D(s.length, r.length);
        }
        /**
 * Generates the canonical ID for the provided field value (as used in Target
 * serialization).
 */ (t.mapValue, e.mapValue);

      default:
        throw V();
    }
}

function At(t, e) {
    if ("string" == typeof t && "string" == typeof e && t.length === e.length) return D(t, e);
    const n = ct(t), s = ct(e), i = D(n.seconds, s.seconds);
    return 0 !== i ? i : D(n.nanos, s.nanos);
}

function Rt(t) {
    return Pt(t);
}

function Pt(t) {
    return "nullValue" in t ? "null" : "booleanValue" in t ? "" + t.booleanValue : "integerValue" in t ? "" + t.integerValue : "doubleValue" in t ? "" + t.doubleValue : "timestampValue" in t ? function(t) {
        const e = ct(t);
        return `time(${e.seconds},${e.nanos})`;
    }(t.timestampValue) : "stringValue" in t ? t.stringValue : "bytesValue" in t ? ut(t.bytesValue).toBase64() : "referenceValue" in t ? (n = t.referenceValue, 
    et.dt(n).toString()) : "geoPointValue" in t ? `geo(${(e = t.geoPointValue).latitude},${e.longitude})` : "arrayValue" in t ? function(t) {
        let e = "[", n = !0;
        for (const s of t.values || []) n ? n = !1 : e += ",", e += Pt(s);
        return e + "]";
    }
    /** Returns a reference value for the provided database and key. */ (t.arrayValue) : "mapValue" in t ? function(t) {
        // Iteration order in JavaScript is not guaranteed. To ensure that we generate
        // matching canonical IDs for identical maps, we need to sort the keys.
        const e = Object.keys(t.fields || {}).sort();
        let n = "{", s = !0;
        for (const i of e) s ? s = !1 : n += ",", n += `${i}:${Pt(t.fields[i])}`;
        return n + "}";
    }(t.mapValue) : V();
    var e, n;
}

function yt(t, e) {
    return {
        referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.ot()}`
    };
}

/** Returns true if `value` is an IntegerValue . */ function gt(t) {
    return !!t && "integerValue" in t;
}

/** Returns true if `value` is a DoubleValue. */
/** Returns true if `value` is an ArrayValue. */
function Vt(t) {
    return !!t && "arrayValue" in t;
}

/** Returns true if `value` is a NullValue. */ function pt(t) {
    return !!t && "nullValue" in t;
}

/** Returns true if `value` is NaN. */ function bt(t) {
    return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue));
}

/** Returns true if `value` is a MapValue. */ function vt(t) {
    return !!t && "mapValue" in t;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An ObjectValue represents a MapValue in the Firestore Proto and offers the
 * ability to add and remove fields (via the ObjectValueBuilder).
 */ class St {
    constructor(t) {
        this.proto = t;
    }
    static empty() {
        return new St({
            mapValue: {}
        });
    }
    /**
     * Returns the value at the given path or null.
     *
     * @param path - the path to search
     * @returns The value at the path or if there it doesn't exist.
     */    field(t) {
        if (t.nt()) return this.proto;
        {
            let e = this.proto;
            for (let n = 0; n < t.length - 1; ++n) {
                if (!e.mapValue.fields) return null;
                if (e = e.mapValue.fields[t.get(n)], !vt(e)) return null;
            }
            return e = (e.mapValue.fields || {})[t.et()], e || null;
        }
    }
    isEqual(t) {
        return Tt(this.proto, t.proto);
    }
}

/**
 * An ObjectValueBuilder provides APIs to set and delete fields from an
 * ObjectValue.
 */ class Dt {
    /**
     * @param baseObject - The object to mutate.
     */
    constructor(t = St.empty()) {
        this.At = t, 
        /** A map that contains the accumulated changes in this builder. */
        this.Rt = new Map;
    }
    /**
     * Sets the field to the provided value.
     *
     * @param path - The field path to set.
     * @param value - The value to set.
     * @returns The current Builder instance.
     */    set(t, e) {
        return this.Pt(t, e), this;
    }
    /**
     * Removes the field at the specified path. If there is no field at the
     * specified path, nothing is changed.
     *
     * @param path - The field path to remove.
     * @returns The current Builder instance.
     */    delete(t) {
        return this.Pt(t, null), this;
    }
    /**
     * Adds `value` to the overlay map at `path`. Creates nested map entries if
     * needed.
     */    Pt(t, e) {
        let n = this.Rt;
        for (let e = 0; e < t.length - 1; ++e) {
            const s = t.get(e);
            let i = n.get(s);
            i instanceof Map ? 
            // Re-use a previously created map
            n = i : i && 10 /* ObjectValue */ === Et(i) ? (
            // Convert the existing Protobuf MapValue into a map
            i = new Map(Object.entries(i.mapValue.fields || {})), n.set(s, i), n = i) : (
            // Create an empty map to represent the current nesting level
            i = new Map, n.set(s, i), n = i);
        }
        n.set(t.et(), e);
    }
    /** Returns an ObjectValue with all mutations applied. */    yt() {
        const t = this.gt(tt.at(), this.Rt);
        return null != t ? new St(t) : this.At;
    }
    /**
     * Applies any overlays from `currentOverlays` that exist at `currentPath`
     * and returns the merged data at `currentPath` (or null if there were no
     * changes).
     *
     * @param currentPath - The path at the current nesting level. Can be set to
     * FieldValue.emptyPath() to represent the root.
     * @param currentOverlays - The overlays at the current nesting level in the
     * same format as `overlayMap`.
     * @returns The merged data at `currentPath` or null if no modifications
     * were applied.
     */    gt(t, e) {
        let n = !1;
        const s = this.At.field(t), i = vt(s) ? // If there is already data at the current path, base our
        Object.assign({}, s.mapValue.fields) : {};
        return e.forEach(((e, s) => {
            if (e instanceof Map) {
                const r = this.gt(t.child(s), e);
                null != r && (i[s] = r, n = !0);
            } else null !== e ? (i[s] = e, n = !0) : i.hasOwnProperty(s) && (delete i[s], n = !0);
        })), n ? {
            mapValue: {
                fields: i
            }
        } : null;
    }
}

/**
 * Returns a FieldMask built from all fields in a MapValue.
 */ function Ct(t) {
    const e = [];
    return st(t.fields || {}, ((t, n) => {
        const s = new tt([ t ]);
        if (vt(n)) {
            const t = Ct(n.mapValue).fields;
            if (0 === t.length) 
            // Preserve the empty map by adding it to the FieldMask.
            e.push(s); else 
            // For nested and non-empty ObjectValues, add the FieldPath of the
            // leaf nodes.
            for (const n of t) e.push(s.child(n));
        } else 
        // For nested and non-empty ObjectValues, add the FieldPath of the leaf
        // nodes.
        e.push(s);
    })), new rt(e);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * The result of a lookup for a given path may be an existing document or a
 * marker that this document does not exist at a given version.
 */ class xt {
    constructor(t, e) {
        this.key = t, this.version = e;
    }
}

/**
 * Represents a document in Firestore with a key, version, data and whether the
 * data has local mutations applied to it.
 */ class Nt extends xt {
    constructor(t, e, n, s) {
        super(t, e), this.Vt = n, this.bt = !!s.bt, this.hasCommittedMutations = !!s.hasCommittedMutations;
    }
    field(t) {
        return this.Vt.field(t);
    }
    data() {
        return this.Vt;
    }
    vt() {
        return this.Vt.proto;
    }
    isEqual(t) {
        return t instanceof Nt && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.bt === t.bt && this.hasCommittedMutations === t.hasCommittedMutations && this.Vt.isEqual(t.Vt);
    }
    toString() {
        return `Document(${this.key}, ${this.version}, ${this.Vt.toString()}, {hasLocalMutations: ${this.bt}}), {hasCommittedMutations: ${this.hasCommittedMutations}})`;
    }
    get hasPendingWrites() {
        return this.bt || this.hasCommittedMutations;
    }
}

/**
 * Compares the value for field `field` in the provided documents. Throws if
 * the field does not exist in both documents.
 */
/**
 * A class representing a deleted document.
 * Version is set to 0 if we don't point to any specific time, otherwise it
 * denotes time we know it didn't exist at.
 */
class Ot extends xt {
    constructor(t, e, n) {
        super(t, e), this.hasCommittedMutations = !(!n || !n.hasCommittedMutations);
    }
    toString() {
        return `NoDocument(${this.key}, ${this.version})`;
    }
    get hasPendingWrites() {
        return this.hasCommittedMutations;
    }
    isEqual(t) {
        return t instanceof Ot && t.hasCommittedMutations === this.hasCommittedMutations && t.version.isEqual(this.version) && t.key.isEqual(this.key);
    }
}

/**
 * A class representing an existing document whose data is unknown (e.g. a
 * document that was updated without a known base document).
 */ class Ft extends xt {
    toString() {
        return `UnknownDocument(${this.key}, ${this.version})`;
    }
    get hasPendingWrites() {
        return !0;
    }
    isEqual(t) {
        return t instanceof Ft && t.version.isEqual(this.version) && t.key.isEqual(this.key);
    }
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Visible for testing
class kt {
    constructor(t, e = null, n = [], s = [], i = null, r = null, o = null) {
        this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = s, this.limit = i, 
        this.startAt = r, this.endAt = o, this.St = null;
    }
}

/**
 * Initializes a Target with a path and optional additional query constraints.
 * Path must currently be empty if this is a collection group query.
 *
 * NOTE: you should always construct `Target` from `Query.toTarget` instead of
 * using this factory method, because `Query` provides an implicit `orderBy`
 * property.
 */ function Mt(t, e = null, n = [], s = [], i = null, r = null, o = null) {
    return new kt(t, e, n, s, i, r, o);
}

function Lt(t) {
    const e = b(t);
    if (null === e.St) {
        let t = e.path.ot();
        null !== e.collectionGroup && (t += "|cg:" + e.collectionGroup), t += "|f:", t += e.filters.map((t => Qt(t))).join(","), 
        t += "|ob:", t += e.orderBy.map((t => function(t) {
            // TODO(b/29183165): Make this collision robust.
            return t.field.ot() + t.dir;
        }(t))).join(","), ft(e.limit) || (t += "|l:", t += e.limit), e.startAt && (t += "|lb:", 
        t += Zt(e.startAt)), e.endAt && (t += "|ub:", t += Zt(e.endAt)), e.St = t;
    }
    return e.St;
}

function $t(t) {
    let e = t.path.ot();
    return null !== t.collectionGroup && (e += " collectionGroup=" + t.collectionGroup), 
    t.filters.length > 0 && (e += `, filters: [${t.filters.map((t => {
        return `${(e = t).field.ot()} ${e.op} ${Rt(e.value)}`;
        /** Returns a debug description for `filter`. */
        var e;
        /** Filter that matches on key fields (i.e. '__name__'). */    })).join(", ")}]`), 
    ft(t.limit) || (e += ", limit: " + t.limit), t.orderBy.length > 0 && (e += `, orderBy: [${t.orderBy.map((t => function(t) {
        return `${t.field.ot()} (${t.dir})`;
    }(t))).join(", ")}]`), t.startAt && (e += ", startAt: " + Zt(t.startAt)), t.endAt && (e += ", endAt: " + Zt(t.endAt)), 
    `Target(${e})`;
}

function Bt(t, e) {
    if (t.limit !== e.limit) return !1;
    if (t.orderBy.length !== e.orderBy.length) return !1;
    for (let n = 0; n < t.orderBy.length; n++) if (!ee(t.orderBy[n], e.orderBy[n])) return !1;
    if (t.filters.length !== e.filters.length) return !1;
    for (let i = 0; i < t.filters.length; i++) if (n = t.filters[i], s = e.filters[i], 
    n.op !== s.op || !n.field.isEqual(s.field) || !Tt(n.value, s.value)) return !1;
    var n, s;
    return t.collectionGroup === e.collectionGroup && (!!t.path.isEqual(e.path) && (!!se(t.startAt, e.startAt) && se(t.endAt, e.endAt)));
}

function qt(t) {
    return et.Et(t.path) && null === t.collectionGroup && 0 === t.filters.length;
}

class Ut extends class {} {
    constructor(t, e, n) {
        super(), this.field = t, this.op = e, this.value = n;
    }
    /**
     * Creates a filter based on the provided arguments.
     */    static create(t, e, n) {
        return t.ht() ? "in" /* IN */ === e || "not-in" /* NOT_IN */ === e ? this.Dt(t, e, n) : new Kt(t, e, n) : "array-contains" /* ARRAY_CONTAINS */ === e ? new zt(t, n) : "in" /* IN */ === e ? new Ht(t, n) : "not-in" /* NOT_IN */ === e ? new Jt(t, n) : "array-contains-any" /* ARRAY_CONTAINS_ANY */ === e ? new Yt(t, n) : new Ut(t, e, n);
    }
    static Dt(t, e, n) {
        return "in" /* IN */ === e ? new jt(t, n) : new Wt(t, n);
    }
    matches(t) {
        const e = t.field(this.field);
        // Types do not have to match in NOT_EQUAL filters.
                return "!=" /* NOT_EQUAL */ === this.op ? null !== e && this.Ct(mt(e, this.value)) : null !== e && Et(this.value) === Et(e) && this.Ct(mt(e, this.value));
        // Only compare types with matching backend order (such as double and int).
        }
    Ct(t) {
        switch (this.op) {
          case "<" /* LESS_THAN */ :
            return t < 0;

          case "<=" /* LESS_THAN_OR_EQUAL */ :
            return t <= 0;

          case "==" /* EQUAL */ :
            return 0 === t;

          case "!=" /* NOT_EQUAL */ :
            return 0 !== t;

          case ">" /* GREATER_THAN */ :
            return t > 0;

          case ">=" /* GREATER_THAN_OR_EQUAL */ :
            return t >= 0;

          default:
            return V();
        }
    }
    xt() {
        return [ "<" /* LESS_THAN */ , "<=" /* LESS_THAN_OR_EQUAL */ , ">" /* GREATER_THAN */ , ">=" /* GREATER_THAN_OR_EQUAL */ , "!=" /* NOT_EQUAL */ , "not-in" /* NOT_IN */ ].indexOf(this.op) >= 0;
    }
}

function Qt(t) {
    // TODO(b/29183165): Technically, this won't be unique if two values have
    // the same description, such as the int 3 and the string "3". So we should
    // add the types in here somehow, too.
    return t.field.ot() + t.op.toString() + Rt(t.value);
}

class Kt extends Ut {
    constructor(t, e, n) {
        super(t, e, n), this.key = et.dt(n.referenceValue);
    }
    matches(t) {
        const e = et.J(t.key, this.key);
        return this.Ct(e);
    }
}

/** Filter that matches on key fields within an array. */ class jt extends Ut {
    constructor(t, e) {
        super(t, "in" /* IN */ , e), this.keys = Gt("in" /* IN */ , e);
    }
    matches(t) {
        return this.keys.some((e => e.isEqual(t.key)));
    }
}

/** Filter that matches on key fields not present within an array. */ class Wt extends Ut {
    constructor(t, e) {
        super(t, "not-in" /* NOT_IN */ , e), this.keys = Gt("not-in" /* NOT_IN */ , e);
    }
    matches(t) {
        return !this.keys.some((e => e.isEqual(t.key)));
    }
}

function Gt(t, e) {
    var n;
    return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((t => et.dt(t.referenceValue)));
}

/** A Filter that implements the array-contains operator. */ class zt extends Ut {
    constructor(t, e) {
        super(t, "array-contains" /* ARRAY_CONTAINS */ , e);
    }
    matches(t) {
        const e = t.field(this.field);
        return Vt(e) && It(e.arrayValue, this.value);
    }
}

/** A Filter that implements the IN operator. */ class Ht extends Ut {
    constructor(t, e) {
        super(t, "in" /* IN */ , e);
    }
    matches(t) {
        const e = t.field(this.field);
        return null !== e && It(this.value.arrayValue, e);
    }
}

/** A Filter that implements the not-in operator. */ class Jt extends Ut {
    constructor(t, e) {
        super(t, "not-in" /* NOT_IN */ , e);
    }
    matches(t) {
        if (It(this.value.arrayValue, {
            nullValue: "NULL_VALUE"
        })) return !1;
        const e = t.field(this.field);
        return null !== e && !It(this.value.arrayValue, e);
    }
}

/** A Filter that implements the array-contains-any operator. */ class Yt extends Ut {
    constructor(t, e) {
        super(t, "array-contains-any" /* ARRAY_CONTAINS_ANY */ , e);
    }
    matches(t) {
        const e = t.field(this.field);
        return !(!Vt(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => It(this.value.arrayValue, t)));
    }
}

/**
 * Represents a bound of a query.
 *
 * The bound is specified with the given components representing a position and
 * whether it's just before or just after the position (relative to whatever the
 * query order is).
 *
 * The position represents a logical index position for a query. It's a prefix
 * of values for the (potentially implicit) order by clauses of a query.
 *
 * Bound provides a function to determine whether a document comes before or
 * after a bound. This is influenced by whether the position is just before or
 * just after the provided values.
 */ class Xt {
    constructor(t, e) {
        this.position = t, this.before = e;
    }
}

function Zt(t) {
    // TODO(b/29183165): Make this collision robust.
    return `${t.before ? "b" : "a"}:${t.position.map((t => Rt(t))).join(",")}`;
}

/**
 * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
 */ class te {
    constructor(t, e = "asc" /* ASCENDING */) {
        this.field = t, this.dir = e;
    }
}

function ee(t, e) {
    return t.dir === e.dir && t.field.isEqual(e.field);
}

/**
 * Returns true if a document sorts before a bound using the provided sort
 * order.
 */ function ne(t, e, n) {
    let s = 0;
    for (let i = 0; i < t.position.length; i++) {
        const r = e[i], o = t.position[i];
        if (r.field.ht()) s = et.J(et.dt(o.referenceValue), n.key); else {
            s = mt(o, n.field(r.field));
        }
        if ("desc" /* DESCENDING */ === r.dir && (s *= -1), 0 !== s) break;
    }
    return t.before ? s <= 0 : s < 0;
}

function se(t, e) {
    if (null === t) return null === e;
    if (null === e) return !1;
    if (t.before !== e.before || t.position.length !== e.position.length) return !1;
    for (let n = 0; n < t.position.length; n++) {
        if (!Tt(t.position[n], e.position[n])) return !1;
    }
    return !0;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Query encapsulates all the query attributes we support in the SDK. It can
 * be run against the LocalStore, as well as be converted to a `Target` to
 * query the RemoteStore results.
 *
 * Visible for testing.
 */ class ie {
    /**
     * Initializes a Query with a path and optional additional query constraints.
     * Path must currently be empty if this is a collection group query.
     */
    constructor(t, e = null, n = [], s = [], i = null, r = "F" /* First */ , o = null, c = null) {
        this.path = t, this.collectionGroup = e, this.Nt = n, this.filters = s, this.limit = i, 
        this.limitType = r, this.startAt = o, this.endAt = c, this.Ot = null, 
        // The corresponding `Target` of this `Query` instance.
        this.Ft = null, this.startAt, this.endAt;
    }
}

/** Creates a new Query instance with the options provided. */ function re(t, e, n, s, i, r, o, c) {
    return new ie(t, e, n, s, i, r, o, c);
}

/** Creates a new Query for a query that matches all documents at `path` */ function oe(t) {
    return new ie(t);
}

/**
 * Helper to convert a collection group query into a collection query at a
 * specific path. This is used when executing collection group queries, since
 * we have to split the query into a set of collection queries at multiple
 * paths.
 */ function ce(t) {
    return !ft(t.limit) && "F" /* First */ === t.limitType;
}

function ae(t) {
    return !ft(t.limit) && "L" /* Last */ === t.limitType;
}

function ue(t) {
    return t.Nt.length > 0 ? t.Nt[0].field : null;
}

function he(t) {
    for (const e of t.filters) if (e.xt()) return e.field;
    return null;
}

/**
 * Checks if any of the provided Operators are included in the query and
 * returns the first one that is, or null if none are.
 */
/**
 * Returns whether the query matches a collection group rather than a specific
 * collection.
 */
function le(t) {
    return null !== t.collectionGroup;
}

/**
 * Returns the implicit order by constraint that is used to execute the Query,
 * which can be different from the order by constraints the user provided (e.g.
 * the SDK and backend always orders by `__name__`).
 */ function _e(t) {
    const e = b(t);
    if (null === e.Ot) {
        e.Ot = [];
        const t = he(e), n = ue(e);
        if (null !== t && null === n) 
        // In order to implicitly add key ordering, we must also add the
        // inequality filter field for it to be a valid query.
        // Note that the default inequality field and key ordering is ascending.
        t.ht() || e.Ot.push(new te(t)), e.Ot.push(new te(tt.lt(), "asc" /* ASCENDING */)); else {
            let t = !1;
            for (const n of e.Nt) e.Ot.push(n), n.field.ht() && (t = !0);
            if (!t) {
                // The order of the implicit key ordering always matches the last
                // explicit order by
                const t = e.Nt.length > 0 ? e.Nt[e.Nt.length - 1].dir : "asc" /* ASCENDING */;
                e.Ot.push(new te(tt.lt(), t));
            }
        }
    }
    return e.Ot;
}

/**
 * Converts this `Query` instance to it's corresponding `Target` representation.
 */ function fe(t) {
    const e = b(t);
    if (!e.Ft) if ("F" /* First */ === e.limitType) e.Ft = Mt(e.path, e.collectionGroup, _e(e), e.filters, e.limit, e.startAt, e.endAt); else {
        // Flip the orderBy directions since we want the last results
        const t = [];
        for (const n of _e(e)) {
            const e = "desc" /* DESCENDING */ === n.dir ? "asc" /* ASCENDING */ : "desc" /* DESCENDING */;
            t.push(new te(n.field, e));
        }
        // We need to swap the cursors to match the now-flipped query ordering.
                const n = e.endAt ? new Xt(e.endAt.position, !e.endAt.before) : null, s = e.startAt ? new Xt(e.startAt.position, !e.startAt.before) : null;
        // Now return as a LimitType.First query.
        e.Ft = Mt(e.path, e.collectionGroup, t, e.filters, e.limit, n, s);
    }
    return e.Ft;
}

function de(t, e, n) {
    return new ie(t.path, t.collectionGroup, t.Nt.slice(), t.filters.slice(), e, n, t.startAt, t.endAt);
}

function we(t, e) {
    return Bt(fe(t), fe(e)) && t.limitType === e.limitType;
}

// TODO(b/29183165): This is used to get a unique string from a query to, for
// example, use as a dictionary key, but the implementation is subject to
// collisions. Make it collision-free.
function Ee(t) {
    return `${Lt(fe(t))}|lt:${t.limitType}`;
}

function Te(t) {
    return `Query(target=${$t(fe(t))}; limitType=${t.limitType})`;
}

/** Returns whether `doc` matches the constraints of `query`. */ function Ie(t, e) {
    return function(t, e) {
        const n = e.key.path;
        return null !== t.collectionGroup ? e.key.wt(t.collectionGroup) && t.path.st(n) : et.Et(t.path) ? t.path.isEqual(n) : t.path.it(n);
    }
    /**
 * A document must have a value for every ordering clause in order to show up
 * in the results.
 */ (t, e) && function(t, e) {
        for (const n of t.Nt) 
        // order by key always matches
        if (!n.field.ht() && null === e.field(n.field)) return !1;
        return !0;
    }(t, e) && function(t, e) {
        for (const n of t.filters) if (!n.matches(e)) return !1;
        return !0;
    }
    /** Makes sure a document is within the bounds, if provided. */ (t, e) && function(t, e) {
        if (t.startAt && !ne(t.startAt, _e(t), e)) return !1;
        if (t.endAt && ne(t.endAt, _e(t), e)) return !1;
        return !0;
    }
    /**
 * Returns a new comparator function that can be used to compare two documents
 * based on the Query's ordering constraint.
 */ (t, e);
}

function me(t) {
    return (e, n) => {
        let s = !1;
        for (const i of _e(t)) {
            const t = Ae(i, e, n);
            if (0 !== t) return t;
            s = s || i.field.ht();
        }
        return 0;
    };
}

function Ae(t, e, n) {
    const s = t.field.ht() ? et.J(e.key, n.key) : function(t, e, n) {
        const s = e.field(t), i = n.field(t);
        return null !== s && null !== i ? mt(s, i) : V();
    }(t.field, e, n);
    switch (t.dir) {
      case "asc" /* ASCENDING */ :
        return s;

      case "desc" /* DESCENDING */ :
        return -1 * s;

      default:
        return V();
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An immutable set of metadata that the local store tracks for each target.
 */ class Re {
    constructor(
    /** The target being listened to. */
    t, 
    /**
     * The target ID to which the target corresponds; Assigned by the
     * LocalStore for user listens and by the SyncEngine for limbo watches.
     */
    e, 
    /** The purpose of the target. */
    n, 
    /**
     * The sequence number of the last transaction during which this target data
     * was modified.
     */
    s, 
    /** The latest snapshot version seen for this target. */
    i = J.min()
    /**
     * The maximum snapshot version at which the associated view
     * contained no limbo documents.
     */ , r = J.min()
    /**
     * An opaque, server-assigned token that allows watching a target to be
     * resumed after disconnecting without retransmitting all the data that
     * matches the target. The resume token essentially identifies a point in
     * time from which the server should resume sending results.
     */ , o = N.h) {
        this.target = t, this.targetId = e, this.kt = n, this.sequenceNumber = s, this.Mt = i, 
        this.lastLimboFreeSnapshotVersion = r, this.resumeToken = o;
    }
    /** Creates a new target data instance with an updated sequence number. */    Lt(t) {
        return new Re(this.target, this.targetId, this.kt, t, this.Mt, this.lastLimboFreeSnapshotVersion, this.resumeToken);
    }
    /**
     * Creates a new target data instance with an updated resume token and
     * snapshot version.
     */    $t(t, e) {
        return new Re(this.target, this.targetId, this.kt, this.sequenceNumber, e, this.lastLimboFreeSnapshotVersion, t);
    }
    /**
     * Creates a new target data instance with an updated last limbo free
     * snapshot version number.
     */    Bt(t) {
        return new Re(this.target, this.targetId, this.kt, this.sequenceNumber, this.Mt, t, this.resumeToken);
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Returns an DoubleValue for `value` that is encoded based the serializer's
 * `useProto3Json` setting.
 */ function Pe(t, e) {
    if (t.qt) {
        if (isNaN(e)) return {
            doubleValue: "NaN"
        };
        if (e === 1 / 0) return {
            doubleValue: "Infinity"
        };
        if (e === -1 / 0) return {
            doubleValue: "-Infinity"
        };
    }
    return {
        doubleValue: dt(e) ? "-0" : e
    };
}

/**
 * Returns an IntegerValue for `value`.
 */ function ye(t) {
    return {
        integerValue: "" + t
    };
}

/**
 * Returns a value for a number that's appropriate to put into a proto.
 * The return value is an IntegerValue if it can safely represent the value,
 * otherwise a DoubleValue is returned.
 */ function ge(t, e) {
    return wt(e) ? ye(e) : Pe(t, e);
}

/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Used to represent a field transform on a mutation. */ class Ve {
    constructor() {
        // Make sure that the structural type of `TransformOperation` is unique.
        // See https://github.com/microsoft/TypeScript/issues/5451
        this.Ut = void 0;
    }
}

/**
 * Computes the local transform result against the provided `previousValue`,
 * optionally using the provided localWriteTime.
 */ function pe(t, e, n) {
    return t instanceof Se ? function(t, e) {
        const n = {
            fields: {
                __type__: {
                    stringValue: "server_timestamp"
                },
                __local_write_time__: {
                    timestampValue: {
                        seconds: t.seconds,
                        nanos: t.nanoseconds
                    }
                }
            }
        };
        return e && (n.fields.__previous_value__ = e), {
            mapValue: n
        };
    }(n, e) : t instanceof De ? Ce(t, e) : t instanceof xe ? Ne(t, e) : function(t, e) {
        // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit
        // precision and resolves overflows by reducing precision, we do not
        // manually cap overflows at 2^63.
        const n = ve(t, e), s = Fe(n) + Fe(t.Qt);
        return gt(n) && gt(t.Qt) ? ye(s) : Pe(t.Kt, s);
    }(t, e);
}

/**
 * Computes a final transform result after the transform has been acknowledged
 * by the server, potentially using the server-provided transformResult.
 */ function be(t, e, n) {
    // The server just sends null as the transform result for array operations,
    // so we have to calculate a result the same as we do for local
    // applications.
    return t instanceof De ? Ce(t, e) : t instanceof xe ? Ne(t, e) : n;
}

/**
 * If this transform operation is not idempotent, returns the base value to
 * persist for this transform. If a base value is returned, the transform
 * operation is always applied to this base value, even if document has
 * already been updated.
 *
 * Base values provide consistent behavior for non-idempotent transforms and
 * allow us to return the same latency-compensated value even if the backend
 * has already applied the transform operation. The base value is null for
 * idempotent transforms, as they can be re-played even if the backend has
 * already applied them.
 *
 * @returns a base value to store along with the mutation, or null for
 * idempotent transforms.
 */ function ve(t, e) {
    return t instanceof Oe ? gt(n = e) || function(t) {
        return !!t && "doubleValue" in t;
    }
    /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ (n) ? e : {
        integerValue: 0
    } : null;
    var n;
}

/** Transforms a value into a server-generated timestamp. */
class Se extends Ve {}

/** Transforms an array value via a union operation. */ class De extends Ve {
    constructor(t) {
        super(), this.elements = t;
    }
}

function Ce(t, e) {
    const n = ke(e);
    for (const e of t.elements) n.some((t => Tt(t, e))) || n.push(e);
    return {
        arrayValue: {
            values: n
        }
    };
}

/** Transforms an array value via a remove operation. */ class xe extends Ve {
    constructor(t) {
        super(), this.elements = t;
    }
}

function Ne(t, e) {
    let n = ke(e);
    for (const e of t.elements) n = n.filter((t => !Tt(t, e)));
    return {
        arrayValue: {
            values: n
        }
    };
}

/**
 * Implements the backend semantics for locally computed NUMERIC_ADD (increment)
 * transforms. Converts all field values to integers or doubles, but unlike the
 * backend does not cap integer values at 2^63. Instead, JavaScript number
 * arithmetic is used and precision loss can occur for values greater than 2^53.
 */ class Oe extends Ve {
    constructor(t, e) {
        super(), this.Kt = t, this.Qt = e;
    }
}

function Fe(t) {
    return at(t.integerValue || t.doubleValue);
}

function ke(t) {
    return Vt(t) && t.arrayValue.values ? t.arrayValue.values.slice() : [];
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** A field path and the TransformOperation to perform upon it. */ class Me {
    constructor(t, e) {
        this.field = t, this.transform = e;
    }
}

function Le(t, e) {
    return t.field.isEqual(e.field) && function(t, e) {
        return t instanceof De && e instanceof De || t instanceof xe && e instanceof xe ? C(t.elements, e.elements, Tt) : t instanceof Oe && e instanceof Oe ? Tt(t.Qt, e.Qt) : t instanceof Se && e instanceof Se;
    }(t.transform, e.transform);
}

/** The result of successfully applying a mutation to the backend. */
class $e {
    constructor(
    /**
     * The version at which the mutation was committed:
     *
     * - For most operations, this is the updateTime in the WriteResult.
     * - For deletes, the commitTime of the WriteResponse (because deletes are
     *   not stored and have no updateTime).
     *
     * Note that these versions can be different: No-op writes will not change
     * the updateTime even though the commitTime advances.
     */
    t, 
    /**
     * The resulting fields returned from the backend after a mutation
     * containing field transforms has been committed. Contains one FieldValue
     * for each FieldTransform that was in the mutation.
     *
     * Will be null if the mutation did not contain any field transforms.
     */
    e) {
        this.version = t, this.transformResults = e;
    }
}

/**
 * Encodes a precondition for a mutation. This follows the model that the
 * backend accepts with the special case of an explicit "empty" precondition
 * (meaning no precondition).
 */ class Be {
    constructor(t, e) {
        this.updateTime = t, this.exists = e;
    }
    /** Creates a new empty Precondition. */    static jt() {
        return new Be;
    }
    /** Creates a new Precondition with an exists flag. */    static exists(t) {
        return new Be(void 0, t);
    }
    /** Creates a new Precondition based on a version a document exists at. */    static updateTime(t) {
        return new Be(t);
    }
    /** Returns whether this Precondition is empty. */    get Wt() {
        return void 0 === this.updateTime && void 0 === this.exists;
    }
    isEqual(t) {
        return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);
    }
}

/**
 * Returns true if the preconditions is valid for the given document
 * (or null if no document is available).
 */ function qe(t, e) {
    return void 0 !== t.updateTime ? e instanceof Nt && e.version.isEqual(t.updateTime) : void 0 === t.exists || t.exists === e instanceof Nt;
}

/**
 * A mutation describes a self-contained change to a document. Mutations can
 * create, replace, delete, and update subsets of documents.
 *
 * Mutations not only act on the value of the document but also its version.
 *
 * For local mutations (mutations that haven't been committed yet), we preserve
 * the existing version for Set and Patch mutations. For Delete mutations, we
 * reset the version to 0.
 *
 * Here's the expected transition table.
 *
 * MUTATION           APPLIED TO            RESULTS IN
 *
 * SetMutation        Document(v3)          Document(v3)
 * SetMutation        NoDocument(v3)        Document(v0)
 * SetMutation        null                  Document(v0)
 * PatchMutation      Document(v3)          Document(v3)
 * PatchMutation      NoDocument(v3)        NoDocument(v3)
 * PatchMutation      null                  null
 * DeleteMutation     Document(v3)          NoDocument(v0)
 * DeleteMutation     NoDocument(v3)        NoDocument(v0)
 * DeleteMutation     null                  NoDocument(v0)
 *
 * For acknowledged mutations, we use the updateTime of the WriteResponse as
 * the resulting version for Set and Patch mutations. As deletes have no
 * explicit update time, we use the commitTime of the WriteResponse for
 * Delete mutations.
 *
 * If a mutation is acknowledged by the backend but fails the precondition check
 * locally, we return an `UnknownDocument` and rely on Watch to send us the
 * updated version.
 *
 * Field transforms are used only with Patch and Set Mutations. We use the
 * `updateTransforms` message to store transforms, rather than the `transforms`s
 * messages.
 *
 * ## Subclassing Notes
 *
 * Subclasses of Mutation need to implement applyToRemoteDocument() and
 * applyToLocalView() to implement the actual behavior of applying the mutation
 * to some source document.
 */ class Ue {}

/**
 * Applies this mutation to the given MaybeDocument or null for the purposes
 * of computing a new remote document. If the input document doesn't match the
 * expected state (e.g. it is null or outdated), an `UnknownDocument` can be
 * returned.
 *
 * @param mutation - The mutation to apply.
 * @param maybeDoc - The document to mutate. The input document can be null if
 *     the client has no knowledge of the pre-mutation state of the document.
 * @param mutationResult - The result of applying the mutation from the backend.
 * @returns The mutated document. The returned document may be an
 *     UnknownDocument if the mutation could not be applied to the locally
 *     cached base document.
 */ function Qe(t, e, n) {
    return t instanceof ze ? function(t, e, n) {
        // Unlike applySetMutationToLocalView, if we're applying a mutation to a
        // remote document the server has accepted the mutation so the precondition
        // must have held.
        let s = t.value;
        if (n.transformResults) {
            const i = Ye(t.fieldTransforms, e, n.transformResults);
            s = Ze(t.fieldTransforms, s, i);
        }
        return new Nt(t.key, n.version, s, {
            hasCommittedMutations: !0
        });
    }(t, e, n) : t instanceof He ? function(t, e, n) {
        if (!qe(t.Gt, e)) 
        // Since the mutation was not rejected, we know that the precondition
        // matched on the backend. We therefore must not have the expected version
        // of the document in our cache and return an UnknownDocument with the
        // known updateTime.
        return new Ft(t.key, n.version);
        const s = n.transformResults ? Ye(t.fieldTransforms, e, n.transformResults) : [], i = Je(t, e, s);
        return new Nt(t.key, n.version, i, {
            hasCommittedMutations: !0
        });
    }(t, e, n) : function(t, e, n) {
        // Unlike applyToLocalView, if we're applying a mutation to a remote
        // document the server has accepted the mutation so the precondition must
        // have held.
        return new Ot(t.key, n.version, {
            hasCommittedMutations: !0
        });
    }(t, 0, n);
}

/**
 * Applies this mutation to the given MaybeDocument or null for the purposes
 * of computing the new local view of a document. Both the input and returned
 * documents can be null.
 *
 * @param mutation - The mutation to apply.
 * @param maybeDoc - The document to mutate. The input document can be null if
 *     the client has no knowledge of the pre-mutation state of the document.
 * @param baseDoc - The state of the document prior to this mutation batch. The
 *     input document can be null if the client has no knowledge of the
 *     pre-mutation state of the document.
 * @param localWriteTime - A timestamp indicating the local write time of the
 *     batch this mutation is a part of.
 * @returns The mutated document. The returned document may be null, but only
 *     if maybeDoc was null and the mutation would not create a new document.
 */ function Ke(t, e, n, s) {
    return t instanceof ze ? function(t, e, n, s) {
        if (!qe(t.Gt, e)) return e;
        let i = t.value;
        const r = Xe(t.fieldTransforms, n, e);
        i = Ze(t.fieldTransforms, i, r);
        const o = Ge(e);
        return new Nt(t.key, o, i, {
            bt: !0
        });
    }
    /**
 * A mutation that modifies fields of the document at the given key with the
 * given values. The values are applied through a field mask:
 *
 *  * When a field is in both the mask and the values, the corresponding field
 *    is updated.
 *  * When a field is in neither the mask nor the values, the corresponding
 *    field is unmodified.
 *  * When a field is in the mask but not in the values, the corresponding field
 *    is deleted.
 *  * When a field is not in the mask but is in the values, the values map is
 *    ignored.
 */ (t, e, s) : t instanceof He ? function(t, e, n, s) {
        if (!qe(t.Gt, e)) return e;
        const i = Ge(e), r = Xe(t.fieldTransforms, n, e), o = Je(t, e, r);
        return new Nt(t.key, i, o, {
            bt: !0
        });
    }
    /**
 * Patches the data of document if available or creates a new document. Note
 * that this does not check whether or not the precondition of this patch
 * holds.
 */ (t, e, s) : function(t, e) {
        if (!qe(t.Gt, e)) return e;
        return new Ot(t.key, J.min());
    }
    /**
 * A mutation that verifies the existence of the document at the given key with
 * the provided precondition.
 *
 * The `verify` operation is only used in Transactions, and this class serves
 * primarily to facilitate serialization into protos.
 */ (t, e);
}

/**
 * If this mutation is not idempotent, returns the base value to persist with
 * this mutation. If a base value is returned, the mutation is always applied
 * to this base value, even if document has already been updated.
 *
 * The base value is a sparse object that consists of only the document
 * fields for which this mutation contains a non-idempotent transformation
 * (e.g. a numeric increment). The provided value guarantees consistent
 * behavior for non-idempotent transforms and allow us to return the same
 * latency-compensated value even if the backend has already applied the
 * mutation. The base value is null for idempotent mutations, as they can be
 * re-played even if the backend has already applied them.
 *
 * @returns a base value to store along with the mutation, or null for
 * idempotent mutations.
 */ function je(t, e) {
    return function(t, e) {
        let n = null;
        for (const s of t) {
            const t = e instanceof Nt ? e.field(s.field) : void 0, i = ve(s.transform, t || null);
            null != i && (n = null == n ? (new Dt).set(s.field, i) : n.set(s.field, i));
        }
        return n ? n.yt() : null;
    }(t.fieldTransforms, e);
}

function We(t, e) {
    return t.type === e.type && (!!t.key.isEqual(e.key) && (!!t.Gt.isEqual(e.Gt) && (!!function(t, e) {
        return void 0 === t && void 0 === e || !(!t || !e) && C(t, e, ((t, e) => Le(t, e)));
    }(t.fieldTransforms, e.fieldTransforms) && (0 /* Set */ === t.type ? t.value.isEqual(e.value) : 1 /* Patch */ !== t.type || t.data.isEqual(e.data) && t.zt.isEqual(e.zt)))));
}

/**
 * Returns the version from the given document for use as the result of a
 * mutation. Mutations are defined to return the version of the base document
 * only if it is an existing document. Deleted and unknown documents have a
 * post-mutation version of SnapshotVersion.min().
 */ function Ge(t) {
    return t instanceof Nt ? t.version : J.min();
}

/**
 * A mutation that creates or replaces the document at the given key with the
 * object value contents.
 */ class ze extends Ue {
    constructor(t, e, n, s = []) {
        super(), this.key = t, this.value = e, this.Gt = n, this.fieldTransforms = s, this.type = 0 /* Set */;
    }
}

class He extends Ue {
    constructor(t, e, n, s, i = []) {
        super(), this.key = t, this.data = e, this.zt = n, this.Gt = s, this.fieldTransforms = i, 
        this.type = 1 /* Patch */;
    }
}

function Je(t, e, n) {
    let s;
    return s = e instanceof Nt ? e.data() : St.empty(), s = function(t, e) {
        const n = new Dt(e);
        return t.zt.fields.forEach((e => {
            if (!e.nt()) {
                const s = t.data.field(e);
                null !== s ? n.set(e, s) : n.delete(e);
            }
        })), n.yt();
    }
    /**
 * Creates a list of "transform results" (a transform result is a field value
 * representing the result of applying a transform) for use after a mutation
 * containing transforms has been acknowledged by the server.
 *
 * @param fieldTransforms - The field transforms to apply the result to.
 * @param baseDoc - The document prior to applying this mutation batch.
 * @param serverTransformResults - The transform results received by the server.
 * @returns The transform results list.
 */ (t, s), s = Ze(t.fieldTransforms, s, n), s;
}

function Ye(t, e, n) {
    const s = [];
    p(t.length === n.length);
    for (let i = 0; i < n.length; i++) {
        const r = t[i], o = r.transform;
        let c = null;
        e instanceof Nt && (c = e.field(r.field)), s.push(be(o, c, n[i]));
    }
    return s;
}

/**
 * Creates a list of "transform results" (a transform result is a field value
 * representing the result of applying a transform) for use when applying a
 * transform locally.
 *
 * @param fieldTransforms - The field transforms to apply the result to.
 * @param localWriteTime - The local time of the mutation (used to
 *     generate ServerTimestampValues).
 * @param maybeDoc - The current state of the document after applying all
 *     previous mutations.
 * @param baseDoc - The document prior to applying this mutation batch.
 * @returns The transform results list.
 */ function Xe(t, e, n, s) {
    const i = [];
    for (const s of t) {
        const t = s.transform;
        let r = null;
        n instanceof Nt && (r = n.field(s.field)), i.push(pe(t, r, e));
    }
    return i;
}

function Ze(t, e, n) {
    const s = new Dt(e);
    for (let e = 0; e < t.length; e++) {
        const i = t[e];
        s.set(i.field, n[e]);
    }
    return s.yt();
}

/** A mutation that deletes the document at the given key. */ class tn extends Ue {
    constructor(t, e) {
        super(), this.key = t, this.Gt = e, this.type = 2 /* Delete */ , this.fieldTransforms = [];
    }
}

class en extends Ue {
    constructor(t, e) {
        super(), this.key = t, this.Gt = e, this.type = 3 /* Verify */ , this.fieldTransforms = [];
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class nn {
    // TODO(b/33078163): just use simplest form of existence filter for now
    constructor(t) {
        this.count = t;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Error Codes describing the different ways GRPC can fail. These are copied
 * directly from GRPC's sources here:
 *
 * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
 *
 * Important! The names of these identifiers matter because the string forms
 * are used for reverse lookups from the webchannel stream. Do NOT change the
 * names of these identifiers or change this into a const enum.
 */ var sn, rn;

/**
 * Determines whether an error code represents a permanent error when received
 * in response to a non-write operation.
 *
 * See isPermanentWriteError for classifying write errors.
 */
function on(t) {
    switch (t) {
      case O.OK:
        return V();

      case O.CANCELLED:
      case O.UNKNOWN:
      case O.DEADLINE_EXCEEDED:
      case O.RESOURCE_EXHAUSTED:
      case O.INTERNAL:
      case O.UNAVAILABLE:
 // Unauthenticated means something went wrong with our token and we need
        // to retry with new credentials which will happen automatically.
              case O.UNAUTHENTICATED:
        return !1;

      case O.INVALID_ARGUMENT:
      case O.NOT_FOUND:
      case O.ALREADY_EXISTS:
      case O.PERMISSION_DENIED:
      case O.FAILED_PRECONDITION:
 // Aborted might be retried in some scenarios, but that is dependant on
        // the context and should handled individually by the calling code.
        // See https://cloud.google.com/apis/design/errors.
              case O.ABORTED:
      case O.OUT_OF_RANGE:
      case O.UNIMPLEMENTED:
      case O.DATA_LOSS:
        return !0;

      default:
        return V();
    }
}

/**
 * Determines whether an error code represents a permanent error when received
 * in response to a write operation.
 *
 * Write operations must be handled specially because as of b/119437764, ABORTED
 * errors on the write stream should be retried too (even though ABORTED errors
 * are not generally retryable).
 *
 * Note that during the initial handshake on the write stream an ABORTED error
 * signals that we should discard our stream token (i.e. it is permanent). This
 * means a handshake error should be classified with isPermanentError, above.
 */
/**
 * Maps an error Code from GRPC status code number, like 0, 1, or 14. These
 * are not the same as HTTP status codes.
 *
 * @returns The Code equivalent to the given GRPC status code. Fails if there
 *     is no match.
 */
function cn(t) {
    if (void 0 === t) 
    // This shouldn't normally happen, but in certain error cases (like trying
    // to send invalid proto messages) we may get an error with no GRPC code.
    return P("GRPC error has no .code"), O.UNKNOWN;
    switch (t) {
      case sn.OK:
        return O.OK;

      case sn.CANCELLED:
        return O.CANCELLED;

      case sn.UNKNOWN:
        return O.UNKNOWN;

      case sn.DEADLINE_EXCEEDED:
        return O.DEADLINE_EXCEEDED;

      case sn.RESOURCE_EXHAUSTED:
        return O.RESOURCE_EXHAUSTED;

      case sn.INTERNAL:
        return O.INTERNAL;

      case sn.UNAVAILABLE:
        return O.UNAVAILABLE;

      case sn.UNAUTHENTICATED:
        return O.UNAUTHENTICATED;

      case sn.INVALID_ARGUMENT:
        return O.INVALID_ARGUMENT;

      case sn.NOT_FOUND:
        return O.NOT_FOUND;

      case sn.ALREADY_EXISTS:
        return O.ALREADY_EXISTS;

      case sn.PERMISSION_DENIED:
        return O.PERMISSION_DENIED;

      case sn.FAILED_PRECONDITION:
        return O.FAILED_PRECONDITION;

      case sn.ABORTED:
        return O.ABORTED;

      case sn.OUT_OF_RANGE:
        return O.OUT_OF_RANGE;

      case sn.UNIMPLEMENTED:
        return O.UNIMPLEMENTED;

      case sn.DATA_LOSS:
        return O.DATA_LOSS;

      default:
        return V();
    }
}

/**
 * Converts an HTTP response's error status to the equivalent error code.
 *
 * @param status - An HTTP error response status ("FAILED_PRECONDITION",
 * "UNKNOWN", etc.)
 * @returns The equivalent Code. Non-matching responses are mapped to
 *     Code.UNKNOWN.
 */ (rn = sn || (sn = {}))[rn.OK = 0] = "OK", rn[rn.CANCELLED = 1] = "CANCELLED", 
rn[rn.UNKNOWN = 2] = "UNKNOWN", rn[rn.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", 
rn[rn.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", rn[rn.NOT_FOUND = 5] = "NOT_FOUND", 
rn[rn.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", rn[rn.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", 
rn[rn.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", rn[rn.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", 
rn[rn.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", rn[rn.ABORTED = 10] = "ABORTED", 
rn[rn.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", rn[rn.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", 
rn[rn.INTERNAL = 13] = "INTERNAL", rn[rn.UNAVAILABLE = 14] = "UNAVAILABLE", rn[rn.DATA_LOSS = 15] = "DATA_LOSS";

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// An immutable sorted map implementation, based on a Left-leaning Red-Black
// tree.
class an {
    constructor(t, e) {
        this.J = t, this.root = e || hn.EMPTY;
    }
    // Returns a copy of the map, with the specified key/value added or replaced.
    Ht(t, e) {
        return new an(this.J, this.root.Ht(t, e, this.J).copy(null, null, hn.Jt, null, null));
    }
    // Returns a copy of the map, with the specified key removed.
    remove(t) {
        return new an(this.J, this.root.remove(t, this.J).copy(null, null, hn.Jt, null, null));
    }
    // Returns the value of the node with the given key, or null.
    get(t) {
        let e = this.root;
        for (;!e.nt(); ) {
            const n = this.J(t, e.key);
            if (0 === n) return e.value;
            n < 0 ? e = e.left : n > 0 && (e = e.right);
        }
        return null;
    }
    // Returns the index of the element in this sorted map, or -1 if it doesn't
    // exist.
    indexOf(t) {
        // Number of nodes that were pruned when descending right
        let e = 0, n = this.root;
        for (;!n.nt(); ) {
            const s = this.J(t, n.key);
            if (0 === s) return e + n.left.size;
            s < 0 ? n = n.left : (
            // Count all nodes left of the node plus the node itself
            e += n.left.size + 1, n = n.right);
        }
        // Node not found
                return -1;
    }
    nt() {
        return this.root.nt();
    }
    // Returns the total number of nodes in the map.
    get size() {
        return this.root.size;
    }
    // Returns the minimum key in the map.
    Yt() {
        return this.root.Yt();
    }
    // Returns the maximum key in the map.
    Xt() {
        return this.root.Xt();
    }
    // Traverses the map in key order and calls the specified action function
    // for each key/value pair. If action returns true, traversal is aborted.
    // Returns the first truthy value returned by action, or the last falsey
    // value returned by action.
    Zt(t) {
        return this.root.Zt(t);
    }
    forEach(t) {
        this.Zt(((e, n) => (t(e, n), !1)));
    }
    toString() {
        const t = [];
        return this.Zt(((e, n) => (t.push(`${e}:${n}`), !1))), `{${t.join(", ")}}`;
    }
    // Traverses the map in reverse key order and calls the specified action
    // function for each key/value pair. If action returns true, traversal is
    // aborted.
    // Returns the first truthy value returned by action, or the last falsey
    // value returned by action.
    te(t) {
        return this.root.te(t);
    }
    // Returns an iterator over the SortedMap.
    ee() {
        return new un(this.root, null, this.J, !1);
    }
    ne(t) {
        return new un(this.root, t, this.J, !1);
    }
    se() {
        return new un(this.root, null, this.J, !0);
    }
    ie(t) {
        return new un(this.root, t, this.J, !0);
    }
}

 // end SortedMap
// An iterator over an LLRBNode.
class un {
    constructor(t, e, n, s) {
        this.re = s, this.oe = [];
        let i = 1;
        for (;!t.nt(); ) if (i = e ? n(t.key, e) : 1, 
        // flip the comparison if we're going in reverse
        s && (i *= -1), i < 0) 
        // This node is less than our start key. ignore it
        t = this.re ? t.left : t.right; else {
            if (0 === i) {
                // This node is exactly equal to our start key. Push it on the stack,
                // but stop iterating;
                this.oe.push(t);
                break;
            }
            // This node is greater than our start key, add it to the stack and move
            // to the next one
            this.oe.push(t), t = this.re ? t.right : t.left;
        }
    }
    ce() {
        let t = this.oe.pop();
        const e = {
            key: t.key,
            value: t.value
        };
        if (this.re) for (t = t.left; !t.nt(); ) this.oe.push(t), t = t.right; else for (t = t.right; !t.nt(); ) this.oe.push(t), 
        t = t.left;
        return e;
    }
    ae() {
        return this.oe.length > 0;
    }
    ue() {
        if (0 === this.oe.length) return null;
        const t = this.oe[this.oe.length - 1];
        return {
            key: t.key,
            value: t.value
        };
    }
}

 // end SortedMapIterator
// Represents a node in a Left-leaning Red-Black tree.
class hn {
    constructor(t, e, n, s, i) {
        this.key = t, this.value = e, this.color = null != n ? n : hn.RED, this.left = null != s ? s : hn.EMPTY, 
        this.right = null != i ? i : hn.EMPTY, this.size = this.left.size + 1 + this.right.size;
    }
    // Returns a copy of the current node, optionally replacing pieces of it.
    copy(t, e, n, s, i) {
        return new hn(null != t ? t : this.key, null != e ? e : this.value, null != n ? n : this.color, null != s ? s : this.left, null != i ? i : this.right);
    }
    nt() {
        return !1;
    }
    // Traverses the tree in key order and calls the specified action function
    // for each node. If action returns true, traversal is aborted.
    // Returns the first truthy value returned by action, or the last falsey
    // value returned by action.
    Zt(t) {
        return this.left.Zt(t) || t(this.key, this.value) || this.right.Zt(t);
    }
    // Traverses the tree in reverse key order and calls the specified action
    // function for each node. If action returns true, traversal is aborted.
    // Returns the first truthy value returned by action, or the last falsey
    // value returned by action.
    te(t) {
        return this.right.te(t) || t(this.key, this.value) || this.left.te(t);
    }
    // Returns the minimum node in the tree.
    min() {
        return this.left.nt() ? this : this.left.min();
    }
    // Returns the maximum key in the tree.
    Yt() {
        return this.min().key;
    }
    // Returns the maximum key in the tree.
    Xt() {
        return this.right.nt() ? this.key : this.right.Xt();
    }
    // Returns new tree, with the key/value added.
    Ht(t, e, n) {
        let s = this;
        const i = n(t, s.key);
        return s = i < 0 ? s.copy(null, null, null, s.left.Ht(t, e, n), null) : 0 === i ? s.copy(null, e, null, null, null) : s.copy(null, null, null, null, s.right.Ht(t, e, n)), 
        s.he();
    }
    le() {
        if (this.left.nt()) return hn.EMPTY;
        let t = this;
        return t.left._e() || t.left.left._e() || (t = t.fe()), t = t.copy(null, null, null, t.left.le(), null), 
        t.he();
    }
    // Returns new tree, with the specified item removed.
    remove(t, e) {
        let n, s = this;
        if (e(t, s.key) < 0) s.left.nt() || s.left._e() || s.left.left._e() || (s = s.fe()), 
        s = s.copy(null, null, null, s.left.remove(t, e), null); else {
            if (s.left._e() && (s = s.de()), s.right.nt() || s.right._e() || s.right.left._e() || (s = s.we()), 
            0 === e(t, s.key)) {
                if (s.right.nt()) return hn.EMPTY;
                n = s.right.min(), s = s.copy(n.key, n.value, null, null, s.right.le());
            }
            s = s.copy(null, null, null, null, s.right.remove(t, e));
        }
        return s.he();
    }
    _e() {
        return this.color;
    }
    // Returns new tree after performing any needed rotations.
    he() {
        let t = this;
        return t.right._e() && !t.left._e() && (t = t.Ee()), t.left._e() && t.left.left._e() && (t = t.de()), 
        t.left._e() && t.right._e() && (t = t.Te()), t;
    }
    fe() {
        let t = this.Te();
        return t.right.left._e() && (t = t.copy(null, null, null, null, t.right.de()), t = t.Ee(), 
        t = t.Te()), t;
    }
    we() {
        let t = this.Te();
        return t.left.left._e() && (t = t.de(), t = t.Te()), t;
    }
    Ee() {
        const t = this.copy(null, null, hn.RED, null, this.right.left);
        return this.right.copy(null, null, this.color, t, null);
    }
    de() {
        const t = this.copy(null, null, hn.RED, this.left.right, null);
        return this.left.copy(null, null, this.color, null, t);
    }
    Te() {
        const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);
        return this.copy(null, null, !this.color, t, e);
    }
    // For testing.
    Ie() {
        const t = this.me();
        return Math.pow(2, t) <= this.size + 1;
    }
    // In a balanced RB tree, the black-depth (number of black nodes) from root to
    // leaves is equal on both sides.  This function verifies that or asserts.
    me() {
        if (this._e() && this.left._e()) throw V();
        if (this.right._e()) throw V();
        const t = this.left.me();
        if (t !== this.right.me()) throw V();
        return t + (this._e() ? 0 : 1);
    }
}

 // end LLRBNode
// Empty node is shared between all LLRB trees.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
hn.EMPTY = null, hn.RED = !0, hn.Jt = !1;

// end LLRBEmptyNode
hn.EMPTY = new 
// Represents an empty node (a leaf node in the Red-Black Tree).
class {
    constructor() {
        this.size = 0;
    }
    get key() {
        throw V();
    }
    get value() {
        throw V();
    }
    get color() {
        throw V();
    }
    get left() {
        throw V();
    }
    get right() {
        throw V();
    }
    // Returns a copy of the current node.
    copy(t, e, n, s, i) {
        return this;
    }
    // Returns a copy of the tree, with the specified key/value added.
    Ht(t, e, n) {
        return new hn(t, e);
    }
    // Returns a copy of the tree, with the specified key removed.
    remove(t, e) {
        return this;
    }
    nt() {
        return !0;
    }
    Zt(t) {
        return !1;
    }
    te(t) {
        return !1;
    }
    Yt() {
        return null;
    }
    Xt() {
        return null;
    }
    _e() {
        return !1;
    }
    // For testing.
    Ie() {
        return !0;
    }
    me() {
        return 0;
    }
};

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * SortedSet is an immutable (copy-on-write) collection that holds elements
 * in order specified by the provided comparator.
 *
 * NOTE: if provided comparator returns 0 for two elements, we consider them to
 * be equal!
 */
class ln {
    constructor(t) {
        this.J = t, this.data = new an(this.J);
    }
    has(t) {
        return null !== this.data.get(t);
    }
    first() {
        return this.data.Yt();
    }
    last() {
        return this.data.Xt();
    }
    get size() {
        return this.data.size;
    }
    indexOf(t) {
        return this.data.indexOf(t);
    }
    /** Iterates elements in order defined by "comparator" */    forEach(t) {
        this.data.Zt(((e, n) => (t(e), !1)));
    }
    /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */    Ae(t, e) {
        const n = this.data.ne(t[0]);
        for (;n.ae(); ) {
            const s = n.ce();
            if (this.J(s.key, t[1]) >= 0) return;
            e(s.key);
        }
    }
    /**
     * Iterates over `elem`s such that: start &lt;= elem until false is returned.
     */    Re(t, e) {
        let n;
        for (n = void 0 !== e ? this.data.ne(e) : this.data.ee(); n.ae(); ) {
            if (!t(n.ce().key)) return;
        }
    }
    /** Finds the least element greater than or equal to `elem`. */    Pe(t) {
        const e = this.data.ne(t);
        return e.ae() ? e.ce().key : null;
    }
    ee() {
        return new _n(this.data.ee());
    }
    ne(t) {
        return new _n(this.data.ne(t));
    }
    /** Inserts or updates an element */    add(t) {
        return this.copy(this.data.remove(t).Ht(t, !0));
    }
    /** Deletes an element */    delete(t) {
        return this.has(t) ? this.copy(this.data.remove(t)) : this;
    }
    nt() {
        return this.data.nt();
    }
    ye(t) {
        let e = this;
        // Make sure `result` always refers to the larger one of the two sets.
                return e.size < t.size && (e = t, t = this), t.forEach((t => {
            e = e.add(t);
        })), e;
    }
    isEqual(t) {
        if (!(t instanceof ln)) return !1;
        if (this.size !== t.size) return !1;
        const e = this.data.ee(), n = t.data.ee();
        for (;e.ae(); ) {
            const t = e.ce().key, s = n.ce().key;
            if (0 !== this.J(t, s)) return !1;
        }
        return !0;
    }
    rt() {
        const t = [];
        return this.forEach((e => {
            t.push(e);
        })), t;
    }
    toString() {
        const t = [];
        return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")";
    }
    copy(t) {
        const e = new ln(this.J);
        return e.data = t, e;
    }
}

class _n {
    constructor(t) {
        this.ge = t;
    }
    ce() {
        return this.ge.ce().key;
    }
    ae() {
        return this.ge.ae();
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const fn = new an(et.J);

function dn() {
    return fn;
}

function wn() {
    return dn();
}

const En = new an(et.J);

function Tn() {
    return En;
}

const In = new an(et.J);

function mn() {
    return In;
}

const An = new ln(et.J);

function Rn(...t) {
    let e = An;
    for (const n of t) e = e.add(n);
    return e;
}

const Pn = new ln(D);

function yn() {
    return Pn;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * DocumentSet is an immutable (copy-on-write) collection that holds documents
 * in order specified by the provided comparator. We always add a document key
 * comparator on top of what is provided to guarantee document equality based on
 * the key.
 */ class gn {
    /** The default ordering is by key if the comparator is omitted */
    constructor(t) {
        // We are adding document key comparator to the end as it's the only
        // guaranteed unique property of a document.
        this.J = t ? (e, n) => t(e, n) || et.J(e.key, n.key) : (t, e) => et.J(t.key, e.key), 
        this.Ve = Tn(), this.pe = new an(this.J);
    }
    /**
     * Returns an empty copy of the existing DocumentSet, using the same
     * comparator.
     */    static be(t) {
        return new gn(t.J);
    }
    has(t) {
        return null != this.Ve.get(t);
    }
    get(t) {
        return this.Ve.get(t);
    }
    first() {
        return this.pe.Yt();
    }
    last() {
        return this.pe.Xt();
    }
    nt() {
        return this.pe.nt();
    }
    /**
     * Returns the index of the provided key in the document set, or -1 if the
     * document key is not present in the set;
     */    indexOf(t) {
        const e = this.Ve.get(t);
        return e ? this.pe.indexOf(e) : -1;
    }
    get size() {
        return this.pe.size;
    }
    /** Iterates documents in order defined by "comparator" */    forEach(t) {
        this.pe.Zt(((e, n) => (t(e), !1)));
    }
    /** Inserts or updates a document with the same key */    add(t) {
        // First remove the element if we have it.
        const e = this.delete(t.key);
        return e.copy(e.Ve.Ht(t.key, t), e.pe.Ht(t, null));
    }
    /** Deletes a document with a given key */    delete(t) {
        const e = this.get(t);
        return e ? this.copy(this.Ve.remove(t), this.pe.remove(e)) : this;
    }
    isEqual(t) {
        if (!(t instanceof gn)) return !1;
        if (this.size !== t.size) return !1;
        const e = this.pe.ee(), n = t.pe.ee();
        for (;e.ae(); ) {
            const t = e.ce().key, s = n.ce().key;
            if (!t.isEqual(s)) return !1;
        }
        return !0;
    }
    toString() {
        const t = [];
        return this.forEach((e => {
            t.push(e.toString());
        })), 0 === t.length ? "DocumentSet ()" : "DocumentSet (\n  " + t.join("  \n") + "\n)";
    }
    copy(t, e) {
        const n = new gn;
        return n.J = this.J, n.Ve = t, n.pe = e, n;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * DocumentChangeSet keeps track of a set of changes to docs in a query, merging
 * duplicate events for the same doc.
 */ class Vn {
    constructor() {
        this.ve = new an(et.J);
    }
    track(t) {
        const e = t.doc.key, n = this.ve.get(e);
        n ? 
        // Merge the new change with the existing change.
        0 /* Added */ !== t.type && 3 /* Metadata */ === n.type ? this.ve = this.ve.Ht(e, t) : 3 /* Metadata */ === t.type && 1 /* Removed */ !== n.type ? this.ve = this.ve.Ht(e, {
            type: n.type,
            doc: t.doc
        }) : 2 /* Modified */ === t.type && 2 /* Modified */ === n.type ? this.ve = this.ve.Ht(e, {
            type: 2 /* Modified */ ,
            doc: t.doc
        }) : 2 /* Modified */ === t.type && 0 /* Added */ === n.type ? this.ve = this.ve.Ht(e, {
            type: 0 /* Added */ ,
            doc: t.doc
        }) : 1 /* Removed */ === t.type && 0 /* Added */ === n.type ? this.ve = this.ve.remove(e) : 1 /* Removed */ === t.type && 2 /* Modified */ === n.type ? this.ve = this.ve.Ht(e, {
            type: 1 /* Removed */ ,
            doc: n.doc
        }) : 0 /* Added */ === t.type && 1 /* Removed */ === n.type ? this.ve = this.ve.Ht(e, {
            type: 2 /* Modified */ ,
            doc: t.doc
        }) : 
        // This includes these cases, which don't make sense:
        // Added->Added
        // Removed->Removed
        // Modified->Added
        // Removed->Modified
        // Metadata->Added
        // Removed->Metadata
        V() : this.ve = this.ve.Ht(e, t);
    }
    Se() {
        const t = [];
        return this.ve.Zt(((e, n) => {
            t.push(n);
        })), t;
    }
}

class pn {
    constructor(t, e, n, s, i, r, o, c) {
        this.query = t, this.docs = e, this.De = n, this.docChanges = s, this.Ce = i, this.fromCache = r, 
        this.xe = o, this.Ne = c;
    }
    /** Returns a view snapshot as if all documents in the snapshot were added. */    static Oe(t, e, n, s) {
        const i = [];
        return e.forEach((t => {
            i.push({
                type: 0 /* Added */ ,
                doc: t
            });
        })), new pn(t, e, gn.be(e), i, n, s, 
        /* syncStateChanged= */ !0, 
        /* excludesMetadataChanges= */ !1);
    }
    get hasPendingWrites() {
        return !this.Ce.nt();
    }
    isEqual(t) {
        if (!(this.fromCache === t.fromCache && this.xe === t.xe && this.Ce.isEqual(t.Ce) && we(this.query, t.query) && this.docs.isEqual(t.docs) && this.De.isEqual(t.De))) return !1;
        const e = this.docChanges, n = t.docChanges;
        if (e.length !== n.length) return !1;
        for (let t = 0; t < e.length; t++) if (e[t].type !== n[t].type || !e[t].doc.isEqual(n[t].doc)) return !1;
        return !0;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An event from the RemoteStore. It is split into targetChanges (changes to the
 * state or the set of documents in our watched targets) and documentUpdates
 * (changes to the actual documents).
 */ class bn {
    constructor(
    /**
     * The snapshot version this event brings us up to, or MIN if not set.
     */
    t, 
    /**
     * A map from target to changes to the target. See TargetChange.
     */
    e, 
    /**
     * A set of targets that is known to be inconsistent. Listens for these
     * targets should be re-established without resume tokens.
     */
    n, 
    /**
     * A set of which documents have changed or been deleted, along with the
     * doc's new values (if not deleted).
     */
    s, 
    /**
     * A set of which document updates are due only to limbo resolution targets.
     */
    i) {
        this.Mt = t, this.Fe = e, this.ke = n, this.Me = s, this.Le = i;
    }
    /**
     * HACK: Views require RemoteEvents in order to determine whether the view is
     * CURRENT, but secondary tabs don't receive remote events. So this method is
     * used to create a synthesized RemoteEvent that can be used to apply a
     * CURRENT status change to a View, for queries executed in a different tab.
     */
    // PORTING NOTE: Multi-tab only
    static $e(t, e) {
        const n = new Map;
        return n.set(t, vn.Be(t, e)), new bn(J.min(), n, yn(), dn(), Rn());
    }
}

/**
 * A TargetChange specifies the set of changes for a specific target as part of
 * a RemoteEvent. These changes track which documents are added, modified or
 * removed, as well as the target's resume token and whether the target is
 * marked CURRENT.
 * The actual changes *to* documents are not part of the TargetChange since
 * documents may be part of multiple targets.
 */ class vn {
    constructor(
    /**
     * An opaque, server-assigned token that allows watching a query to be resumed
     * after disconnecting without retransmitting all the data that matches the
     * query. The resume token essentially identifies a point in time from which
     * the server should resume sending results.
     */
    t, 
    /**
     * The "current" (synced) status of this target. Note that "current"
     * has special meaning in the RPC protocol that implies that a target is
     * both up-to-date and consistent with the rest of the watch stream.
     */
    e, 
    /**
     * The set of documents that were newly assigned to this target as part of
     * this remote event.
     */
    n, 
    /**
     * The set of documents that were already assigned to this target but received
     * an update during this remote event.
     */
    s, 
    /**
     * The set of documents that were removed from this target as part of this
     * remote event.
     */
    i) {
        this.resumeToken = t, this.qe = e, this.Ue = n, this.Qe = s, this.Ke = i;
    }
    /**
     * This method is used to create a synthesized TargetChanges that can be used to
     * apply a CURRENT status change to a View (for queries executed in a different
     * tab) or for new queries (to raise snapshots with correct CURRENT status).
     */    static Be(t, e) {
        return new vn(N.h, e, Rn(), Rn(), Rn());
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Represents a changed document and a list of target ids to which this change
 * applies.
 *
 * If document has been deleted NoDocument will be provided.
 */ class Sn {
    constructor(
    /** The new document applies to all of these targets. */
    t, 
    /** The new document is removed from all of these targets. */
    e, 
    /** The key of the document for this change. */
    n, 
    /**
     * The new document or NoDocument if it was deleted. Is null if the
     * document went out of view without the server sending a new document.
     */
    s) {
        this.je = t, this.removedTargetIds = e, this.key = n, this.We = s;
    }
}

class Dn {
    constructor(t, e) {
        this.targetId = t, this.Ge = e;
    }
}

class Cn {
    constructor(
    /** What kind of change occurred to the watch target. */
    t, 
    /** The target IDs that were added/removed/set. */
    e, 
    /**
     * An opaque, server-assigned token that allows watching a target to be
     * resumed after disconnecting without retransmitting all the data that
     * matches the target. The resume token essentially identifies a point in
     * time from which the server should resume sending results.
     */
    n = N.h
    /** An RPC error indicating why the watch failed. */ , s = null) {
        this.state = t, this.targetIds = e, this.resumeToken = n, this.cause = s;
    }
}

/** Tracks the internal state of a Watch target. */ class xn {
    constructor() {
        /**
         * The number of pending responses (adds or removes) that we are waiting on.
         * We only consider targets active that have no pending responses.
         */
        this.ze = 0, 
        /**
         * Keeps track of the document changes since the last raised snapshot.
         *
         * These changes are continuously updated as we receive document updates and
         * always reflect the current set of changes against the last issued snapshot.
         */
        this.He = Fn(), 
        /** See public getters for explanations of these fields. */
        this.Je = N.h, this.Ye = !1, 
        /**
         * Whether this target state should be included in the next snapshot. We
         * initialize to true so that newly-added targets are included in the next
         * RemoteEvent.
         */
        this.Xe = !0;
    }
    /**
     * Whether this target has been marked 'current'.
     *
     * 'Current' has special meaning in the RPC protocol: It implies that the
     * Watch backend has sent us all changes up to the point at which the target
     * was added and that the target is consistent with the rest of the watch
     * stream.
     */    get qe() {
        return this.Ye;
    }
    /** The last resume token sent to us for this target. */    get resumeToken() {
        return this.Je;
    }
    /** Whether this target has pending target adds or target removes. */    get Ze() {
        return 0 !== this.ze;
    }
    /** Whether we have modified any state that should trigger a snapshot. */    get tn() {
        return this.Xe;
    }
    /**
     * Applies the resume token to the TargetChange, but only when it has a new
     * value. Empty resumeTokens are discarded.
     */    en(t) {
        t.o() > 0 && (this.Xe = !0, this.Je = t);
    }
    /**
     * Creates a target change from the current set of changes.
     *
     * To reset the document changes after raising this snapshot, call
     * `clearPendingChanges()`.
     */    nn() {
        let t = Rn(), e = Rn(), n = Rn();
        return this.He.forEach(((s, i) => {
            switch (i) {
              case 0 /* Added */ :
                t = t.add(s);
                break;

              case 2 /* Modified */ :
                e = e.add(s);
                break;

              case 1 /* Removed */ :
                n = n.add(s);
                break;

              default:
                V();
            }
        })), new vn(this.Je, this.Ye, t, e, n);
    }
    /**
     * Resets the document changes and sets `hasPendingChanges` to false.
     */    sn() {
        this.Xe = !1, this.He = Fn();
    }
    rn(t, e) {
        this.Xe = !0, this.He = this.He.Ht(t, e);
    }
    on(t) {
        this.Xe = !0, this.He = this.He.remove(t);
    }
    cn() {
        this.ze += 1;
    }
    an() {
        this.ze -= 1;
    }
    un() {
        this.Xe = !0, this.Ye = !0;
    }
}

/**
 * A helper class to accumulate watch changes into a RemoteEvent.
 */
class Nn {
    constructor(t) {
        this.hn = t, 
        /** The internal state of all tracked targets. */
        this.ln = new Map, 
        /** Keeps track of the documents to update since the last raised snapshot. */
        this._n = dn(), 
        /** A mapping of document keys to their set of target IDs. */
        this.fn = On(), 
        /**
         * A list of targets with existence filter mismatches. These targets are
         * known to be inconsistent and their listens needs to be re-established by
         * RemoteStore.
         */
        this.dn = new ln(D);
    }
    /**
     * Processes and adds the DocumentWatchChange to the current set of changes.
     */    wn(t) {
        for (const e of t.je) t.We instanceof Nt ? this.En(e, t.We) : t.We instanceof Ot && this.Tn(e, t.key, t.We);
        for (const e of t.removedTargetIds) this.Tn(e, t.key, t.We);
    }
    /** Processes and adds the WatchTargetChange to the current set of changes. */    In(t) {
        this.mn(t, (e => {
            const n = this.An(e);
            switch (t.state) {
              case 0 /* NoChange */ :
                this.Rn(e) && n.en(t.resumeToken);
                break;

              case 1 /* Added */ :
                // We need to decrement the number of pending acks needed from watch
                // for this targetId.
                n.an(), n.Ze || 
                // We have a freshly added target, so we need to reset any state
                // that we had previously. This can happen e.g. when remove and add
                // back a target for existence filter mismatches.
                n.sn(), n.en(t.resumeToken);
                break;

              case 2 /* Removed */ :
                // We need to keep track of removed targets to we can post-filter and
                // remove any target changes.
                // We need to decrement the number of pending acks needed from watch
                // for this targetId.
                n.an(), n.Ze || this.removeTarget(e);
                break;

              case 3 /* Current */ :
                this.Rn(e) && (n.un(), n.en(t.resumeToken));
                break;

              case 4 /* Reset */ :
                this.Rn(e) && (
                // Reset the target and synthesizes removes for all existing
                // documents. The backend will re-add any documents that still
                // match the target before it sends the next global snapshot.
                this.Pn(e), n.en(t.resumeToken));
                break;

              default:
                V();
            }
        }));
    }
    /**
     * Iterates over all targetIds that the watch change applies to: either the
     * targetIds explicitly listed in the change or the targetIds of all currently
     * active targets.
     */    mn(t, e) {
        t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.ln.forEach(((t, n) => {
            this.Rn(n) && e(n);
        }));
    }
    /**
     * Handles existence filters and synthesizes deletes for filter mismatches.
     * Targets that are invalidated by filter mismatches are added to
     * `pendingTargetResets`.
     */    yn(t) {
        const e = t.targetId, n = t.Ge.count, s = this.gn(e);
        if (s) {
            const t = s.target;
            if (qt(t)) if (0 === n) {
                // The existence filter told us the document does not exist. We deduce
                // that this document does not exist and apply a deleted document to
                // our updates. Without applying this deleted document there might be
                // another query that will raise this document as part of a snapshot
                // until it is resolved, essentially exposing inconsistency between
                // queries.
                const n = new et(t.path);
                this.Tn(e, n, new Ot(n, J.min()));
            } else p(1 === n); else {
                this.Vn(e) !== n && (
                // Existence filter mismatch: We reset the mapping and raise a new
                // snapshot with `isFromCache:true`.
                this.Pn(e), this.dn = this.dn.add(e));
            }
        }
    }
    /**
     * Converts the currently accumulated state into a remote event at the
     * provided snapshot version. Resets the accumulated changes before returning.
     */    pn(t) {
        const e = new Map;
        this.ln.forEach(((n, s) => {
            const i = this.gn(s);
            if (i) {
                if (n.qe && qt(i.target)) {
                    // Document queries for document that don't exist can produce an empty
                    // result set. To update our local cache, we synthesize a document
                    // delete if we have not previously received the document. This
                    // resolves the limbo state of the document, removing it from
                    // limboDocumentRefs.
                    // TODO(dimond): Ideally we would have an explicit lookup target
                    // instead resulting in an explicit delete message and we could
                    // remove this special logic.
                    const e = new et(i.target.path);
                    null !== this._n.get(e) || this.bn(s, e) || this.Tn(s, e, new Ot(e, t));
                }
                n.tn && (e.set(s, n.nn()), n.sn());
            }
        }));
        let n = Rn();
        // We extract the set of limbo-only document updates as the GC logic
        // special-cases documents that do not appear in the target cache.
        
        // TODO(gsoltis): Expand on this comment once GC is available in the JS
        // client.
                this.fn.forEach(((t, e) => {
            let s = !0;
            e.Re((t => {
                const e = this.gn(t);
                return !e || 2 /* LimboResolution */ === e.kt || (s = !1, !1);
            })), s && (n = n.add(t));
        }));
        const s = new bn(t, e, this.dn, this._n, n);
        return this._n = dn(), this.fn = On(), this.dn = new ln(D), s;
    }
    /**
     * Adds the provided document to the internal list of document updates and
     * its document key to the given target's mapping.
     */
    // Visible for testing.
    En(t, e) {
        if (!this.Rn(t)) return;
        const n = this.bn(t, e.key) ? 2 /* Modified */ : 0 /* Added */;
        this.An(t).rn(e.key, n), this._n = this._n.Ht(e.key, e), this.fn = this.fn.Ht(e.key, this.vn(e.key).add(t));
    }
    /**
     * Removes the provided document from the target mapping. If the
     * document no longer matches the target, but the document's state is still
     * known (e.g. we know that the document was deleted or we received the change
     * that caused the filter mismatch), the new document can be provided
     * to update the remote document cache.
     */
    // Visible for testing.
    Tn(t, e, n) {
        if (!this.Rn(t)) return;
        const s = this.An(t);
        this.bn(t, e) ? s.rn(e, 1 /* Removed */) : 
        // The document may have entered and left the target before we raised a
        // snapshot, so we can just ignore the change.
        s.on(e), this.fn = this.fn.Ht(e, this.vn(e).delete(t)), n && (this._n = this._n.Ht(e, n));
    }
    removeTarget(t) {
        this.ln.delete(t);
    }
    /**
     * Returns the current count of documents in the target. This includes both
     * the number of documents that the LocalStore considers to be part of the
     * target as well as any accumulated changes.
     */    Vn(t) {
        const e = this.An(t).nn();
        return this.hn.Sn(t).size + e.Ue.size - e.Ke.size;
    }
    /**
     * Increment the number of acks needed from watch before we can consider the
     * server to be 'in-sync' with the client's active targets.
     */    cn(t) {
        this.An(t).cn();
    }
    An(t) {
        let e = this.ln.get(t);
        return e || (e = new xn, this.ln.set(t, e)), e;
    }
    vn(t) {
        let e = this.fn.get(t);
        return e || (e = new ln(D), this.fn = this.fn.Ht(t, e)), e;
    }
    /**
     * Verifies that the user is still interested in this target (by calling
     * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs
     * from watch.
     */    Rn(t) {
        const e = null !== this.gn(t);
        return e || R("WatchChangeAggregator", "Detected inactive target", t), e;
    }
    /**
     * Returns the TargetData for an active target (i.e. a target that the user
     * is still interested in that has no outstanding target change requests).
     */    gn(t) {
        const e = this.ln.get(t);
        return e && e.Ze ? null : this.hn.Dn(t);
    }
    /**
     * Resets the state of a Watch target to its initial state (e.g. sets
     * 'current' to false, clears the resume token and removes its target mapping
     * from all documents).
     */    Pn(t) {
        this.ln.set(t, new xn);
        this.hn.Sn(t).forEach((e => {
            this.Tn(t, e, /*updatedDocument=*/ null);
        }));
    }
    /**
     * Returns whether the LocalStore considers the document to be part of the
     * specified target.
     */    bn(t, e) {
        return this.hn.Sn(t).has(e);
    }
}

function On() {
    return new an(et.J);
}

function Fn() {
    return new an(et.J);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const kn = (() => {
    const t = {
        asc: "ASCENDING",
        desc: "DESCENDING"
    };
    return t;
})(), Mn = (() => {
    const t = {
        "<": "LESS_THAN",
        "<=": "LESS_THAN_OR_EQUAL",
        ">": "GREATER_THAN",
        ">=": "GREATER_THAN_OR_EQUAL",
        "==": "EQUAL",
        "!=": "NOT_EQUAL",
        "array-contains": "ARRAY_CONTAINS",
        in: "IN",
        "not-in": "NOT_IN",
        "array-contains-any": "ARRAY_CONTAINS_ANY"
    };
    return t;
})();

/**
 * This class generates JsonObject values for the Datastore API suitable for
 * sending to either GRPC stub methods or via the JSON/HTTP REST API.
 *
 * The serializer supports both Protobuf.js and Proto3 JSON formats. By
 * setting `useProto3Json` to true, the serializer will use the Proto3 JSON
 * format.
 *
 * For a description of the Proto3 JSON format check
 * https://developers.google.com/protocol-buffers/docs/proto3#json
 *
 * TODO(klimt): We can remove the databaseId argument if we keep the full
 * resource name in documents.
 */
class Ln {
    constructor(t, e) {
        this.T = t, this.qt = e;
    }
}

/**
 * Returns a value for a Date that's appropriate to put into a proto.
 */
function $n(t, e) {
    if (t.qt) {
        return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`;
    }
    return {
        seconds: "" + e.seconds,
        nanos: e.nanoseconds
    };
}

/**
 * Returns a value for bytes that's appropriate to put in a proto.
 *
 * Visible for testing.
 */
function Bn(t, e) {
    return t.qt ? e.toBase64() : e.toUint8Array();
}

/**
 * Returns a ByteString based on the proto string value.
 */ function qn(t, e) {
    return $n(t, e.G());
}

function Un(t) {
    return p(!!t), J.j(function(t) {
        const e = ct(t);
        return new H(e.seconds, e.nanos);
    }(t));
}

function Qn(t, e) {
    return function(t) {
        return new X([ "projects", t.projectId, "databases", t.database ]);
    }(t).child("documents").child(e).ot();
}

function Kn(t) {
    const e = X.ct(t);
    return p(Is(e)), e;
}

function jn(t, e) {
    return Qn(t.T, e.path);
}

function Wn(t, e) {
    const n = Kn(e);
    if (n.get(1) !== t.T.projectId) throw new F(O.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n.get(1) + " vs " + t.T.projectId);
    if (n.get(3) !== t.T.database) throw new F(O.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n.get(3) + " vs " + t.T.database);
    return new et(Jn(n));
}

function Gn(t, e) {
    return Qn(t.T, e);
}

function zn(t) {
    const e = Kn(t);
    // In v1beta1 queries for collections at the root did not have a trailing
    // "/documents". In v1 all resource paths contain "/documents". Preserve the
    // ability to read the v1beta1 form for compatibility with queries persisted
    // in the local target cache.
        return 4 === e.length ? X.at() : Jn(e);
}

function Hn(t) {
    return new X([ "projects", t.T.projectId, "databases", t.T.database ]).ot();
}

function Jn(t) {
    return p(t.length > 4 && "documents" === t.get(4)), t.X(5);
}

/** Creates a Document proto from key and fields (but no create/update time) */ function Yn(t, e, n) {
    return {
        name: jn(t, e),
        fields: n.proto.mapValue.fields
    };
}

function Xn(t, e, n) {
    const s = Wn(t, e.name), i = Un(e.updateTime), r = new St({
        mapValue: {
            fields: e.fields
        }
    });
    return new Nt(s, i, r, {
        hasCommittedMutations: !!n
    });
}

function Zn(t, e) {
    return "found" in e ? function(t, e) {
        p(!!e.found), e.found.name, e.found.updateTime;
        const n = Wn(t, e.found.name), s = Un(e.found.updateTime), i = new St({
            mapValue: {
                fields: e.found.fields
            }
        });
        return new Nt(n, s, i, {});
    }(t, e) : "missing" in e ? function(t, e) {
        p(!!e.missing), p(!!e.readTime);
        const n = Wn(t, e.missing), s = Un(e.readTime);
        return new Ot(n, s);
    }(t, e) : V();
}

function ts(t, e) {
    let n;
    if ("targetChange" in e) {
        e.targetChange;
        // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'
        // if unset
        const s = function(t) {
            return "NO_CHANGE" === t ? 0 /* NoChange */ : "ADD" === t ? 1 /* Added */ : "REMOVE" === t ? 2 /* Removed */ : "CURRENT" === t ? 3 /* Current */ : "RESET" === t ? 4 /* Reset */ : V();
        }(e.targetChange.targetChangeType || "NO_CHANGE"), i = e.targetChange.targetIds || [], r = function(t, e) {
            return t.qt ? (p(void 0 === e || "string" == typeof e), N.fromBase64String(e || "")) : (p(void 0 === e || e instanceof Uint8Array), 
            N.fromUint8Array(e || new Uint8Array));
        }(t, e.targetChange.resumeToken), o = e.targetChange.cause, c = o && function(t) {
            const e = void 0 === t.code ? O.UNKNOWN : cn(t.code);
            return new F(e, t.message || "");
        }
        /**
 * Returns a value for a number (or null) that's appropriate to put into
 * a google.protobuf.Int32Value proto.
 * DO NOT USE THIS FOR ANYTHING ELSE.
 * This method cheats. It's typed as returning "number" because that's what
 * our generated proto interfaces say Int32Value must be. But GRPC actually
 * expects a { value: <number> } struct.
 */ (o);
        n = new Cn(s, i, r, c || null);
    } else if ("documentChange" in e) {
        e.documentChange;
        const s = e.documentChange;
        s.document, s.document.name, s.document.updateTime;
        const i = Wn(t, s.document.name), r = Un(s.document.updateTime), o = new St({
            mapValue: {
                fields: s.document.fields
            }
        }), c = new Nt(i, r, o, {}), a = s.targetIds || [], u = s.removedTargetIds || [];
        n = new Sn(a, u, c.key, c);
    } else if ("documentDelete" in e) {
        e.documentDelete;
        const s = e.documentDelete;
        s.document;
        const i = Wn(t, s.document), r = s.readTime ? Un(s.readTime) : J.min(), o = new Ot(i, r), c = s.removedTargetIds || [];
        n = new Sn([], c, o.key, o);
    } else if ("documentRemove" in e) {
        e.documentRemove;
        const s = e.documentRemove;
        s.document;
        const i = Wn(t, s.document), r = s.removedTargetIds || [];
        n = new Sn([], r, i, null);
    } else {
        if (!("filter" in e)) return V();
        {
            e.filter;
            const t = e.filter;
            t.targetId;
            const s = t.count || 0, i = new nn(s), r = t.targetId;
            n = new Dn(r, i);
        }
    }
    return n;
}

function es(t, e) {
    let n;
    if (e instanceof ze) n = {
        update: Yn(t, e.key, e.value)
    }; else if (e instanceof tn) n = {
        delete: jn(t, e.key)
    }; else if (e instanceof He) n = {
        update: Yn(t, e.key, e.data),
        updateMask: Ts(e.zt)
    }; else {
        if (!(e instanceof en)) return V();
        n = {
            verify: jn(t, e.key)
        };
    }
    return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((t => function(t, e) {
        const n = e.transform;
        if (n instanceof Se) return {
            fieldPath: e.field.ot(),
            setToServerValue: "REQUEST_TIME"
        };
        if (n instanceof De) return {
            fieldPath: e.field.ot(),
            appendMissingElements: {
                values: n.elements
            }
        };
        if (n instanceof xe) return {
            fieldPath: e.field.ot(),
            removeAllFromArray: {
                values: n.elements
            }
        };
        if (n instanceof Oe) return {
            fieldPath: e.field.ot(),
            increment: n.Qt
        };
        throw V();
    }(0, t)))), e.Gt.Wt || (n.currentDocument = function(t, e) {
        return void 0 !== e.updateTime ? {
            updateTime: qn(t, e.updateTime)
        } : void 0 !== e.exists ? {
            exists: e.exists
        } : V();
    }(t, e.Gt)), n;
}

function ns(t, e) {
    const n = e.currentDocument ? function(t) {
        return void 0 !== t.updateTime ? Be.updateTime(Un(t.updateTime)) : void 0 !== t.exists ? Be.exists(t.exists) : Be.jt();
    }(e.currentDocument) : Be.jt(), s = e.updateTransforms ? e.updateTransforms.map((e => function(t, e) {
        let n = null;
        if ("setToServerValue" in e) p("REQUEST_TIME" === e.setToServerValue), n = new Se; else if ("appendMissingElements" in e) {
            const t = e.appendMissingElements.values || [];
            n = new De(t);
        } else if ("removeAllFromArray" in e) {
            const t = e.removeAllFromArray.values || [];
            n = new xe(t);
        } else "increment" in e ? n = new Oe(t, e.increment) : V();
        const s = tt._t(e.fieldPath);
        return new Me(s, n);
    }(t, e))) : [];
    if (e.update) {
        e.update.name;
        const i = Wn(t, e.update.name), r = new St({
            mapValue: {
                fields: e.update.fields
            }
        });
        if (e.updateMask) {
            const t = function(t) {
                const e = t.fieldPaths || [];
                return new rt(e.map((t => tt._t(t))));
            }(e.updateMask);
            return new He(i, r, t, n, s);
        }
        return new ze(i, r, n, s);
    }
    if (e.delete) {
        const s = Wn(t, e.delete);
        return new tn(s, n);
    }
    if (e.verify) {
        const s = Wn(t, e.verify);
        return new en(s, n);
    }
    return V();
}

function ss(t, e) {
    return t && t.length > 0 ? (p(void 0 !== e), t.map((t => function(t, e) {
        // NOTE: Deletes don't have an updateTime.
        let n = t.updateTime ? Un(t.updateTime) : Un(e);
        n.isEqual(J.min()) && (
        // The Firestore Emulator currently returns an update time of 0 for
        // deletes of non-existing documents (rather than null). This breaks the
        // test "get deleted doc while offline with source=cache" as NoDocuments
        // with version 0 are filtered by IndexedDb's RemoteDocumentCache.
        // TODO(#2149): Remove this when Emulator is fixed
        n = Un(e));
        let s = null;
        return t.transformResults && t.transformResults.length > 0 && (s = t.transformResults), 
        new $e(n, s);
    }(t, e)))) : [];
}

function is(t, e) {
    return {
        documents: [ Gn(t, e.path) ]
    };
}

function rs(t, e) {
    // Dissect the path into parent, collectionId, and optional key filter.
    const n = {
        structuredQuery: {}
    }, s = e.path;
    null !== e.collectionGroup ? (n.parent = Gn(t, s), n.structuredQuery.from = [ {
        collectionId: e.collectionGroup,
        allDescendants: !0
    } ]) : (n.parent = Gn(t, s.Z()), n.structuredQuery.from = [ {
        collectionId: s.et()
    } ]);
    const i = function(t) {
        if (0 === t.length) return;
        const e = t.map((t => 
        // visible for testing
        function(t) {
            if ("==" /* EQUAL */ === t.op) {
                if (bt(t.value)) return {
                    unaryFilter: {
                        field: fs(t.field),
                        op: "IS_NAN"
                    }
                };
                if (pt(t.value)) return {
                    unaryFilter: {
                        field: fs(t.field),
                        op: "IS_NULL"
                    }
                };
            } else if ("!=" /* NOT_EQUAL */ === t.op) {
                if (bt(t.value)) return {
                    unaryFilter: {
                        field: fs(t.field),
                        op: "IS_NOT_NAN"
                    }
                };
                if (pt(t.value)) return {
                    unaryFilter: {
                        field: fs(t.field),
                        op: "IS_NOT_NULL"
                    }
                };
            }
            return {
                fieldFilter: {
                    field: fs(t.field),
                    op: _s(t.op),
                    value: t.value
                }
            };
        }(t)));
        if (1 === e.length) return e[0];
        return {
            compositeFilter: {
                op: "AND",
                filters: e
            }
        };
    }(e.filters);
    i && (n.structuredQuery.where = i);
    const r = function(t) {
        if (0 === t.length) return;
        return t.map((t => 
        // visible for testing
        function(t) {
            return {
                field: fs(t.field),
                direction: ls(t.dir)
            };
        }(t)));
    }(e.orderBy);
    r && (n.structuredQuery.orderBy = r);
    const o = function(t, e) {
        return t.qt || ft(e) ? e : {
            value: e
        };
    }
    /**
 * Returns a number (or null) from a google.protobuf.Int32Value proto.
 */ (t, e.limit);
    return null !== o && (n.structuredQuery.limit = o), e.startAt && (n.structuredQuery.startAt = us(e.startAt)), 
    e.endAt && (n.structuredQuery.endAt = us(e.endAt)), n;
}

function os(t) {
    let e = zn(t.parent);
    const n = t.structuredQuery, s = n.from ? n.from.length : 0;
    let i = null;
    if (s > 0) {
        p(1 === s);
        const t = n.from[0];
        t.allDescendants ? i = t.collectionId : e = e.child(t.collectionId);
    }
    let r = [];
    n.where && (r = as(n.where));
    let o = [];
    n.orderBy && (o = n.orderBy.map((t => function(t) {
        return new te(ds(t.field), 
        // visible for testing
        function(t) {
            switch (t) {
              case "ASCENDING":
                return "asc" /* ASCENDING */;

              case "DESCENDING":
                return "desc" /* DESCENDING */;

              default:
                return;
            }
        }
        // visible for testing
        (t.direction));
    }(t))));
    let c = null;
    n.limit && (c = function(t) {
        let e;
        return e = "object" == typeof t ? t.value : t, ft(e) ? null : e;
    }(n.limit));
    let a = null;
    n.startAt && (a = hs(n.startAt));
    let u = null;
    return n.endAt && (u = hs(n.endAt)), re(e, i, o, r, c, "F" /* First */ , a, u);
}

function cs(t, e) {
    const n = function(t, e) {
        switch (e) {
          case 0 /* Listen */ :
            return null;

          case 1 /* ExistenceFilterMismatch */ :
            return "existence-filter-mismatch";

          case 2 /* LimboResolution */ :
            return "limbo-document";

          default:
            return V();
        }
    }(0, e.kt);
    return null == n ? null : {
        "goog-listen-tags": n
    };
}

function as(t) {
    return t ? void 0 !== t.unaryFilter ? [ Es(t) ] : void 0 !== t.fieldFilter ? [ ws(t) ] : void 0 !== t.compositeFilter ? t.compositeFilter.filters.map((t => as(t))).reduce(((t, e) => t.concat(e))) : V() : [];
}

function us(t) {
    return {
        before: t.before,
        values: t.position
    };
}

function hs(t) {
    const e = !!t.before, n = t.values || [];
    return new Xt(n, e);
}

// visible for testing
function ls(t) {
    return kn[t];
}

function _s(t) {
    return Mn[t];
}

function fs(t) {
    return {
        fieldPath: t.ot()
    };
}

function ds(t) {
    return tt._t(t.fieldPath);
}

function ws(t) {
    return Ut.create(ds(t.fieldFilter.field), function(t) {
        switch (t) {
          case "EQUAL":
            return "==" /* EQUAL */;

          case "NOT_EQUAL":
            return "!=" /* NOT_EQUAL */;

          case "GREATER_THAN":
            return ">" /* GREATER_THAN */;

          case "GREATER_THAN_OR_EQUAL":
            return ">=" /* GREATER_THAN_OR_EQUAL */;

          case "LESS_THAN":
            return "<" /* LESS_THAN */;

          case "LESS_THAN_OR_EQUAL":
            return "<=" /* LESS_THAN_OR_EQUAL */;

          case "ARRAY_CONTAINS":
            return "array-contains" /* ARRAY_CONTAINS */;

          case "IN":
            return "in" /* IN */;

          case "NOT_IN":
            return "not-in" /* NOT_IN */;

          case "ARRAY_CONTAINS_ANY":
            return "array-contains-any" /* ARRAY_CONTAINS_ANY */;

          case "OPERATOR_UNSPECIFIED":
          default:
            return V();
        }
    }(t.fieldFilter.op), t.fieldFilter.value);
}

function Es(t) {
    switch (t.unaryFilter.op) {
      case "IS_NAN":
        const e = ds(t.unaryFilter.field);
        return Ut.create(e, "==" /* EQUAL */ , {
            doubleValue: NaN
        });

      case "IS_NULL":
        const n = ds(t.unaryFilter.field);
        return Ut.create(n, "==" /* EQUAL */ , {
            nullValue: "NULL_VALUE"
        });

      case "IS_NOT_NAN":
        const s = ds(t.unaryFilter.field);
        return Ut.create(s, "!=" /* NOT_EQUAL */ , {
            doubleValue: NaN
        });

      case "IS_NOT_NULL":
        const i = ds(t.unaryFilter.field);
        return Ut.create(i, "!=" /* NOT_EQUAL */ , {
            nullValue: "NULL_VALUE"
        });

      case "OPERATOR_UNSPECIFIED":
      default:
        return V();
    }
}

function Ts(t) {
    const e = [];
    return t.fields.forEach((t => e.push(t.ot()))), {
        fieldPaths: e
    };
}

function Is(t) {
    // Resource names have at least 4 components (project ID, database ID)
    return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class ms {
    constructor() {
        this.promise = new Promise(((t, e) => {
            this.resolve = t, this.reject = e;
        }));
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * PersistencePromise is essentially a re-implementation of Promise except
 * it has a .next() method instead of .then() and .next() and .catch() callbacks
 * are executed synchronously when a PersistencePromise resolves rather than
 * asynchronously (Promise implementations use setImmediate() or similar).
 *
 * This is necessary to interoperate with IndexedDB which will automatically
 * commit transactions if control is returned to the event loop without
 * synchronously initiating another operation on the transaction.
 *
 * NOTE: .then() and .catch() only allow a single consumer, unlike normal
 * Promises.
 */ class As {
    constructor(t) {
        // NOTE: next/catchCallback will always point to our own wrapper functions,
        // not the user's raw next() or catch() callbacks.
        this.Cn = null, this.xn = null, 
        // When the operation resolves, we'll set result or error and mark isDone.
        this.result = void 0, this.error = void 0, this.Nn = !1, 
        // Set to true when .then() or .catch() are called and prevents additional
        // chaining.
        this.On = !1, t((t => {
            this.Nn = !0, this.result = t, this.Cn && 
            // value should be defined unless T is Void, but we can't express
            // that in the type system.
            this.Cn(t);
        }), (t => {
            this.Nn = !0, this.error = t, this.xn && this.xn(t);
        }));
    }
    catch(t) {
        return this.next(void 0, t);
    }
    next(t, e) {
        return this.On && V(), this.On = !0, this.Nn ? this.error ? this.Fn(e, this.error) : this.kn(t, this.result) : new As(((n, s) => {
            this.Cn = e => {
                this.kn(t, e).next(n, s);
            }, this.xn = t => {
                this.Fn(e, t).next(n, s);
            };
        }));
    }
    Mn() {
        return new Promise(((t, e) => {
            this.next(t, e);
        }));
    }
    Ln(t) {
        try {
            const e = t();
            return e instanceof As ? e : As.resolve(e);
        } catch (t) {
            return As.reject(t);
        }
    }
    kn(t, e) {
        return t ? this.Ln((() => t(e))) : As.resolve(e);
    }
    Fn(t, e) {
        return t ? this.Ln((() => t(e))) : As.reject(e);
    }
    static resolve(t) {
        return new As(((e, n) => {
            e(t);
        }));
    }
    static reject(t) {
        return new As(((e, n) => {
            n(t);
        }));
    }
    static $n(
    // Accept all Promise types in waitFor().
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    t) {
        return new As(((e, n) => {
            let s = 0, i = 0, r = !1;
            t.forEach((t => {
                ++s, t.next((() => {
                    ++i, r && i === s && e();
                }), (t => n(t)));
            })), r = !0, i === s && e();
        }));
    }
    /**
     * Given an array of predicate functions that asynchronously evaluate to a
     * boolean, implements a short-circuiting `or` between the results. Predicates
     * will be evaluated until one of them returns `true`, then stop. The final
     * result will be whether any of them returned `true`.
     */    static Bn(t) {
        let e = As.resolve(!1);
        for (const n of t) e = e.next((t => t ? As.resolve(t) : n()));
        return e;
    }
    static forEach(t, e) {
        const n = [];
        return t.forEach(((t, s) => {
            n.push(e.call(this, t, s));
        })), this.$n(n);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// References to `window` are guarded by SimpleDb.isAvailable()
/* eslint-disable no-restricted-globals */
/**
 * Wraps an IDBTransaction and exposes a store() method to get a handle to a
 * specific object store.
 */
class Rs {
    constructor(t, e) {
        this.action = t, this.transaction = e, this.aborted = !1, 
        /**
         * A promise that resolves with the result of the IndexedDb transaction.
         */
        this.qn = new ms, this.transaction.oncomplete = () => {
            this.qn.resolve();
        }, this.transaction.onabort = () => {
            e.error ? this.qn.reject(new gs(t, e.error)) : this.qn.resolve();
        }, this.transaction.onerror = e => {
            const n = Ss(e.target.error);
            this.qn.reject(new gs(t, n));
        };
    }
    static open(t, e, n, s) {
        try {
            return new Rs(e, t.transaction(s, n));
        } catch (t) {
            throw new gs(e, t);
        }
    }
    get Un() {
        return this.qn.promise;
    }
    abort(t) {
        t && this.qn.reject(t), this.aborted || (R("SimpleDb", "Aborting transaction:", t ? t.message : "Client-initiated abort"), 
        this.aborted = !0, this.transaction.abort());
    }
    /**
     * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All
     * operations performed on the SimpleDbStore happen within the context of this
     * transaction and it cannot be used anymore once the transaction is
     * completed.
     *
     * Note that we can't actually enforce that the KeyType and ValueType are
     * correct, but they allow type safety through the rest of the consuming code.
     */    store(t) {
        const e = this.transaction.objectStore(t);
        return new ps(e);
    }
}

/**
 * Provides a wrapper around IndexedDb with a simplified interface that uses
 * Promise-like return values to chain operations. Real promises cannot be used
 * since .then() continuations are executed asynchronously (e.g. via
 * .setImmediate), which would cause IndexedDB to end the transaction.
 * See PersistencePromise for more details.
 */ class Ps {
    /*
     * Creates a new SimpleDb wrapper for IndexedDb database `name`.
     *
     * Note that `version` must not be a downgrade. IndexedDB does not support
     * downgrading the schema version. We currently do not support any way to do
     * versioning outside of IndexedDB's versioning mechanism, as only
     * version-upgrade transactions are allowed to do things like create
     * objectstores.
     */
    constructor(t, n, s) {
        this.name = t, this.version = n, this.Qn = s;
        // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the
        // bug we're checking for should exist in iOS >= 12.2 and < 13, but for
        // whatever reason it's much harder to hit after 12.2 so we only proactively
        // log on 12.2.
        12.2 === Ps.Kn(e()) && P("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.");
    }
    /** Deletes the specified database. */    static delete(t) {
        return R("SimpleDb", "Removing database:", t), bs(window.indexedDB.deleteDatabase(t)).Mn();
    }
    /** Returns true if IndexedDB is available in the current environment. */    static jn() {
        if ("undefined" == typeof indexedDB) return !1;
        if (Ps.Wn()) return !0;
        // We extensively use indexed array values and compound keys,
        // which IE and Edge do not support. However, they still have indexedDB
        // defined on the window, so we need to check for them here and make sure
        // to return that persistence is not enabled for those browsers.
        // For tracking support of this feature, see here:
        // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/
        // Check the UA string to find out the browser.
                const t = e(), n = Ps.Kn(t), s = 0 < n && n < 10, i = Ps.Gn(t), r = 0 < i && i < 4.5;
        // IE 10
        // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
        // IE 11
        // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
        // Edge
        // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,
        // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
        // iOS Safari: Disable for users running iOS version < 10.
                return !(t.indexOf("MSIE ") > 0 || t.indexOf("Trident/") > 0 || t.indexOf("Edge/") > 0 || s || r);
    }
    /**
     * Returns true if the backing IndexedDB store is the Node IndexedDBShim
     * (see https://github.com/axemclion/IndexedDBShim).
     */    static Wn() {
        var t;
        return "undefined" != typeof process && "YES" === (null === (t = process.env) || void 0 === t ? void 0 : t.zn);
    }
    /** Helper to get a typed SimpleDbStore from a transaction. */    static Hn(t, e) {
        return t.store(e);
    }
    // visible for testing
    /** Parse User Agent to determine iOS version. Returns -1 if not found. */
    static Kn(t) {
        const e = t.match(/i(?:phone|pad|pod) os ([\d_]+)/i), n = e ? e[1].split("_").slice(0, 2).join(".") : "-1";
        return Number(n);
    }
    // visible for testing
    /** Parse User Agent to determine Android version. Returns -1 if not found. */
    static Gn(t) {
        const e = t.match(/Android ([\d.]+)/i), n = e ? e[1].split(".").slice(0, 2).join(".") : "-1";
        return Number(n);
    }
    /**
     * Opens the specified database, creating or upgrading it if necessary.
     */    async Jn(t) {
        return this.db || (R("SimpleDb", "Opening database:", this.name), this.db = await new Promise(((e, n) => {
            // TODO(mikelehen): Investigate browser compatibility.
            // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
            // suggests IE9 and older WebKit browsers handle upgrade
            // differently. They expect setVersion, as described here:
            // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion
            const s = indexedDB.open(this.name, this.version);
            s.onsuccess = t => {
                const n = t.target.result;
                e(n);
            }, s.onblocked = () => {
                n(new gs(t, "Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."));
            }, s.onerror = e => {
                const s = e.target.error;
                "VersionError" === s.name ? n(new F(O.FAILED_PRECONDITION, "A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")) : n(new gs(t, s));
            }, s.onupgradeneeded = t => {
                R("SimpleDb", 'Database "' + this.name + '" requires upgrade from version:', t.oldVersion);
                const e = t.target.result;
                this.Qn.Yn(e, s.transaction, t.oldVersion, this.version).next((() => {
                    R("SimpleDb", "Database upgrade to version " + this.version + " complete");
                }));
            };
        }))), this.Xn && (this.db.onversionchange = t => this.Xn(t)), this.db;
    }
    Zn(t) {
        this.Xn = t, this.db && (this.db.onversionchange = e => t(e));
    }
    async runTransaction(t, e, n, s) {
        const i = "readonly" === e;
        let r = 0;
        for (;;) {
            ++r;
            try {
                this.db = await this.Jn(t);
                const e = Rs.open(this.db, t, i ? "readonly" : "readwrite", n), r = s(e).catch((t => (
                // Abort the transaction if there was an error.
                e.abort(t), As.reject(t)))).Mn();
                // As noted above, errors are propagated by aborting the transaction. So
                // we swallow any error here to avoid the browser logging it as unhandled.
                return r.catch((() => {})), 
                // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to
                // fire), but still return the original transactionFnResult back to the
                // caller.
                await e.Un, r;
            } catch (t) {
                // TODO(schmidt-sebastian): We could probably be smarter about this and
                // not retry exceptions that are likely unrecoverable (such as quota
                // exceeded errors).
                // Note: We cannot use an instanceof check for FirestoreException, since the
                // exception is wrapped in a generic error by our async/await handling.
                const e = "FirebaseError" !== t.name && r < 3;
                if (R("SimpleDb", "Transaction failed with error:", t.message, "Retrying:", e), 
                this.close(), !e) return Promise.reject(t);
            }
        }
    }
    close() {
        this.db && this.db.close(), this.db = void 0;
    }
}

/**
 * A controller for iterating over a key range or index. It allows an iterate
 * callback to delete the currently-referenced object, or jump to a new key
 * within the key range or index.
 */ class ys {
    constructor(t) {
        this.ts = t, this.es = !1, this.ns = null;
    }
    get Nn() {
        return this.es;
    }
    get ss() {
        return this.ns;
    }
    set cursor(t) {
        this.ts = t;
    }
    /**
     * This function can be called to stop iteration at any point.
     */    done() {
        this.es = !0;
    }
    /**
     * This function can be called to skip to that next key, which could be
     * an index or a primary key.
     */    rs(t) {
        this.ns = t;
    }
    /**
     * Delete the current cursor value from the object store.
     *
     * NOTE: You CANNOT do this with a keysOnly query.
     */    delete() {
        return bs(this.ts.delete());
    }
}

/** An error that wraps exceptions that thrown during IndexedDB execution. */ class gs extends F {
    constructor(t, e) {
        super(O.UNAVAILABLE, `IndexedDB transaction '${t}' failed: ${e}`), this.name = "IndexedDbTransactionError";
    }
}

/** Verifies whether `e` is an IndexedDbTransactionError. */ function Vs(t) {
    // Use name equality, as instanceof checks on errors don't work with errors
    // that wrap other errors.
    return "IndexedDbTransactionError" === t.name;
}

/**
 * A wrapper around an IDBObjectStore providing an API that:
 *
 * 1) Has generic KeyType / ValueType parameters to provide strongly-typed
 * methods for acting against the object store.
 * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every
 * method return a PersistencePromise instead.
 * 3) Provides a higher-level API to avoid needing to do excessive wrapping of
 * intermediate IndexedDB types (IDBCursorWithValue, etc.)
 */ class ps {
    constructor(t) {
        this.store = t;
    }
    put(t, e) {
        let n;
        return void 0 !== e ? (R("SimpleDb", "PUT", this.store.name, t, e), n = this.store.put(e, t)) : (R("SimpleDb", "PUT", this.store.name, "<auto-key>", t), 
        n = this.store.put(t)), bs(n);
    }
    /**
     * Adds a new value into an Object Store and returns the new key. Similar to
     * IndexedDb's `add()`, this method will fail on primary key collisions.
     *
     * @param value - The object to write.
     * @returns The key of the value to add.
     */    add(t) {
        R("SimpleDb", "ADD", this.store.name, t, t);
        return bs(this.store.add(t));
    }
    /**
     * Gets the object with the specified key from the specified store, or null
     * if no object exists with the specified key.
     *
     * @key The key of the object to get.
     * @returns The object with the specified key or null if no object exists.
     */    get(t) {
        // We're doing an unsafe cast to ValueType.
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        return bs(this.store.get(t)).next((e => (
        // Normalize nonexistence to null.
        void 0 === e && (e = null), R("SimpleDb", "GET", this.store.name, t, e), e)));
    }
    delete(t) {
        R("SimpleDb", "DELETE", this.store.name, t);
        return bs(this.store.delete(t));
    }
    /**
     * If we ever need more of the count variants, we can add overloads. For now,
     * all we need is to count everything in a store.
     *
     * Returns the number of rows in the store.
     */    count() {
        R("SimpleDb", "COUNT", this.store.name);
        return bs(this.store.count());
    }
    os(t, e) {
        const n = this.cursor(this.options(t, e)), s = [];
        return this.cs(n, ((t, e) => {
            s.push(e);
        })).next((() => s));
    }
    us(t, e) {
        R("SimpleDb", "DELETE ALL", this.store.name);
        const n = this.options(t, e);
        n.hs = !1;
        const s = this.cursor(n);
        return this.cs(s, ((t, e, n) => n.delete()));
    }
    ls(t, e) {
        let n;
        e ? n = t : (n = {}, e = t);
        const s = this.cursor(n);
        return this.cs(s, e);
    }
    /**
     * Iterates over a store, but waits for the given callback to complete for
     * each entry before iterating the next entry. This allows the callback to do
     * asynchronous work to determine if this iteration should continue.
     *
     * The provided callback should return `true` to continue iteration, and
     * `false` otherwise.
     */    _s(t) {
        const e = this.cursor({});
        return new As(((n, s) => {
            e.onerror = t => {
                const e = Ss(t.target.error);
                s(e);
            }, e.onsuccess = e => {
                const s = e.target.result;
                s ? t(s.primaryKey, s.value).next((t => {
                    t ? s.continue() : n();
                })) : n();
            };
        }));
    }
    cs(t, e) {
        const n = [];
        return new As(((s, i) => {
            t.onerror = t => {
                i(t.target.error);
            }, t.onsuccess = t => {
                const i = t.target.result;
                if (!i) return void s();
                const r = new ys(i), o = e(i.primaryKey, i.value, r);
                if (o instanceof As) {
                    const t = o.catch((t => (r.done(), As.reject(t))));
                    n.push(t);
                }
                r.Nn ? s() : null === r.ss ? i.continue() : i.continue(r.ss);
            };
        })).next((() => As.$n(n)));
    }
    options(t, e) {
        let n = void 0;
        return void 0 !== t && ("string" == typeof t ? n = t : e = t), {
            index: n,
            range: e
        };
    }
    cursor(t) {
        let e = "next";
        if (t.reverse && (e = "prev"), t.index) {
            const n = this.store.index(t.index);
            return t.hs ? n.openKeyCursor(t.range, e) : n.openCursor(t.range, e);
        }
        return this.store.openCursor(t.range, e);
    }
}

/**
 * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror
 * handlers to resolve / reject the PersistencePromise as appropriate.
 */ function bs(t) {
    return new As(((e, n) => {
        t.onsuccess = t => {
            const n = t.target.result;
            e(n);
        }, t.onerror = t => {
            const e = Ss(t.target.error);
            n(e);
        };
    }));
}

// Guard so we only report the error once.
let vs = !1;

function Ss(t) {
    const n = Ps.Kn(e());
    if (n >= 12.2 && n < 13) {
        const e = "An internal error was encountered in the Indexed Database server";
        if (t.message.indexOf(e) >= 0) {
            // Wrap error in a more descriptive one.
            const t = new F("internal", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${e}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);
            return vs || (vs = !0, 
            // Throw a global exception outside of this promise chain, for the user to
            // potentially catch.
            setTimeout((() => {
                throw t;
            }), 0)), t;
        }
    }
    return t;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Represents an operation scheduled to be run in the future on an AsyncQueue.
 *
 * It is created via DelayedOperation.createAndSchedule().
 *
 * Supports cancellation (via cancel()) and early execution (via skipDelay()).
 *
 * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
 * in newer versions of TypeScript defines `finally`, which is not available in
 * IE.
 */
class Ds {
    constructor(t, e, n, s, i) {
        this.fs = t, this.ds = e, this.ws = n, this.op = s, this.Es = i, this.Ts = new ms, 
        this.then = this.Ts.promise.then.bind(this.Ts.promise), 
        // It's normal for the deferred promise to be canceled (due to cancellation)
        // and so we attach a dummy catch callback to avoid
        // 'UnhandledPromiseRejectionWarning' log spam.
        this.Ts.promise.catch((t => {}));
    }
    /**
     * Creates and returns a DelayedOperation that has been scheduled to be
     * executed on the provided asyncQueue after the provided delayMs.
     *
     * @param asyncQueue - The queue to schedule the operation on.
     * @param id - A Timer ID identifying the type of operation this is.
     * @param delayMs - The delay (ms) before the operation should be scheduled.
     * @param op - The operation to run.
     * @param removalCallback - A callback to be called synchronously once the
     *   operation is executed or canceled, notifying the AsyncQueue to remove it
     *   from its delayedOperations list.
     *   PORTING NOTE: This exists to prevent making removeDelayedOperation() and
     *   the DelayedOperation class public.
     */    static Is(t, e, n, s, i) {
        const r = Date.now() + n, o = new Ds(t, e, r, s, i);
        return o.start(n), o;
    }
    /**
     * Starts the timer. This is called immediately after construction by
     * createAndSchedule().
     */    start(t) {
        this.As = setTimeout((() => this.Rs()), t);
    }
    /**
     * Queues the operation to run immediately (if it hasn't already been run or
     * canceled).
     */    Ps() {
        return this.Rs();
    }
    /**
     * Cancels the operation if it hasn't already been executed or canceled. The
     * promise will be rejected.
     *
     * As long as the operation has not yet been run, calling cancel() provides a
     * guarantee that the operation will not be run.
     */    cancel(t) {
        null !== this.As && (this.clearTimeout(), this.Ts.reject(new F(O.CANCELLED, "Operation cancelled" + (t ? ": " + t : ""))));
    }
    Rs() {
        this.fs.ys((() => null !== this.As ? (this.clearTimeout(), this.op().then((t => this.Ts.resolve(t)))) : Promise.resolve()));
    }
    clearTimeout() {
        null !== this.As && (this.Es(this), clearTimeout(this.As), this.As = null);
    }
}

/**
 * Returns a FirestoreError that can be surfaced to the user if the provided
 * error is an IndexedDbTransactionError. Re-throws the error otherwise.
 */ function Cs(t, e) {
    if (P("AsyncQueue", `${e}: ${t}`), Vs(t)) return new F(O.UNAVAILABLE, `${e}: ${t}`);
    throw t;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const xs = "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";

/**
 * A base class representing a persistence transaction, encapsulating both the
 * transaction's sequence numbers as well as a list of onCommitted listeners.
 *
 * When you call Persistence.runTransaction(), it will create a transaction and
 * pass it to your callback. You then pass it to any method that operates
 * on persistence.
 */ class Ns {
    constructor() {
        this.gs = [];
    }
    Vs(t) {
        this.gs.push(t);
    }
    ps() {
        this.gs.forEach((t => t()));
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Encodes a resource path into a IndexedDb-compatible string form.
 */
function Os(t) {
    let e = "";
    for (let n = 0; n < t.length; n++) e.length > 0 && (e = ks(e)), e = Fs(t.get(n), e);
    return ks(e);
}

/** Encodes a single segment of a resource path into the given result */ function Fs(t, e) {
    let n = e;
    const s = t.length;
    for (let e = 0; e < s; e++) {
        const s = t.charAt(e);
        switch (s) {
          case "\0":
            n += "";
            break;

          case "":
            n += "";
            break;

          default:
            n += s;
        }
    }
    return n;
}

/** Encodes a path separator into the given result */ function ks(t) {
    return t + "";
}

/**
 * Decodes the given IndexedDb-compatible string form of a resource path into
 * a ResourcePath instance. Note that this method is not suitable for use with
 * decoding resource names from the server; those are One Platform format
 * strings.
 */ function Ms(t) {
    // Event the empty path must encode as a path of at least length 2. A path
    // with exactly 2 must be the empty path.
    const e = t.length;
    if (p(e >= 2), 2 === e) return p("" === t.charAt(0) && "" === t.charAt(1)), X.at();
    // Escape characters cannot exist past the second-to-last position in the
    // source value.
        const n = e - 2, s = [];
    let i = "";
    for (let r = 0; r < e; ) {
        // The last two characters of a valid encoded path must be a separator, so
        // there must be an end to this segment.
        const e = t.indexOf("", r);
        (e < 0 || e > n) && V();
        switch (t.charAt(e + 1)) {
          case "":
            const n = t.substring(r, e);
            let o;
            0 === i.length ? 
            // Avoid copying for the common case of a segment that excludes \0
            // and \001
            o = n : (i += n, o = i, i = ""), s.push(o);
            break;

          case "":
            i += t.substring(r, e), i += "\0";
            break;

          case "":
            // The escape character can be used in the output to encode itself.
            i += t.substring(r, e + 1);
            break;

          default:
            V();
        }
        r = e + 2;
    }
    return new X(s);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Schema Version for the Web client:
 * 1.  Initial version including Mutation Queue, Query Cache, and Remote
 *     Document Cache
 * 2.  Used to ensure a targetGlobal object exists and add targetCount to it. No
 *     longer required because migration 3 unconditionally clears it.
 * 3.  Dropped and re-created Query Cache to deal with cache corruption related
 *     to limbo resolution. Addresses
 *     https://github.com/firebase/firebase-ios-sdk/issues/1548
 * 4.  Multi-Tab Support.
 * 5.  Removal of held write acks.
 * 6.  Create document global for tracking document cache size.
 * 7.  Ensure every cached document has a sentinel row with a sequence number.
 * 8.  Add collection-parent index for Collection Group queries.
 * 9.  Change RemoteDocumentChanges store to be keyed by readTime rather than
 *     an auto-incrementing ID. This is required for Index-Free queries.
 * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.
 * 11. Add bundles and named_queries for bundle support.
 */
/**
 * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.
 */
class Ls {
    constructor(t, e) {
        this.seconds = t, this.nanoseconds = e;
    }
}

/**
 * A singleton object to be stored in the 'owner' store in IndexedDb.
 *
 * A given database can have a single primary tab assigned at a given time. That
 * tab must validate that it is still holding the primary lease before every
 * operation that requires locked access. The primary tab should regularly
 * write an updated timestamp to this lease to prevent other tabs from
 * "stealing" the primary lease
 */ class $s {
    constructor(t, 
    /** Whether to allow shared access from multiple tabs. */
    e, n) {
        this.ownerId = t, this.allowTabSynchronization = e, this.leaseTimestampMs = n;
    }
}

/**
 * Name of the IndexedDb object store.
 *
 * Note that the name 'owner' is chosen to ensure backwards compatibility with
 * older clients that only supported single locked access to the persistence
 * layer.
 */ $s.store = "owner", 
/**
 * The key string used for the single object that exists in the
 * DbPrimaryClient store.
 */
$s.key = "owner";

/**
 * An object to be stored in the 'mutationQueues' store in IndexedDb.
 *
 * Each user gets a single queue of MutationBatches to apply to the server.
 * DbMutationQueue tracks the metadata about the queue.
 */
class Bs {
    constructor(
    /**
     * The normalized user ID to which this queue belongs.
     */
    t, 
    /**
     * An identifier for the highest numbered batch that has been acknowledged
     * by the server. All MutationBatches in this queue with batchIds less
     * than or equal to this value are considered to have been acknowledged by
     * the server.
     *
     * NOTE: this is deprecated and no longer used by the code.
     */
    e, 
    /**
     * A stream token that was previously sent by the server.
     *
     * See StreamingWriteRequest in datastore.proto for more details about
     * usage.
     *
     * After sending this token, earlier tokens may not be used anymore so
     * only a single stream token is retained.
     *
     * NOTE: this is deprecated and no longer used by the code.
     */
    n) {
        this.userId = t, this.lastAcknowledgedBatchId = e, this.lastStreamToken = n;
    }
}

/** Name of the IndexedDb object store.  */ Bs.store = "mutationQueues", 
/** Keys are automatically assigned via the userId property. */
Bs.keyPath = "userId";

/**
 * An object to be stored in the 'mutations' store in IndexedDb.
 *
 * Represents a batch of user-level mutations intended to be sent to the server
 * in a single write. Each user-level batch gets a separate DbMutationBatch
 * with a new batchId.
 */
class qs {
    constructor(
    /**
     * The normalized user ID to which this batch belongs.
     */
    t, 
    /**
     * An identifier for this batch, allocated using an auto-generated key.
     */
    e, 
    /**
     * The local write time of the batch, stored as milliseconds since the
     * epoch.
     */
    n, 
    /**
     * A list of "mutations" that represent a partial base state from when this
     * write batch was initially created. During local application of the write
     * batch, these baseMutations are applied prior to the real writes in order
     * to override certain document fields from the remote document cache. This
     * is necessary in the case of non-idempotent writes (e.g. `increment()`
     * transforms) to make sure that the local view of the modified documents
     * doesn't flicker if the remote document cache receives the result of the
     * non-idempotent write before the write is removed from the queue.
     *
     * These mutations are never sent to the backend.
     */
    s, 
    /**
     * A list of mutations to apply. All mutations will be applied atomically.
     *
     * Mutations are serialized via toMutation().
     */
    i) {
        this.userId = t, this.batchId = e, this.localWriteTimeMs = n, this.baseMutations = s, 
        this.mutations = i;
    }
}

/** Name of the IndexedDb object store.  */ qs.store = "mutations", 
/** Keys are automatically assigned via the userId, batchId properties. */
qs.keyPath = "batchId", 
/** The index name for lookup of mutations by user. */
qs.userMutationsIndex = "userMutationsIndex", 
/** The user mutations index is keyed by [userId, batchId] pairs. */
qs.userMutationsKeyPath = [ "userId", "batchId" ];

/**
 * An object to be stored in the 'documentMutations' store in IndexedDb.
 *
 * A manually maintained index of all the mutation batches that affect a given
 * document key. The rows in this table are references based on the contents of
 * DbMutationBatch.mutations.
 */
class Us {
    constructor() {}
    /**
     * Creates a [userId] key for use in the DbDocumentMutations index to iterate
     * over all of a user's document mutations.
     */    static prefixForUser(t) {
        return [ t ];
    }
    /**
     * Creates a [userId, encodedPath] key for use in the DbDocumentMutations
     * index to iterate over all at document mutations for a given path or lower.
     */    static prefixForPath(t, e) {
        return [ t, Os(e) ];
    }
    /**
     * Creates a full index key of [userId, encodedPath, batchId] for inserting
     * and deleting into the DbDocumentMutations index.
     */    static key(t, e, n) {
        return [ t, Os(e), n ];
    }
}

Us.store = "documentMutations", 
/**
 * Because we store all the useful information for this store in the key,
 * there is no useful information to store as the value. The raw (unencoded)
 * path cannot be stored because IndexedDb doesn't store prototype
 * information.
 */
Us.PLACEHOLDER = new Us;

/**
 * Represents the known absence of a document at a particular version.
 * Stored in IndexedDb as part of a DbRemoteDocument object.
 */
class Qs {
    constructor(t, e) {
        this.path = t, this.readTime = e;
    }
}

/**
 * Represents a document that is known to exist but whose data is unknown.
 * Stored in IndexedDb as part of a DbRemoteDocument object.
 */ class Ks {
    constructor(t, e) {
        this.path = t, this.version = e;
    }
}

/**
 * An object to be stored in the 'remoteDocuments' store in IndexedDb.
 * It represents either:
 *
 * - A complete document.
 * - A "no document" representing a document that is known not to exist (at
 * some version).
 * - An "unknown document" representing a document that is known to exist (at
 * some version) but whose contents are unknown.
 *
 * Note: This is the persisted equivalent of a MaybeDocument and could perhaps
 * be made more general if necessary.
 */ class js {
    // TODO: We are currently storing full document keys almost three times
    // (once as part of the primary key, once - partly - as `parentPath` and once
    // inside the encoded documents). During our next migration, we should
    // rewrite the primary key as parentPath + document ID which would allow us
    // to drop one value.
    constructor(
    /**
     * Set to an instance of DbUnknownDocument if the data for a document is
     * not known, but it is known that a document exists at the specified
     * version (e.g. it had a successful update applied to it)
     */
    t, 
    /**
     * Set to an instance of a DbNoDocument if it is known that no document
     * exists.
     */
    e, 
    /**
     * Set to an instance of a Document if there's a cached version of the
     * document.
     */
    n, 
    /**
     * Documents that were written to the remote document store based on
     * a write acknowledgment are marked with `hasCommittedMutations`. These
     * documents are potentially inconsistent with the backend's copy and use
     * the write's commit version as their document version.
     */
    s, 
    /**
     * When the document was read from the backend. Undefined for data written
     * prior to schema version 9.
     */
    i, 
    /**
     * The path of the collection this document is part of. Undefined for data
     * written prior to schema version 9.
     */
    r) {
        this.unknownDocument = t, this.noDocument = e, this.document = n, this.hasCommittedMutations = s, 
        this.readTime = i, this.parentPath = r;
    }
}

js.store = "remoteDocuments", 
/**
 * An index that provides access to all entries sorted by read time (which
 * corresponds to the last modification time of each row).
 *
 * This index is used to provide a changelog for Multi-Tab.
 */
js.readTimeIndex = "readTimeIndex", js.readTimeIndexPath = "readTime", 
/**
 * An index that provides access to documents in a collection sorted by read
 * time.
 *
 * This index is used to allow the RemoteDocumentCache to fetch newly changed
 * documents in a collection.
 */
js.collectionReadTimeIndex = "collectionReadTimeIndex", js.collectionReadTimeIndexPath = [ "parentPath", "readTime" ];

/**
 * Contains a single entry that has metadata about the remote document cache.
 */
class Ws {
    /**
     * @param byteSize - Approximately the total size in bytes of all the
     * documents in the document cache.
     */
    constructor(t) {
        this.byteSize = t;
    }
}

Ws.store = "remoteDocumentGlobal", Ws.key = "remoteDocumentGlobalKey";

/**
 * An object to be stored in the 'targets' store in IndexedDb.
 *
 * This is based on and should be kept in sync with the proto used in the iOS
 * client.
 *
 * Each query the client listens to against the server is tracked on disk so
 * that the query can be efficiently resumed on restart.
 */
class Gs {
    constructor(
    /**
     * An auto-generated sequential numeric identifier for the query.
     *
     * Queries are stored using their canonicalId as the key, but these
     * canonicalIds can be quite long so we additionally assign a unique
     * queryId which can be used by referenced data structures (e.g.
     * indexes) to minimize the on-disk cost.
     */
    t, 
    /**
     * The canonical string representing this query. This is not unique.
     */
    e, 
    /**
     * The last readTime received from the Watch Service for this query.
     *
     * This is the same value as TargetChange.read_time in the protos.
     */
    n, 
    /**
     * An opaque, server-assigned token that allows watching a query to be
     * resumed after disconnecting without retransmitting all the data
     * that matches the query. The resume token essentially identifies a
     * point in time from which the server should resume sending results.
     *
     * This is related to the snapshotVersion in that the resumeToken
     * effectively also encodes that value, but the resumeToken is opaque
     * and sometimes encodes additional information.
     *
     * A consequence of this is that the resumeToken should be used when
     * asking the server to reason about where this client is in the watch
     * stream, but the client should use the snapshotVersion for its own
     * purposes.
     *
     * This is the same value as TargetChange.resume_token in the protos.
     */
    s, 
    /**
     * A sequence number representing the last time this query was
     * listened to, used for garbage collection purposes.
     *
     * Conventionally this would be a timestamp value, but device-local
     * clocks are unreliable and they must be able to create new listens
     * even while disconnected. Instead this should be a monotonically
     * increasing number that's incremented on each listen call.
     *
     * This is different from the queryId since the queryId is an
     * immutable identifier assigned to the Query on first use while
     * lastListenSequenceNumber is updated every time the query is
     * listened to.
     */
    i, 
    /**
     * Denotes the maximum snapshot version at which the associated query view
     * contained no limbo documents.  Undefined for data written prior to
     * schema version 9.
     */
    r, 
    /**
     * The query for this target.
     *
     * Because canonical ids are not unique we must store the actual query. We
     * use the proto to have an object we can persist without having to
     * duplicate translation logic to and from a `Query` object.
     */
    o) {
        this.targetId = t, this.canonicalId = e, this.readTime = n, this.resumeToken = s, 
        this.lastListenSequenceNumber = i, this.lastLimboFreeSnapshotVersion = r, this.query = o;
    }
}

Gs.store = "targets", 
/** Keys are automatically assigned via the targetId property. */
Gs.keyPath = "targetId", 
/** The name of the queryTargets index. */
Gs.queryTargetsIndexName = "queryTargetsIndex", 
/**
 * The index of all canonicalIds to the targets that they match. This is not
 * a unique mapping because canonicalId does not promise a unique name for all
 * possible queries, so we append the targetId to make the mapping unique.
 */
Gs.queryTargetsKeyPath = [ "canonicalId", "targetId" ];

/**
 * An object representing an association between a target and a document, or a
 * sentinel row marking the last sequence number at which a document was used.
 * Each document cached must have a corresponding sentinel row before lru
 * garbage collection is enabled.
 *
 * The target associations and sentinel rows are co-located so that orphaned
 * documents and their sequence numbers can be identified efficiently via a scan
 * of this store.
 */
class zs {
    constructor(
    /**
     * The targetId identifying a target or 0 for a sentinel row.
     */
    t, 
    /**
     * The path to the document, as encoded in the key.
     */
    e, 
    /**
     * If this is a sentinel row, this should be the sequence number of the last
     * time the document specified by `path` was used. Otherwise, it should be
     * `undefined`.
     */
    n) {
        this.targetId = t, this.path = e, this.sequenceNumber = n;
    }
}

/** Name of the IndexedDb object store.  */ zs.store = "targetDocuments", 
/** Keys are automatically assigned via the targetId, path properties. */
zs.keyPath = [ "targetId", "path" ], 
/** The index name for the reverse index. */
zs.documentTargetsIndex = "documentTargetsIndex", 
/** We also need to create the reverse index for these properties. */
zs.documentTargetsKeyPath = [ "path", "targetId" ];

/**
 * A record of global state tracked across all Targets, tracked separately
 * to avoid the need for extra indexes.
 *
 * This should be kept in-sync with the proto used in the iOS client.
 */
class Hs {
    constructor(
    /**
     * The highest numbered target id across all targets.
     *
     * See DbTarget.targetId.
     */
    t, 
    /**
     * The highest numbered lastListenSequenceNumber across all targets.
     *
     * See DbTarget.lastListenSequenceNumber.
     */
    e, 
    /**
     * A global snapshot version representing the last consistent snapshot we
     * received from the backend. This is monotonically increasing and any
     * snapshots received from the backend prior to this version (e.g. for
     * targets resumed with a resumeToken) should be suppressed (buffered)
     * until the backend has caught up to this snapshot version again. This
     * prevents our cache from ever going backwards in time.
     */
    n, 
    /**
     * The number of targets persisted.
     */
    s) {
        this.highestTargetId = t, this.highestListenSequenceNumber = e, this.lastRemoteSnapshotVersion = n, 
        this.targetCount = s;
    }
}

/**
 * The key string used for the single object that exists in the
 * DbTargetGlobal store.
 */ Hs.key = "targetGlobalKey", Hs.store = "targetGlobal";

/**
 * An object representing an association between a Collection id (e.g. 'messages')
 * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection.
 * This is used to efficiently find all collections to query when performing
 * a Collection Group query.
 */
class Js {
    constructor(
    /**
     * The collectionId (e.g. 'messages')
     */
    t, 
    /**
     * The path to the parent (either a document location or an empty path for
     * a root-level collection).
     */
    e) {
        this.collectionId = t, this.parent = e;
    }
}

/** Name of the IndexedDb object store. */ Js.store = "collectionParents", 
/** Keys are automatically assigned via the collectionId, parent properties. */
Js.keyPath = [ "collectionId", "parent" ];

/**
 * A record of the metadata state of each client.
 *
 * PORTING NOTE: This is used to synchronize multi-tab state and does not need
 * to be ported to iOS or Android.
 */
class Ys {
    constructor(
    // Note: Previous schema versions included a field
    // "lastProcessedDocumentChangeId". Don't use anymore.
    /** The auto-generated client id assigned at client startup. */
    t, 
    /** The last time this state was updated. */
    e, 
    /** Whether the client's network connection is enabled. */
    n, 
    /** Whether this client is running in a foreground tab. */
    s) {
        this.clientId = t, this.updateTimeMs = e, this.networkEnabled = n, this.inForeground = s;
    }
}

/** Name of the IndexedDb object store. */ Ys.store = "clientMetadata", 
/** Keys are automatically assigned via the clientId properties. */
Ys.keyPath = "clientId";

/**
 * A object representing a bundle loaded by the SDK.
 */
class Xs {
    constructor(
    /** The ID of the loaded bundle. */
    t, 
    /** The create time of the loaded bundle. */
    e, 
    /** The schema version of the loaded bundle. */
    n) {
        this.bundleId = t, this.createTime = e, this.version = n;
    }
}

/** Name of the IndexedDb object store. */ Xs.store = "bundles", Xs.keyPath = "bundleId";

/**
 * A object representing a named query loaded by the SDK via a bundle.
 */
class Zs {
    constructor(
    /** The name of the query. */
    t, 
    /** The read time of the results saved in the bundle from the named query. */
    e, 
    /** The query saved in the bundle. */
    n) {
        this.name = t, this.readTime = e, this.bundledQuery = n;
    }
}

/** Name of the IndexedDb object store. */ Zs.store = "namedQueries", Zs.keyPath = "name";

// Visible for testing
const ti = [ ...[ ...[ ...[ ...[ Bs.store, qs.store, Us.store, js.store, Gs.store, $s.store, Hs.store, zs.store ], Ys.store ], Ws.store ], Js.store ], Xs.store, Zs.store ];

// V2 is no longer usable (see comment at top of file)
// Visible for testing
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class ei extends Ns {
    constructor(t, e) {
        super(), this.bs = t, this.vs = e;
    }
}

function ni(t, e) {
    const n = b(t);
    return Ps.Hn(n.bs, e);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A batch of mutations that will be sent as one unit to the backend.
 */ class si {
    /**
     * @param batchId - The unique ID of this mutation batch.
     * @param localWriteTime - The original write time of this mutation.
     * @param baseMutations - Mutations that are used to populate the base
     * values when this mutation is applied locally. This can be used to locally
     * overwrite values that are persisted in the remote document cache. Base
     * mutations are never sent to the backend.
     * @param mutations - The user-provided mutations in this mutation batch.
     * User-provided mutations are applied both locally and remotely on the
     * backend.
     */
    constructor(t, e, n, s) {
        this.batchId = t, this.Ss = e, this.baseMutations = n, this.mutations = s;
    }
    /**
     * Applies all the mutations in this MutationBatch to the specified document
     * to create a new remote document
     *
     * @param docKey - The key of the document to apply mutations to.
     * @param maybeDoc - The document to apply mutations to.
     * @param batchResult - The result of applying the MutationBatch to the
     * backend.
     */    Ds(t, e, n) {
        const s = n.Cs;
        for (let n = 0; n < this.mutations.length; n++) {
            const i = this.mutations[n];
            if (i.key.isEqual(t)) {
                e = Qe(i, e, s[n]);
            }
        }
        return e;
    }
    /**
     * Computes the local view of a document given all the mutations in this
     * batch.
     *
     * @param docKey - The key of the document to apply mutations to.
     * @param maybeDoc - The document to apply mutations to.
     */    xs(t, e) {
        // First, apply the base state. This allows us to apply non-idempotent
        // transform against a consistent set of values.
        for (const n of this.baseMutations) n.key.isEqual(t) && (e = Ke(n, e, 0, this.Ss));
        // Second, apply all user-provided mutations.
        for (const n of this.mutations) n.key.isEqual(t) && (e = Ke(n, e, 0, this.Ss));
        return e;
    }
    /**
     * Computes the local view for all provided documents given the mutations in
     * this batch.
     */    Ns(t) {
        // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations
        // directly (as done in `applyToLocalView()`), we can reduce the complexity
        // to O(n).
        let e = t;
        return this.mutations.forEach((n => {
            const s = this.xs(n.key, t.get(n.key));
            s && (e = e.Ht(n.key, s));
        })), e;
    }
    keys() {
        return this.mutations.reduce(((t, e) => t.add(e.key)), Rn());
    }
    isEqual(t) {
        return this.batchId === t.batchId && C(this.mutations, t.mutations, ((t, e) => We(t, e))) && C(this.baseMutations, t.baseMutations, ((t, e) => We(t, e)));
    }
}

/** The result of applying a mutation batch to the backend. */ class ii {
    constructor(t, e, n, 
    /**
     * A pre-computed mapping from each mutated document to the resulting
     * version.
     */
    s) {
        this.batch = t, this.Os = e, this.Cs = n, this.Fs = s;
    }
    /**
     * Creates a new MutationBatchResult for the given batch and results. There
     * must be one result for each mutation in the batch. This static factory
     * caches a document=&gt;version mapping (docVersions).
     */    static from(t, e, n) {
        p(t.mutations.length === n.length);
        let s = mn();
        const i = t.mutations;
        for (let t = 0; t < i.length; t++) s = s.Ht(i[t].key, n[t].version);
        return new ii(t, e, n, s);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Serializer for values stored in the LocalStore. */ class ri {
    constructor(t) {
        this.ks = t;
    }
}

/** Decodes a remote document from storage locally to a Document. */ function oi(t, e) {
    if (e.document) return Xn(t.ks, e.document, !!e.hasCommittedMutations);
    if (e.noDocument) {
        const t = et.Tt(e.noDocument.path), n = li(e.noDocument.readTime);
        return new Ot(t, n, {
            hasCommittedMutations: !!e.hasCommittedMutations
        });
    }
    if (e.unknownDocument) {
        const t = et.Tt(e.unknownDocument.path), n = li(e.unknownDocument.version);
        return new Ft(t, n);
    }
    return V();
}

/** Encodes a document for storage locally. */ function ci(t, e, n) {
    const s = ai(n), i = e.key.path.Z().rt();
    if (e instanceof Nt) {
        const n = function(t, e) {
            return {
                name: jn(t, e.key),
                fields: e.vt().mapValue.fields,
                updateTime: $n(t, e.version.G())
            };
        }(t.ks, e), r = e.hasCommittedMutations;
        return new js(
        /* unknownDocument= */ null, 
        /* noDocument= */ null, n, r, s, i);
    }
    if (e instanceof Ot) {
        const t = e.key.path.rt(), n = hi(e.version), r = e.hasCommittedMutations;
        return new js(
        /* unknownDocument= */ null, new Qs(t, n), 
        /* document= */ null, r, s, i);
    }
    if (e instanceof Ft) {
        const t = e.key.path.rt(), n = hi(e.version);
        return new js(new Ks(t, n), 
        /* noDocument= */ null, 
        /* document= */ null, 
        /* hasCommittedMutations= */ !0, s, i);
    }
    return V();
}

function ai(t) {
    const e = t.G();
    return [ e.seconds, e.nanoseconds ];
}

function ui(t) {
    const e = new H(t[0], t[1]);
    return J.j(e);
}

function hi(t) {
    const e = t.G();
    return new Ls(e.seconds, e.nanoseconds);
}

function li(t) {
    const e = new H(t.seconds, t.nanoseconds);
    return J.j(e);
}

/** Encodes a batch of mutations into a DbMutationBatch for local storage. */
/** Decodes a DbMutationBatch into a MutationBatch */
function _i(t, e) {
    const n = (e.baseMutations || []).map((e => ns(t.ks, e)));
    // Squash old transform mutations into existing patch or set mutations.
    // The replacement of representing `transforms` with `update_transforms`
    // on the SDK means that old `transform` mutations stored in IndexedDB need
    // to be updated to `update_transforms`.
    // TODO(b/174608374): Remove this code once we perform a schema migration.
        for (let t = e.mutations.length - 1; t >= 0; --t) {
        const n = e.mutations[t];
        if (void 0 !== (null == n ? void 0 : n.transform)) {
            e.mutations[t - 1].updateTransforms = n.transform.fieldTransforms, e.mutations.splice(t, 1), 
            --t;
        }
    }
    const s = e.mutations.map((e => ns(t.ks, e))), i = H.fromMillis(e.localWriteTimeMs);
    return new si(e.batchId, i, n, s);
}

/** Decodes a DbTarget into TargetData */ function fi(t) {
    const e = li(t.readTime), n = void 0 !== t.lastLimboFreeSnapshotVersion ? li(t.lastLimboFreeSnapshotVersion) : J.min();
    let s;
    var i;
    return void 0 !== t.query.documents ? (p(1 === (i = t.query).documents.length), 
    s = fe(oe(zn(i.documents[0])))) : s = function(t) {
        return fe(os(t));
    }(t.query), new Re(s, t.targetId, 0 /* Listen */ , t.lastListenSequenceNumber, e, n, N.fromBase64String(t.resumeToken));
}

/** Encodes TargetData into a DbTarget for storage locally. */ function di(t, e) {
    const n = hi(e.Mt), s = hi(e.lastLimboFreeSnapshotVersion);
    let i;
    i = qt(e.target) ? is(t.ks, e.target) : rs(t.ks, e.target);
    // We can't store the resumeToken as a ByteString in IndexedDb, so we
    // convert it to a base64 string for storage.
        const r = e.resumeToken.toBase64();
    // lastListenSequenceNumber is always 0 until we do real GC.
        return new Gs(e.targetId, Lt(e.target), n, r, e.sequenceNumber, s, i);
}

/**
 * A helper function for figuring out what kind of query has been stored.
 */
/**
 * Encodes a `BundledQuery` from bundle proto to a Query object.
 *
 * This reconstructs the original query used to build the bundle being loaded,
 * including features exists only in SDKs (for example: limit-to-last).
 */
function wi(t) {
    const e = os({
        parent: t.parent,
        structuredQuery: t.structuredQuery
    });
    return "LAST" === t.limitType ? de(e, e.limit, "L" /* Last */) : e;
}

/** Encodes a NamedQuery proto object to a NamedQuery model object. */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class Ei {
    Ms(t, e) {
        return Ti(t).get(e).next((t => {
            if (t) return {
                id: (e = t).bundleId,
                createTime: li(e.createTime),
                version: e.version
            };
            /** Encodes a DbBundle to a BundleMetadata object. */
            var e;
            /** Encodes a BundleMetadata to a DbBundle. */        }));
    }
    Ls(t, e) {
        return Ti(t).put({
            bundleId: (n = e).id,
            createTime: hi(Un(n.createTime)),
            version: n.version
        });
        var n;
        /** Encodes a DbNamedQuery to a NamedQuery. */    }
    $s(t, e) {
        return Ii(t).get(e).next((t => {
            if (t) return {
                name: (e = t).name,
                query: wi(e.bundledQuery),
                readTime: li(e.readTime)
            };
            var e;
            /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */        }));
    }
    Bs(t, e) {
        return Ii(t).put(function(t) {
            return {
                name: t.name,
                readTime: hi(Un(t.readTime)),
                bundledQuery: t.bundledQuery
            };
        }(e));
    }
}

/**
 * Helper to get a typed SimpleDbStore for the bundles object store.
 */ function Ti(t) {
    return ni(t, Xs.store);
}

/**
 * Helper to get a typed SimpleDbStore for the namedQueries object store.
 */ function Ii(t) {
    return ni(t, Zs.store);
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An in-memory implementation of IndexManager.
 */ class mi {
    constructor() {
        this.qs = new Ai;
    }
    Us(t, e) {
        return this.qs.add(e), As.resolve();
    }
    Qs(t, e) {
        return As.resolve(this.qs.getEntries(e));
    }
}

/**
 * Internal implementation of the collection-parent index exposed by MemoryIndexManager.
 * Also used for in-memory caching by IndexedDbIndexManager and initial index population
 * in indexeddb_schema.ts
 */ class Ai {
    constructor() {
        this.index = {};
    }
    // Returns false if the entry already existed.
    add(t) {
        const e = t.et(), n = t.Z(), s = this.index[e] || new ln(X.J), i = !s.has(n);
        return this.index[e] = s.add(n), i;
    }
    has(t) {
        const e = t.et(), n = t.Z(), s = this.index[e];
        return s && s.has(n);
    }
    getEntries(t) {
        return (this.index[t] || new ln(X.J)).rt();
    }
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A persisted implementation of IndexManager.
 */ class Ri {
    constructor() {
        /**
         * An in-memory copy of the index entries we've already written since the SDK
         * launched. Used to avoid re-writing the same entry repeatedly.
         *
         * This is *NOT* a complete cache of what's in persistence and so can never be used to
         * satisfy reads.
         */
        this.Ks = new Ai;
    }
    /**
     * Adds a new entry to the collection parent index.
     *
     * Repeated calls for the same collectionPath should be avoided within a
     * transaction as IndexedDbIndexManager only caches writes once a transaction
     * has been committed.
     */    Us(t, e) {
        if (!this.Ks.has(e)) {
            const n = e.et(), s = e.Z();
            t.Vs((() => {
                // Add the collection to the in memory cache only if the transaction was
                // successfully committed.
                this.Ks.add(e);
            }));
            const i = {
                collectionId: n,
                parent: Os(s)
            };
            return Pi(t).put(i);
        }
        return As.resolve();
    }
    Qs(t, e) {
        const n = [], s = IDBKeyRange.bound([ e, "" ], [ x(e), "" ], 
        /*lowerOpen=*/ !1, 
        /*upperOpen=*/ !0);
        return Pi(t).os(s).next((t => {
            for (const s of t) {
                // This collectionId guard shouldn't be necessary (and isn't as long
                // as we're running in a real browser), but there's a bug in
                // indexeddbshim that breaks our range in our tests running in node:
                // https://github.com/axemclion/IndexedDBShim/issues/334
                if (s.collectionId !== e) break;
                n.push(Ms(s.parent));
            }
            return n;
        }));
    }
}

/**
 * Helper to get a typed SimpleDbStore for the collectionParents
 * document store.
 */ function Pi(t) {
    return ni(t, Js.store);
}

/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const yi = {
    js: !1,
    Ws: 0,
    Gs: 0,
    zs: 0
};

class gi {
    constructor(
    // When we attempt to collect, we will only do so if the cache size is greater than this
    // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.
    t, 
    // The percentage of sequence numbers that we will attempt to collect
    e, 
    // A cap on the total number of sequence numbers that will be collected. This prevents
    // us from collecting a huge number of sequence numbers if the cache has grown very large.
    n) {
        this.Hs = t, this.Js = e, this.Ys = n;
    }
    static Xs(t) {
        return new gi(t, gi.Zs, gi.ti);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Verifies the error thrown by a LocalStore operation. If a LocalStore
 * operation fails because the primary lease has been taken by another client,
 * we ignore the error (the persistence layer will immediately call
 * `applyPrimaryLease` to propagate the primary state change). All other errors
 * are re-thrown.
 *
 * @param err - An error returned by a LocalStore operation.
 * @returns A Promise that resolves after we recovered, or the original error.
 */
async function Vi(t) {
    if (t.code !== O.FAILED_PRECONDITION || t.message !== xs) throw t;
    R("LocalStore", "Unexpectedly lost primary lease");
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A map implementation that uses objects as keys. Objects must have an
 * associated equals function and must be immutable. Entries in the map are
 * stored together with the key being produced from the mapKeyFn. This map
 * automatically handles collisions of keys.
 */ gi.Zs = 10, gi.ti = 1e3, gi.ei = new gi(41943040, gi.Zs, gi.ti), gi.ni = new gi(-1, 0, 0);

class pi {
    constructor(t, e) {
        this.si = t, this.ii = e, 
        /**
         * The inner map for a key/value pair. Due to the possibility of collisions we
         * keep a list of entries that we do a linear search through to find an actual
         * match. Note that collisions should be rare, so we still expect near
         * constant time lookups in practice.
         */
        this.ri = {};
    }
    /** Get a value for this key, or undefined if it does not exist. */    get(t) {
        const e = this.si(t), n = this.ri[e];
        if (void 0 !== n) for (const [e, s] of n) if (this.ii(e, t)) return s;
    }
    has(t) {
        return void 0 !== this.get(t);
    }
    /** Put this key and value in the map. */    set(t, e) {
        const n = this.si(t), s = this.ri[n];
        if (void 0 !== s) {
            for (let n = 0; n < s.length; n++) if (this.ii(s[n][0], t)) return void (s[n] = [ t, e ]);
            s.push([ t, e ]);
        } else this.ri[n] = [ [ t, e ] ];
    }
    /**
     * Remove this key from the map. Returns a boolean if anything was deleted.
     */    delete(t) {
        const e = this.si(t), n = this.ri[e];
        if (void 0 === n) return !1;
        for (let s = 0; s < n.length; s++) if (this.ii(n[s][0], t)) return 1 === n.length ? delete this.ri[e] : n.splice(s, 1), 
        !0;
        return !1;
    }
    forEach(t) {
        st(this.ri, ((e, n) => {
            for (const [e, s] of n) t(e, s);
        }));
    }
    nt() {
        return it(this.ri);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An in-memory buffer of entries to be written to a RemoteDocumentCache.
 * It can be used to batch up a set of changes to be written to the cache, but
 * additionally supports reading entries back with the `getEntry()` method,
 * falling back to the underlying RemoteDocumentCache if no entry is
 * buffered.
 *
 * Entries added to the cache *must* be read first. This is to facilitate
 * calculating the size delta of the pending changes.
 *
 * PORTING NOTE: This class was implemented then removed from other platforms.
 * If byte-counting ends up being needed on the other platforms, consider
 * porting this class as part of that implementation work.
 */ class bi {
    constructor() {
        // A mapping of document key to the new cache entry that should be written (or null if any
        // existing cache entry should be removed).
        this.oi = new pi((t => t.toString()), ((t, e) => t.isEqual(e))), this.ci = !1;
    }
    ai(t) {
        const e = this.oi.get(t);
        return e ? e.readTime : J.min();
    }
    /**
     * Buffers a `RemoteDocumentCache.addEntry()` call.
     *
     * You can only modify documents that have already been retrieved via
     * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
     */    ui(t, e) {
        this.hi(), this.oi.set(t.key, {
            li: t,
            readTime: e
        });
    }
    /**
     * Buffers a `RemoteDocumentCache.removeEntry()` call.
     *
     * You can only remove documents that have already been retrieved via
     * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
     */    _i(t, e = null) {
        this.hi(), this.oi.set(t, {
            li: null,
            readTime: e
        });
    }
    /**
     * Looks up an entry in the cache. The buffered changes will first be checked,
     * and if no buffered change applies, this will forward to
     * `RemoteDocumentCache.getEntry()`.
     *
     * @param transaction - The transaction in which to perform any persistence
     *     operations.
     * @param documentKey - The key of the entry to look up.
     * @returns The cached Document or NoDocument entry, or null if we have
     *     nothing cached.
     */    fi(t, e) {
        this.hi();
        const n = this.oi.get(e);
        return void 0 !== n ? As.resolve(n.li) : this.di(t, e);
    }
    /**
     * Looks up several entries in the cache, forwarding to
     * `RemoteDocumentCache.getEntry()`.
     *
     * @param transaction - The transaction in which to perform any persistence
     *     operations.
     * @param documentKeys - The keys of the entries to look up.
     * @returns A map of cached `Document`s or `NoDocument`s, indexed by key. If
     *     an entry cannot be found, the corresponding key will be mapped to a
     *     null value.
     */    getEntries(t, e) {
        return this.wi(t, e);
    }
    /**
     * Applies buffered changes to the underlying RemoteDocumentCache, using
     * the provided transaction.
     */    apply(t) {
        return this.hi(), this.ci = !0, this.Ei(t);
    }
    /** Helper to assert this.changes is not null  */    hi() {}
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Delete a mutation batch and the associated document mutations.
 * @returns A PersistencePromise of the document mutations that were removed.
 */ function vi(t, e, n) {
    const s = t.store(qs.store), i = t.store(Us.store), r = [], o = IDBKeyRange.only(n.batchId);
    let c = 0;
    const a = s.ls({
        range: o
    }, ((t, e, n) => (c++, n.delete())));
    r.push(a.next((() => {
        p(1 === c);
    })));
    const u = [];
    for (const t of n.mutations) {
        const s = Us.key(e, t.key.path, n.batchId);
        r.push(i.delete(s)), u.push(t.key);
    }
    return As.$n(r).next((() => u));
}

/**
 * Returns an approximate size for the given document.
 */ function Si(t) {
    let e;
    if (t.document) e = t.document; else if (t.unknownDocument) e = t.unknownDocument; else {
        if (!t.noDocument) throw V();
        e = t.noDocument;
    }
    return JSON.stringify(e).length;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** A mutation queue for a specific user, backed by IndexedDB. */ class Di {
    constructor(
    /**
     * The normalized userId (e.g. null UID => "" userId) used to store /
     * retrieve mutations.
     */
    t, e, n, s) {
        this.userId = t, this.Kt = e, this.Ti = n, this.Ii = s, 
        /**
         * Caches the document keys for pending mutation batches. If the mutation
         * has been removed from IndexedDb, the cached value may continue to
         * be used to retrieve the batch's document keys. To remove a cached value
         * locally, `removeCachedMutationKeys()` should be invoked either directly
         * or through `removeMutationBatches()`.
         *
         * With multi-tab, when the primary client acknowledges or rejects a mutation,
         * this cache is used by secondary clients to invalidate the local
         * view of the documents that were previously affected by the mutation.
         */
        // PORTING NOTE: Multi-tab only.
        this.mi = {};
    }
    /**
     * Creates a new mutation queue for the given user.
     * @param user - The user for which to create a mutation queue.
     * @param serializer - The serializer to use when persisting to IndexedDb.
     */    static Ai(t, e, n, s) {
        // TODO(mcg): Figure out what constraints there are on userIDs
        // In particular, are there any reserved characters? are empty ids allowed?
        // For the moment store these together in the same mutations table assuming
        // that empty userIDs aren't allowed.
        p("" !== t.uid);
        const i = t.A() ? t.uid : "";
        return new Di(i, e, n, s);
    }
    Ri(t) {
        let e = !0;
        const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);
        return xi(t).ls({
            index: qs.userMutationsIndex,
            range: n
        }, ((t, n, s) => {
            e = !1, s.done();
        })).next((() => e));
    }
    Pi(t, e, n, s) {
        const i = Ni(t), r = xi(t);
        // The IndexedDb implementation in Chrome (and Firefox) does not handle
        // compound indices that include auto-generated keys correctly. To ensure
        // that the index entry is added correctly in all browsers, we perform two
        // writes: The first write is used to retrieve the next auto-generated Batch
        // ID, and the second write populates the index and stores the actual
        // mutation batch.
        // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972
        // We write an empty object to obtain key
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        return r.add({}).next((o => {
            p("number" == typeof o);
            const c = new si(o, e, n, s), a = function(t, e, n) {
                const s = n.baseMutations.map((e => es(t.ks, e))), i = n.mutations.map((e => es(t.ks, e)));
                return new qs(e, n.batchId, n.Ss.toMillis(), s, i);
            }(this.Kt, this.userId, c), u = [];
            let h = new ln(((t, e) => D(t.ot(), e.ot())));
            for (const t of s) {
                const e = Us.key(this.userId, t.key.path, o);
                h = h.add(t.key.path.Z()), u.push(r.put(a)), u.push(i.put(e, Us.PLACEHOLDER));
            }
            return h.forEach((e => {
                u.push(this.Ti.Us(t, e));
            })), t.Vs((() => {
                this.mi[o] = c.keys();
            })), As.$n(u).next((() => c));
        }));
    }
    yi(t, e) {
        return xi(t).get(e).next((t => t ? (p(t.userId === this.userId), _i(this.Kt, t)) : null));
    }
    /**
     * Returns the document keys for the mutation batch with the given batchId.
     * For primary clients, this method returns `null` after
     * `removeMutationBatches()` has been called. Secondary clients return a
     * cached result until `removeCachedMutationKeys()` is invoked.
     */
    // PORTING NOTE: Multi-tab only.
    gi(t, e) {
        return this.mi[e] ? As.resolve(this.mi[e]) : this.yi(t, e).next((t => {
            if (t) {
                const n = t.keys();
                return this.mi[e] = n, n;
            }
            return null;
        }));
    }
    Vi(t, e) {
        const n = e + 1, s = IDBKeyRange.lowerBound([ this.userId, n ]);
        let i = null;
        return xi(t).ls({
            index: qs.userMutationsIndex,
            range: s
        }, ((t, e, s) => {
            e.userId === this.userId && (p(e.batchId >= n), i = _i(this.Kt, e)), s.done();
        })).next((() => i));
    }
    pi(t) {
        const e = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);
        let n = -1;
        return xi(t).ls({
            index: qs.userMutationsIndex,
            range: e,
            reverse: !0
        }, ((t, e, s) => {
            n = e.batchId, s.done();
        })).next((() => n));
    }
    bi(t) {
        const e = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);
        return xi(t).os(qs.userMutationsIndex, e).next((t => t.map((t => _i(this.Kt, t)))));
    }
    vi(t, e) {
        // Scan the document-mutation index starting with a prefix starting with
        // the given documentKey.
        const n = Us.prefixForPath(this.userId, e.path), s = IDBKeyRange.lowerBound(n), i = [];
        return Ni(t).ls({
            range: s
        }, ((n, s, r) => {
            const [o, c, a] = n, u = Ms(c);
            // Only consider rows matching exactly the specific key of
            // interest. Note that because we order by path first, and we
            // order terminators before path separators, we'll encounter all
            // the index rows for documentKey contiguously. In particular, all
            // the rows for documentKey will occur before any rows for
            // documents nested in a subcollection beneath documentKey so we
            // can stop as soon as we hit any such row.
                        if (o === this.userId && e.path.isEqual(u)) 
            // Look up the mutation batch in the store.
            return xi(t).get(a).next((t => {
                if (!t) throw V();
                p(t.userId === this.userId), i.push(_i(this.Kt, t));
            }));
            r.done();
        })).next((() => i));
    }
    Si(t, e) {
        let n = new ln(D);
        const s = [];
        return e.forEach((e => {
            const i = Us.prefixForPath(this.userId, e.path), r = IDBKeyRange.lowerBound(i), o = Ni(t).ls({
                range: r
            }, ((t, s, i) => {
                const [r, o, c] = t, a = Ms(o);
                // Only consider rows matching exactly the specific key of
                // interest. Note that because we order by path first, and we
                // order terminators before path separators, we'll encounter all
                // the index rows for documentKey contiguously. In particular, all
                // the rows for documentKey will occur before any rows for
                // documents nested in a subcollection beneath documentKey so we
                // can stop as soon as we hit any such row.
                                r === this.userId && e.path.isEqual(a) ? n = n.add(c) : i.done();
            }));
            s.push(o);
        })), As.$n(s).next((() => this.Di(t, n)));
    }
    Ci(t, e) {
        const n = e.path, s = n.length + 1, i = Us.prefixForPath(this.userId, n), r = IDBKeyRange.lowerBound(i);
        // Collect up unique batchIDs encountered during a scan of the index. Use a
        // SortedSet to accumulate batch IDs so they can be traversed in order in a
        // scan of the main table.
        let o = new ln(D);
        return Ni(t).ls({
            range: r
        }, ((t, e, i) => {
            const [r, c, a] = t, u = Ms(c);
            r === this.userId && n.st(u) ? 
            // Rows with document keys more than one segment longer than the
            // query path can't be matches. For example, a query on 'rooms'
            // can't match the document /rooms/abc/messages/xyx.
            // TODO(mcg): we'll need a different scanner when we implement
            // ancestor queries.
            u.length === s && (o = o.add(a)) : i.done();
        })).next((() => this.Di(t, o)));
    }
    Di(t, e) {
        const n = [], s = [];
        // TODO(rockwood): Implement this using iterate.
        return e.forEach((e => {
            s.push(xi(t).get(e).next((t => {
                if (null === t) throw V();
                p(t.userId === this.userId), n.push(_i(this.Kt, t));
            })));
        })), As.$n(s).next((() => n));
    }
    xi(t, e) {
        return vi(t.bs, this.userId, e).next((n => (t.Vs((() => {
            this.Ni(e.batchId);
        })), As.forEach(n, (e => this.Ii.Oi(t, e))))));
    }
    /**
     * Clears the cached keys for a mutation batch. This method should be
     * called by secondary clients after they process mutation updates.
     *
     * Note that this method does not have to be called from primary clients as
     * the corresponding cache entries are cleared when an acknowledged or
     * rejected batch is removed from the mutation queue.
     */
    // PORTING NOTE: Multi-tab only
    Ni(t) {
        delete this.mi[t];
    }
    Fi(t) {
        return this.Ri(t).next((e => {
            if (!e) return As.resolve();
            // Verify that there are no entries in the documentMutations index if
            // the queue is empty.
                        const n = IDBKeyRange.lowerBound(Us.prefixForUser(this.userId)), s = [];
            return Ni(t).ls({
                range: n
            }, ((t, e, n) => {
                if (t[0] === this.userId) {
                    const e = Ms(t[1]);
                    s.push(e);
                } else n.done();
            })).next((() => {
                p(0 === s.length);
            }));
        }));
    }
    ki(t, e) {
        return Ci(t, this.userId, e);
    }
    // PORTING NOTE: Multi-tab only (state is held in memory in other clients).
    /** Returns the mutation queue's metadata from IndexedDb. */
    Mi(t) {
        return Oi(t).get(this.userId).next((t => t || new Bs(this.userId, -1, 
        /*lastStreamToken=*/ "")));
    }
}

/**
 * @returns true if the mutation queue for the given user contains a pending
 *         mutation for the given key.
 */ function Ci(t, e, n) {
    const s = Us.prefixForPath(e, n.path), i = s[1], r = IDBKeyRange.lowerBound(s);
    let o = !1;
    return Ni(t).ls({
        range: r,
        hs: !0
    }, ((t, n, s) => {
        const [r, c, /*batchID*/ a] = t;
        r === e && c === i && (o = !0), s.done();
    })).next((() => o));
}

/** Returns true if any mutation queue contains the given document. */
/**
 * Helper to get a typed SimpleDbStore for the mutations object store.
 */
function xi(t) {
    return ni(t, qs.store);
}

/**
 * Helper to get a typed SimpleDbStore for the mutationQueues object store.
 */ function Ni(t) {
    return ni(t, Us.store);
}

/**
 * Helper to get a typed SimpleDbStore for the mutationQueues object store.
 */ function Oi(t) {
    return ni(t, Bs.store);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Offset to ensure non-overlapping target ids. */
/**
 * Generates monotonically increasing target IDs for sending targets to the
 * watch stream.
 *
 * The client constructs two generators, one for the target cache, and one for
 * for the sync engine (to generate limbo documents targets). These
 * generators produce non-overlapping IDs (by using even and odd IDs
 * respectively).
 *
 * By separating the target ID space, the query cache can generate target IDs
 * that persist across client restarts, while sync engine can independently
 * generate in-memory target IDs that are transient and can be reused after a
 * restart.
 */
class Fi {
    constructor(t) {
        this.Li = t;
    }
    next() {
        return this.Li += 2, this.Li;
    }
    static $i() {
        // The target cache generator must return '2' in its first call to `next()`
        // as there is no differentiation in the protocol layer between an unset
        // number and the number '0'. If we were to sent a target with target ID
        // '0', the backend would consider it unset and replace it with its own ID.
        return new Fi(0);
    }
    static Bi() {
        // Sync engine assigns target IDs for limbo document detection.
        return new Fi(-1);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class ki {
    constructor(t, e) {
        this.Ii = t, this.Kt = e;
    }
    // PORTING NOTE: We don't cache global metadata for the target cache, since
    // some of it (in particular `highestTargetId`) can be modified by secondary
    // tabs. We could perhaps be more granular (and e.g. still cache
    // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go
    // to IndexedDb whenever we need to read metadata. We can revisit if it turns
    // out to have a meaningful performance impact.
    qi(t) {
        return this.Ui(t).next((e => {
            const n = new Fi(e.highestTargetId);
            return e.highestTargetId = n.next(), this.Qi(t, e).next((() => e.highestTargetId));
        }));
    }
    Ki(t) {
        return this.Ui(t).next((t => J.j(new H(t.lastRemoteSnapshotVersion.seconds, t.lastRemoteSnapshotVersion.nanoseconds))));
    }
    ji(t) {
        return this.Ui(t).next((t => t.highestListenSequenceNumber));
    }
    Wi(t, e, n) {
        return this.Ui(t).next((s => (s.highestListenSequenceNumber = e, n && (s.lastRemoteSnapshotVersion = n.G()), 
        e > s.highestListenSequenceNumber && (s.highestListenSequenceNumber = e), this.Qi(t, s))));
    }
    Gi(t, e) {
        return this.zi(t, e).next((() => this.Ui(t).next((n => (n.targetCount += 1, this.Hi(e, n), 
        this.Qi(t, n))))));
    }
    Ji(t, e) {
        return this.zi(t, e);
    }
    Yi(t, e) {
        return this.Xi(t, e.targetId).next((() => Mi(t).delete(e.targetId))).next((() => this.Ui(t))).next((e => (p(e.targetCount > 0), 
        e.targetCount -= 1, this.Qi(t, e))));
    }
    /**
     * Drops any targets with sequence number less than or equal to the upper bound, excepting those
     * present in `activeTargetIds`. Document associations for the removed targets are also removed.
     * Returns the number of targets removed.
     */    Zi(t, e, n) {
        let s = 0;
        const i = [];
        return Mi(t).ls(((r, o) => {
            const c = fi(o);
            c.sequenceNumber <= e && null === n.get(c.targetId) && (s++, i.push(this.Yi(t, c)));
        })).next((() => As.$n(i))).next((() => s));
    }
    /**
     * Call provided function with each `TargetData` that we have cached.
     */    mn(t, e) {
        return Mi(t).ls(((t, n) => {
            const s = fi(n);
            e(s);
        }));
    }
    Ui(t) {
        return Li(t).get(Hs.key).next((t => (p(null !== t), t)));
    }
    Qi(t, e) {
        return Li(t).put(Hs.key, e);
    }
    zi(t, e) {
        return Mi(t).put(di(this.Kt, e));
    }
    /**
     * In-place updates the provided metadata to account for values in the given
     * TargetData. Saving is done separately. Returns true if there were any
     * changes to the metadata.
     */    Hi(t, e) {
        let n = !1;
        return t.targetId > e.highestTargetId && (e.highestTargetId = t.targetId, n = !0), 
        t.sequenceNumber > e.highestListenSequenceNumber && (e.highestListenSequenceNumber = t.sequenceNumber, 
        n = !0), n;
    }
    tr(t) {
        return this.Ui(t).next((t => t.targetCount));
    }
    er(t, e) {
        // Iterating by the canonicalId may yield more than one result because
        // canonicalId values are not required to be unique per target. This query
        // depends on the queryTargets index to be efficient.
        const n = Lt(e), s = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]);
        let i = null;
        return Mi(t).ls({
            range: s,
            index: Gs.queryTargetsIndexName
        }, ((t, n, s) => {
            const r = fi(n);
            // After finding a potential match, check that the target is
            // actually equal to the requested target.
                        Bt(e, r.target) && (i = r, s.done());
        })).next((() => i));
    }
    nr(t, e, n) {
        // PORTING NOTE: The reverse index (documentsTargets) is maintained by
        // IndexedDb.
        const s = [], i = $i(t);
        return e.forEach((e => {
            const r = Os(e.path);
            s.push(i.put(new zs(n, r))), s.push(this.Ii.sr(t, n, e));
        })), As.$n(s);
    }
    ir(t, e, n) {
        // PORTING NOTE: The reverse index (documentsTargets) is maintained by
        // IndexedDb.
        const s = $i(t);
        return As.forEach(e, (e => {
            const i = Os(e.path);
            return As.$n([ s.delete([ n, i ]), this.Ii.rr(t, n, e) ]);
        }));
    }
    Xi(t, e) {
        const n = $i(t), s = IDBKeyRange.bound([ e ], [ e + 1 ], 
        /*lowerOpen=*/ !1, 
        /*upperOpen=*/ !0);
        return n.delete(s);
    }
    cr(t, e) {
        const n = IDBKeyRange.bound([ e ], [ e + 1 ], 
        /*lowerOpen=*/ !1, 
        /*upperOpen=*/ !0), s = $i(t);
        let i = Rn();
        return s.ls({
            range: n,
            hs: !0
        }, ((t, e, n) => {
            const s = Ms(t[1]), r = new et(s);
            i = i.add(r);
        })).next((() => i));
    }
    ki(t, e) {
        const n = Os(e.path), s = IDBKeyRange.bound([ n ], [ x(n) ], 
        /*lowerOpen=*/ !1, 
        /*upperOpen=*/ !0);
        let i = 0;
        return $i(t).ls({
            index: zs.documentTargetsIndex,
            hs: !0,
            range: s
        }, (([t, e], n, s) => {
            // Having a sentinel row for a document does not count as containing that document;
            // For the target cache, containing the document means the document is part of some
            // target.
            0 !== t && (i++, s.done());
        })).next((() => i > 0));
    }
    /**
     * Looks up a TargetData entry by target ID.
     *
     * @param targetId - The target ID of the TargetData entry to look up.
     * @returns The cached TargetData entry, or null if the cache has no entry for
     * the target.
     */
    // PORTING NOTE: Multi-tab only.
    Dn(t, e) {
        return Mi(t).get(e).next((t => t ? fi(t) : null));
    }
}

/**
 * Helper to get a typed SimpleDbStore for the queries object store.
 */ function Mi(t) {
    return ni(t, Gs.store);
}

/**
 * Helper to get a typed SimpleDbStore for the target globals object store.
 */ function Li(t) {
    return ni(t, Hs.store);
}

/**
 * Helper to get a typed SimpleDbStore for the document target object store.
 */ function $i(t) {
    return ni(t, zs.store);
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ function Bi([t, e], [n, s]) {
    const i = D(t, n);
    return 0 === i ? D(e, s) : i;
}

/**
 * Used to calculate the nth sequence number. Keeps a rolling buffer of the
 * lowest n values passed to `addElement`, and finally reports the largest of
 * them in `maxValue`.
 */ class qi {
    constructor(t) {
        this.ar = t, this.buffer = new ln(Bi), this.ur = 0;
    }
    hr() {
        return ++this.ur;
    }
    lr(t) {
        const e = [ t, this.hr() ];
        if (this.buffer.size < this.ar) this.buffer = this.buffer.add(e); else {
            const t = this.buffer.last();
            Bi(e, t) < 0 && (this.buffer = this.buffer.delete(t).add(e));
        }
    }
    get maxValue() {
        // Guaranteed to be non-empty. If we decide we are not collecting any
        // sequence numbers, nthSequenceNumber below short-circuits. If we have
        // decided that we are collecting n sequence numbers, it's because n is some
        // percentage of the existing sequence numbers. That means we should never
        // be in a situation where we are collecting sequence numbers but don't
        // actually have any.
        return this.buffer.last()[0];
    }
}

/**
 * This class is responsible for the scheduling of LRU garbage collection. It handles checking
 * whether or not GC is enabled, as well as which delay to use before the next run.
 */ class Ui {
    constructor(t, e) {
        this._r = t, this.fs = e, this.dr = !1, this.wr = null;
    }
    start(t) {
        -1 !== this._r.params.Hs && this.Er(t);
    }
    stop() {
        this.wr && (this.wr.cancel(), this.wr = null);
    }
    get Tr() {
        return null !== this.wr;
    }
    Er(t) {
        const e = this.dr ? 3e5 : 6e4;
        R("LruGarbageCollector", `Garbage collection scheduled in ${e}ms`), this.wr = this.fs.Ir("lru_garbage_collection" /* LruGarbageCollection */ , e, (async () => {
            this.wr = null, this.dr = !0;
            try {
                await t.mr(this._r);
            } catch (t) {
                Vs(t) ? R("LruGarbageCollector", "Ignoring IndexedDB error during garbage collection: ", t) : await Vi(t);
            }
            await this.Er(t);
        }));
    }
}

/** Implements the steps for LRU garbage collection. */ class Qi {
    constructor(t, e) {
        this.Ar = t, this.params = e;
    }
    Rr(t, e) {
        return this.Ar.Pr(t).next((t => Math.floor(e / 100 * t)));
    }
    yr(t, e) {
        if (0 === e) return As.resolve(z.U);
        const n = new qi(e);
        return this.Ar.mn(t, (t => n.lr(t.sequenceNumber))).next((() => this.Ar.gr(t, (t => n.lr(t))))).next((() => n.maxValue));
    }
    Zi(t, e, n) {
        return this.Ar.Zi(t, e, n);
    }
    Vr(t, e) {
        return this.Ar.Vr(t, e);
    }
    pr(t, e) {
        return -1 === this.params.Hs ? (R("LruGarbageCollector", "Garbage collection skipped; disabled"), 
        As.resolve(yi)) : this.br(t).next((n => n < this.params.Hs ? (R("LruGarbageCollector", `Garbage collection skipped; Cache size ${n} is lower than threshold ` + this.params.Hs), 
        yi) : this.vr(t, e)));
    }
    br(t) {
        return this.Ar.br(t);
    }
    vr(t, e) {
        let n, s, i, r, o, c, a;
        const h = Date.now();
        return this.Rr(t, this.params.Js).next((e => (
        // Cap at the configured max
        e > this.params.Ys ? (R("LruGarbageCollector", `Capping sequence numbers to collect down to the maximum of ${this.params.Ys} from ` + e), 
        s = this.params.Ys) : s = e, r = Date.now(), this.yr(t, s)))).next((s => (n = s, 
        o = Date.now(), this.Zi(t, n, e)))).next((e => (i = e, c = Date.now(), this.Vr(t, n)))).next((t => {
            if (a = Date.now(), A() <= u.DEBUG) {
                R("LruGarbageCollector", `LRU Garbage Collection\n\tCounted targets in ${r - h}ms\n\tDetermined least recently used ${s} in ` + (o - r) + "ms\n" + `\tRemoved ${i} targets in ` + (c - o) + "ms\n" + `\tRemoved ${t} documents in ` + (a - c) + "ms\n" + `Total Duration: ${a - h}ms`);
            }
            return As.resolve({
                js: !0,
                Ws: s,
                Gs: i,
                zs: t
            });
        }));
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Provides LRU functionality for IndexedDB persistence. */
class Ki {
    constructor(t, e) {
        this.db = t, this._r = function(t, e) {
            return new Qi(t, e);
        }(this, e);
    }
    Pr(t) {
        const e = this.Sr(t);
        return this.db.Dr().tr(t).next((t => e.next((e => t + e))));
    }
    Sr(t) {
        let e = 0;
        return this.gr(t, (t => {
            e++;
        })).next((() => e));
    }
    mn(t, e) {
        return this.db.Dr().mn(t, e);
    }
    gr(t, e) {
        return this.Cr(t, ((t, n) => e(n)));
    }
    sr(t, e, n) {
        return ji(t, n);
    }
    rr(t, e, n) {
        return ji(t, n);
    }
    Zi(t, e, n) {
        return this.db.Dr().Zi(t, e, n);
    }
    Oi(t, e) {
        return ji(t, e);
    }
    /**
     * Returns true if anything would prevent this document from being garbage
     * collected, given that the document in question is not present in any
     * targets and has a sequence number less than or equal to the upper bound for
     * the collection run.
     */    Nr(t, e) {
        return function(t, e) {
            let n = !1;
            return Oi(t)._s((s => Ci(t, s, e).next((t => (t && (n = !0), As.resolve(!t)))))).next((() => n));
        }(t, e);
    }
    Vr(t, e) {
        const n = this.db.Fr().Or(), s = [];
        let i = 0;
        return this.Cr(t, ((r, o) => {
            if (o <= e) {
                const e = this.Nr(t, r).next((e => {
                    if (!e) 
                    // Our size accounting requires us to read all documents before
                    // removing them.
                    return i++, n.fi(t, r).next((() => (n._i(r), $i(t).delete([ 0, Os(r.path) ]))));
                }));
                s.push(e);
            }
        })).next((() => As.$n(s))).next((() => n.apply(t))).next((() => i));
    }
    removeTarget(t, e) {
        const n = e.Lt(t.vs);
        return this.db.Dr().Ji(t, n);
    }
    kr(t, e) {
        return ji(t, e);
    }
    /**
     * Call provided function for each document in the cache that is 'orphaned'. Orphaned
     * means not a part of any target, so the only entry in the target-document index for
     * that document will be the sentinel row (targetId 0), which will also have the sequence
     * number for the last time the document was accessed.
     */    Cr(t, e) {
        const n = $i(t);
        let s, i = z.U;
        return n.ls({
            index: zs.documentTargetsIndex
        }, (([t, n], {path: r, sequenceNumber: o}) => {
            0 === t ? (
            // if nextToReport is valid, report it, this is a new key so the
            // last one must not be a member of any targets.
            i !== z.U && e(new et(Ms(s)), i), 
            // set nextToReport to be this sequence number. It's the next one we
            // might report, if we don't find any targets for this document.
            // Note that the sequence number must be defined when the targetId
            // is 0.
            i = o, s = r) : 
            // set nextToReport to be invalid, we know we don't need to report
            // this one since we found a target for it.
            i = z.U;
        })).next((() => {
            // Since we report sequence numbers after getting to the next key, we
            // need to check if the last key we iterated over was an orphaned
            // document and report it.
            i !== z.U && e(new et(Ms(s)), i);
        }));
    }
    br(t) {
        return this.db.Fr().Mr(t);
    }
}

function ji(t, e) {
    return $i(t).put(
    /**
 * @returns A value suitable for writing a sentinel row in the target-document
 * store.
 */
    function(t, e) {
        return new zs(0, Os(t.path), e);
    }(e, t.vs));
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * The RemoteDocumentCache for IndexedDb. To construct, invoke
 * `newIndexedDbRemoteDocumentCache()`.
 */ class Wi {
    /**
     * @param serializer - The document serializer.
     * @param indexManager - The query indexes that need to be maintained.
     */
    constructor(t, e) {
        this.Kt = t, this.Ti = e;
    }
    /**
     * Adds the supplied entries to the cache.
     *
     * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
     * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
     */    ui(t, e, n) {
        return Hi(t).put(Ji(e), n);
    }
    /**
     * Removes a document from the cache.
     *
     * All calls of `removeEntry`  are required to go through the RemoteDocumentChangeBuffer
     * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
     */    _i(t, e) {
        const n = Hi(t), s = Ji(e);
        return n.delete(s);
    }
    /**
     * Updates the current cache size.
     *
     * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the
     * cache's metadata.
     */    updateMetadata(t, e) {
        return this.getMetadata(t).next((n => (n.byteSize += e, this.Lr(t, n))));
    }
    fi(t, e) {
        return Hi(t).get(Ji(e)).next((t => this.$r(t)));
    }
    /**
     * Looks up an entry in the cache.
     *
     * @param documentKey - The key of the entry to look up.
     * @returns The cached MaybeDocument entry and its size, or null if we have
     * nothing cached.
     */    Br(t, e) {
        return Hi(t).get(Ji(e)).next((t => {
            const e = this.$r(t);
            return e ? {
                li: e,
                size: Si(t)
            } : null;
        }));
    }
    getEntries(t, e) {
        let n = wn();
        return this.qr(t, e, ((t, e) => {
            const s = this.$r(e);
            n = n.Ht(t, s);
        })).next((() => n));
    }
    /**
     * Looks up several entries in the cache.
     *
     * @param documentKeys - The set of keys entries to look up.
     * @returns A map of MaybeDocuments indexed by key (if a document cannot be
     *     found, the key will be mapped to null) and a map of sizes indexed by
     *     key (zero if the key cannot be found).
     */    Ur(t, e) {
        let n = wn(), s = new an(et.J);
        return this.qr(t, e, ((t, e) => {
            const i = this.$r(e);
            i ? (n = n.Ht(t, i), s = s.Ht(t, Si(e))) : (n = n.Ht(t, null), s = s.Ht(t, 0));
        })).next((() => ({
            Qr: n,
            Kr: s
        })));
    }
    qr(t, e, n) {
        if (e.nt()) return As.resolve();
        const s = IDBKeyRange.bound(e.first().path.rt(), e.last().path.rt()), i = e.ee();
        let r = i.ce();
        return Hi(t).ls({
            range: s
        }, ((t, e, s) => {
            const o = et.Tt(t);
            // Go through keys not found in cache.
                        for (;r && et.J(r, o) < 0; ) n(r, null), r = i.ce();
            r && r.isEqual(o) && (
            // Key found in cache.
            n(r, e), r = i.ae() ? i.ce() : null), 
            // Skip to the next key (if there is one).
            r ? s.rs(r.path.rt()) : s.done();
        })).next((() => {
            // The rest of the keys are not in the cache. One case where `iterate`
            // above won't go through them is when the cache is empty.
            for (;r; ) n(r, null), r = i.ae() ? i.ce() : null;
        }));
    }
    jr(t, e, n) {
        let s = Tn();
        const i = e.path.length + 1, r = {};
        if (n.isEqual(J.min())) {
            // Documents are ordered by key, so we can use a prefix scan to narrow
            // down the documents we need to match the query against.
            const t = e.path.rt();
            r.range = IDBKeyRange.lowerBound(t);
        } else {
            // Execute an index-free query and filter by read time. This is safe
            // since all document changes to queries that have a
            // lastLimboFreeSnapshotVersion (`sinceReadTime`) have a read time set.
            const t = e.path.rt(), s = ai(n);
            r.range = IDBKeyRange.lowerBound([ t, s ], 
            /* open= */ !0), r.index = js.collectionReadTimeIndex;
        }
        return Hi(t).ls(r, ((t, n, r) => {
            // The query is actually returning any path that starts with the query
            // path prefix which may include documents in subcollections. For
            // example, a query on 'rooms' will return rooms/abc/messages/xyx but we
            // shouldn't match it. Fix this by discarding rows with document keys
            // more than one segment longer than the query path.
            if (t.length !== i) return;
            const o = oi(this.Kt, n);
            e.path.st(o.key.path) ? o instanceof Nt && Ie(e, o) && (s = s.Ht(o.key, o)) : r.done();
        })).next((() => s));
    }
    Or(t) {
        return new Gi(this, !!t && t.Wr);
    }
    Mr(t) {
        return this.getMetadata(t).next((t => t.byteSize));
    }
    getMetadata(t) {
        return zi(t).get(Ws.key).next((t => (p(!!t), t)));
    }
    Lr(t, e) {
        return zi(t).put(Ws.key, e);
    }
    /**
     * Decodes `remoteDoc` and returns the document (or null, if the document
     * corresponds to the format used for sentinel deletes).
     */    $r(t) {
        if (t) {
            const e = oi(this.Kt, t);
            return e instanceof Ot && e.version.isEqual(J.min()) ? null : e;
        }
        return null;
    }
}

/**
 * Creates a new IndexedDbRemoteDocumentCache.
 *
 * @param serializer - The document serializer.
 * @param indexManager - The query indexes that need to be maintained.
 */
/**
 * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.
 *
 * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size
 * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb
 * when we apply the changes.
 */
class Gi extends bi {
    /**
     * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.
     * @param trackRemovals - Whether to create sentinel deletes that can be tracked by
     * `getNewDocumentChanges()`.
     */
    constructor(t, e) {
        super(), this.Gr = t, this.Wr = e, 
        // A map of document sizes prior to applying the changes in this buffer.
        this.zr = new pi((t => t.toString()), ((t, e) => t.isEqual(e)));
    }
    Ei(t) {
        const e = [];
        let n = 0, s = new ln(((t, e) => D(t.ot(), e.ot())));
        return this.oi.forEach(((i, r) => {
            const o = this.zr.get(i);
            if (r.li) {
                const c = ci(this.Gr.Kt, r.li, this.ai(i));
                s = s.add(i.path.Z());
                const a = Si(c);
                n += a - o, e.push(this.Gr.ui(t, i, c));
            } else if (n -= o, this.Wr) {
                // In order to track removals, we store a "sentinel delete" in the
                // RemoteDocumentCache. This entry is represented by a NoDocument
                // with a version of 0 and ignored by `maybeDecodeDocument()` but
                // preserved in `getNewDocumentChanges()`.
                const n = ci(this.Gr.Kt, new Ot(i, J.min()), this.ai(i));
                e.push(this.Gr.ui(t, i, n));
            } else e.push(this.Gr._i(t, i));
        })), s.forEach((n => {
            e.push(this.Gr.Ti.Us(t, n));
        })), e.push(this.Gr.updateMetadata(t, n)), As.$n(e);
    }
    di(t, e) {
        // Record the size of everything we load from the cache so we can compute a delta later.
        return this.Gr.Br(t, e).next((t => null === t ? (this.zr.set(e, 0), null) : (this.zr.set(e, t.size), 
        t.li)));
    }
    wi(t, e) {
        // Record the size of everything we load from the cache so we can compute
        // a delta later.
        return this.Gr.Ur(t, e).next((({Qr: t, Kr: e}) => (
        // Note: `getAllFromCache` returns two maps instead of a single map from
        // keys to `DocumentSizeEntry`s. This is to allow returning the
        // `NullableMaybeDocumentMap` directly, without a conversion.
        e.forEach(((t, e) => {
            this.zr.set(t, e);
        })), t)));
    }
}

function zi(t) {
    return ni(t, Ws.store);
}

/**
 * Helper to get a typed SimpleDbStore for the remoteDocuments object store.
 */ function Hi(t) {
    return ni(t, js.store);
}

function Ji(t) {
    return t.path.rt();
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Performs database creation and schema upgrades. */ class Yi {
    constructor(t) {
        this.Kt = t;
    }
    /**
     * Performs database creation and schema upgrades.
     *
     * Note that in production, this method is only ever used to upgrade the schema
     * to SCHEMA_VERSION. Different values of toVersion are only used for testing
     * and local feature development.
     */    Yn(t, e, n, s) {
        p(n < s && n >= 0 && s <= 11);
        const i = new Rs("createOrUpgrade", e);
        n < 1 && s >= 1 && (function(t) {
            t.createObjectStore($s.store);
        }(t), function(t) {
            t.createObjectStore(Bs.store, {
                keyPath: Bs.keyPath
            });
            t.createObjectStore(qs.store, {
                keyPath: qs.keyPath,
                autoIncrement: !0
            }).createIndex(qs.userMutationsIndex, qs.userMutationsKeyPath, {
                unique: !0
            }), t.createObjectStore(Us.store);
        }
        /**
 * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads
 * and rewrites all data.
 */ (t), Xi(t), function(t) {
            t.createObjectStore(js.store);
        }(t));
        // Migration 2 to populate the targetGlobal object no longer needed since
        // migration 3 unconditionally clears it.
                let r = As.resolve();
        return n < 3 && s >= 3 && (
        // Brand new clients don't need to drop and recreate--only clients that
        // potentially have corrupt data.
        0 !== n && (!function(t) {
            t.deleteObjectStore(zs.store), t.deleteObjectStore(Gs.store), t.deleteObjectStore(Hs.store);
        }(t), Xi(t)), r = r.next((() => 
        /**
 * Creates the target global singleton row.
 *
 * @param txn - The version upgrade transaction for indexeddb
 */
        function(t) {
            const e = t.store(Hs.store), n = new Hs(
            /*highestTargetId=*/ 0, 
            /*lastListenSequenceNumber=*/ 0, J.min().G(), 
            /*targetCount=*/ 0);
            return e.put(Hs.key, n);
        }
        /**
 * Creates indices on the RemoteDocuments store used for both multi-tab
 * and Index-Free queries.
 */ (i)))), n < 4 && s >= 4 && (0 !== n && (
        // Schema version 3 uses auto-generated keys to generate globally unique
        // mutation batch IDs (this was previously ensured internally by the
        // client). To migrate to the new schema, we have to read all mutations
        // and write them back out. We preserve the existing batch IDs to guarantee
        // consistency with other object stores. Any further mutation batch IDs will
        // be auto-generated.
        r = r.next((() => function(t, e) {
            return e.store(qs.store).os().next((n => {
                t.deleteObjectStore(qs.store);
                t.createObjectStore(qs.store, {
                    keyPath: qs.keyPath,
                    autoIncrement: !0
                }).createIndex(qs.userMutationsIndex, qs.userMutationsKeyPath, {
                    unique: !0
                });
                const s = e.store(qs.store), i = n.map((t => s.put(t)));
                return As.$n(i);
            }));
        }(t, i)))), r = r.next((() => {
            !function(t) {
                t.createObjectStore(Ys.store, {
                    keyPath: Ys.keyPath
                });
            }(t);
        }))), n < 5 && s >= 5 && (r = r.next((() => this.Hr(i)))), n < 6 && s >= 6 && (r = r.next((() => (function(t) {
            t.createObjectStore(Ws.store);
        }(t), this.Jr(i))))), n < 7 && s >= 7 && (r = r.next((() => this.Yr(i)))), n < 8 && s >= 8 && (r = r.next((() => this.Xr(t, i)))), 
        n < 9 && s >= 9 && (r = r.next((() => {
            // Multi-Tab used to manage its own changelog, but this has been moved
            // to the DbRemoteDocument object store itself. Since the previous change
            // log only contained transient data, we can drop its object store.
            !function(t) {
                t.objectStoreNames.contains("remoteDocumentChanges") && t.deleteObjectStore("remoteDocumentChanges");
            }(t), function(t) {
                const e = t.objectStore(js.store);
                e.createIndex(js.readTimeIndex, js.readTimeIndexPath, {
                    unique: !1
                }), e.createIndex(js.collectionReadTimeIndex, js.collectionReadTimeIndexPath, {
                    unique: !1
                });
            }(e);
        }))), n < 10 && s >= 10 && (r = r.next((() => this.Zr(i)))), n < 11 && s >= 11 && (r = r.next((() => {
            !function(t) {
                t.createObjectStore(Xs.store, {
                    keyPath: Xs.keyPath
                });
            }(t), function(t) {
                t.createObjectStore(Zs.store, {
                    keyPath: Zs.keyPath
                });
            }
            /**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ (t);
        }))), r;
    }
    Jr(t) {
        let e = 0;
        return t.store(js.store).ls(((t, n) => {
            e += Si(n);
        })).next((() => {
            const n = new Ws(e);
            return t.store(Ws.store).put(Ws.key, n);
        }));
    }
    Hr(t) {
        const e = t.store(Bs.store), n = t.store(qs.store);
        return e.os().next((e => As.forEach(e, (e => {
            const s = IDBKeyRange.bound([ e.userId, -1 ], [ e.userId, e.lastAcknowledgedBatchId ]);
            return n.os(qs.userMutationsIndex, s).next((n => As.forEach(n, (n => {
                p(n.userId === e.userId);
                const s = _i(this.Kt, n);
                return vi(t, e.userId, s).next((() => {}));
            }))));
        }))));
    }
    /**
     * Ensures that every document in the remote document cache has a corresponding sentinel row
     * with a sequence number. Missing rows are given the most recently used sequence number.
     */    Yr(t) {
        const e = t.store(zs.store), n = t.store(js.store);
        return t.store(Hs.store).get(Hs.key).next((t => {
            const s = [];
            return n.ls(((n, i) => {
                const r = new X(n), o = function(t) {
                    return [ 0, Os(t) ];
                }(r);
                s.push(e.get(o).next((n => n ? As.resolve() : (n => e.put(new zs(0, Os(n), t.highestListenSequenceNumber)))(r))));
            })).next((() => As.$n(s)));
        }));
    }
    Xr(t, e) {
        // Create the index.
        t.createObjectStore(Js.store, {
            keyPath: Js.keyPath
        });
        const n = e.store(Js.store), s = new Ai, i = t => {
            if (s.add(t)) {
                const e = t.et(), s = t.Z();
                return n.put({
                    collectionId: e,
                    parent: Os(s)
                });
            }
        };
        // Helper to add an index entry iff we haven't already written it.
                // Index existing remote documents.
        return e.store(js.store).ls({
            hs: !0
        }, ((t, e) => {
            const n = new X(t);
            return i(n.Z());
        })).next((() => e.store(Us.store).ls({
            hs: !0
        }, (([t, e, n], s) => {
            const r = Ms(e);
            return i(r.Z());
        }))));
    }
    Zr(t) {
        const e = t.store(Gs.store);
        return e.ls(((t, n) => {
            const s = fi(n), i = di(this.Kt, s);
            return e.put(i);
        }));
    }
}

function Xi(t) {
    t.createObjectStore(zs.store, {
        keyPath: zs.keyPath
    }).createIndex(zs.documentTargetsIndex, zs.documentTargetsKeyPath, {
        unique: !0
    });
    // NOTE: This is unique only because the TargetId is the suffix.
    t.createObjectStore(Gs.store, {
        keyPath: Gs.keyPath
    }).createIndex(Gs.queryTargetsIndexName, Gs.queryTargetsKeyPath, {
        unique: !0
    }), t.createObjectStore(Hs.store);
}

const Zi = "Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";

/**
 * Oldest acceptable age in milliseconds for client metadata before the client
 * is considered inactive and its associated data is garbage collected.
 */
/**
 * An IndexedDB-backed instance of Persistence. Data is stored persistently
 * across sessions.
 *
 * On Web only, the Firestore SDKs support shared access to its persistence
 * layer. This allows multiple browser tabs to read and write to IndexedDb and
 * to synchronize state even without network connectivity. Shared access is
 * currently optional and not enabled unless all clients invoke
 * `enablePersistence()` with `{synchronizeTabs:true}`.
 *
 * In multi-tab mode, if multiple clients are active at the same time, the SDK
 * will designate one client as the “primary client”. An effort is made to pick
 * a visible, network-connected and active client, and this client is
 * responsible for letting other clients know about its presence. The primary
 * client writes a unique client-generated identifier (the client ID) to
 * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to
 * update this entry, another client can acquire the lease and take over as
 * primary.
 *
 * Some persistence operations in the SDK are designated as primary-client only
 * operations. This includes the acknowledgment of mutations and all updates of
 * remote documents. The effects of these operations are written to persistence
 * and then broadcast to other tabs via LocalStorage (see
 * `WebStorageSharedClientState`), which then refresh their state from
 * persistence.
 *
 * Similarly, the primary client listens to notifications sent by secondary
 * clients to discover persistence changes written by secondary clients, such as
 * the addition of new mutations and query targets.
 *
 * If multi-tab is not enabled and another tab already obtained the primary
 * lease, IndexedDbPersistence enters a failed state and all subsequent
 * operations will automatically fail.
 *
 * Additionally, there is an optimization so that when a tab is closed, the
 * primary lease is released immediately (this is especially important to make
 * sure that a refreshed tab is able to immediately re-acquire the primary
 * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload
 * since it is an asynchronous API. So in addition to attempting to give up the
 * lease, the leaseholder writes its client ID to a "zombiedClient" entry in
 * LocalStorage which acts as an indicator that another tab should go ahead and
 * take the primary lease immediately regardless of the current lease timestamp.
 *
 * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no
 * longer optional.
 */
class tr {
    constructor(
    /**
     * Whether to synchronize the in-memory state of multiple tabs and share
     * access to local persistence.
     */
    t, e, n, s, i, r, o, c, a, 
    /**
     * If set to true, forcefully obtains database access. Existing tabs will
     * no longer be able to access IndexedDB.
     */
    u) {
        if (this.allowTabSynchronization = t, this.persistenceKey = e, this.clientId = n, 
        this.eo = i, this.window = r, this.document = o, this.no = a, this.so = u, this.io = null, 
        this.ro = !1, this.isPrimary = !1, this.networkEnabled = !0, 
        /** Our window.unload handler, if registered. */
        this.oo = null, this.inForeground = !1, 
        /** Our 'visibilitychange' listener if registered. */
        this.co = null, 
        /** The client metadata refresh task. */
        this.ao = null, 
        /** The last time we garbage collected the client metadata object store. */
        this.uo = Number.NEGATIVE_INFINITY, 
        /** A listener to notify on primary state changes. */
        this.ho = t => Promise.resolve(), !tr.jn()) throw new F(O.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");
        this.Ii = new Ki(this, s), this.lo = e + "main", this.Kt = new ri(c), this._o = new Ps(this.lo, 11, new Yi(this.Kt)), 
        this.fo = new ki(this.Ii, this.Kt), this.Ti = new Ri, this.wo = function(t, e) {
            return new Wi(t, e);
        }
        /**
 * Returns the set of documents that have changed since the specified read
 * time.
 */
        // PORTING NOTE: This is only used for multi-tab synchronization.
        (this.Kt, this.Ti), this.Eo = new Ei, this.window && this.window.localStorage ? this.To = this.window.localStorage : (this.To = null, 
        !1 === u && P("IndexedDbPersistence", "LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."));
    }
    /**
     * Attempt to start IndexedDb persistence.
     *
     * @returns Whether persistence was enabled.
     */    start() {
        // NOTE: This is expected to fail sometimes (in the case of another tab
        // already having the persistence lock), so it's the first thing we should
        // do.
        return this.Io().then((() => {
            if (!this.isPrimary && !this.allowTabSynchronization) 
            // Fail `start()` if `synchronizeTabs` is disabled and we cannot
            // obtain the primary lease.
            throw new F(O.FAILED_PRECONDITION, Zi);
            return this.mo(), this.Ao(), this.Ro(), this.runTransaction("getHighestListenSequenceNumber", "readonly", (t => this.fo.ji(t)));
        })).then((t => {
            this.io = new z(t, this.no);
        })).then((() => {
            this.ro = !0;
        })).catch((t => (this._o && this._o.close(), Promise.reject(t))));
    }
    /**
     * Registers a listener that gets called when the primary state of the
     * instance changes. Upon registering, this listener is invoked immediately
     * with the current primary state.
     *
     * PORTING NOTE: This is only used for Web multi-tab.
     */    Po(t) {
        return this.ho = async e => {
            if (this.Tr) return t(e);
        }, t(this.isPrimary);
    }
    /**
     * Registers a listener that gets called when the database receives a
     * version change event indicating that it has deleted.
     *
     * PORTING NOTE: This is only used for Web multi-tab.
     */    yo(t) {
        this._o.Zn((async e => {
            // Check if an attempt is made to delete IndexedDB.
            null === e.newVersion && await t();
        }));
    }
    /**
     * Adjusts the current network state in the client's metadata, potentially
     * affecting the primary lease.
     *
     * PORTING NOTE: This is only used for Web multi-tab.
     */    Vo(t) {
        this.networkEnabled !== t && (this.networkEnabled = t, 
        // Schedule a primary lease refresh for immediate execution. The eventual
        // lease update will be propagated via `primaryStateListener`.
        this.eo.ys((async () => {
            this.Tr && await this.Io();
        })));
    }
    /**
     * Updates the client metadata in IndexedDb and attempts to either obtain or
     * extend the primary lease for the local client. Asynchronously notifies the
     * primary state listener if the client either newly obtained or released its
     * primary lease.
     */    Io() {
        return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", (t => nr(t).put(new Ys(this.clientId, Date.now(), this.networkEnabled, this.inForeground)).next((() => {
            if (this.isPrimary) return this.po(t).next((t => {
                t || (this.isPrimary = !1, this.eo.bo((() => this.ho(!1))));
            }));
        })).next((() => this.vo(t))).next((e => this.isPrimary && !e ? this.So(t).next((() => !1)) : !!e && this.Do(t).next((() => !0)))))).catch((t => {
            if (Vs(t)) 
            // Proceed with the existing state. Any subsequent access to
            // IndexedDB will verify the lease.
            return R("IndexedDbPersistence", "Failed to extend owner lease: ", t), this.isPrimary;
            if (!this.allowTabSynchronization) throw t;
            return R("IndexedDbPersistence", "Releasing owner lease after error during lease refresh", t), 
            /* isPrimary= */ !1;
        })).then((t => {
            this.isPrimary !== t && this.eo.bo((() => this.ho(t))), this.isPrimary = t;
        }));
    }
    po(t) {
        return er(t).get($s.key).next((t => As.resolve(this.Co(t))));
    }
    xo(t) {
        return nr(t).delete(this.clientId);
    }
    /**
     * If the garbage collection threshold has passed, prunes the
     * RemoteDocumentChanges and the ClientMetadata store based on the last update
     * time of all clients.
     */    async No() {
        if (this.isPrimary && !this.Oo(this.uo, 18e5)) {
            this.uo = Date.now();
            const t = await this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", (t => {
                const e = ni(t, Ys.store);
                return e.os().next((t => {
                    const n = this.Fo(t, 18e5), s = t.filter((t => -1 === n.indexOf(t)));
                    // Delete metadata for clients that are no longer considered active.
                    return As.forEach(s, (t => e.delete(t.clientId))).next((() => s));
                }));
            })).catch((() => []));
            // Delete potential leftover entries that may continue to mark the
            // inactive clients as zombied in LocalStorage.
            // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for
            // the client atomically, but we can't. So we opt to delete the IndexedDb
            // entries first to avoid potentially reviving a zombied client.
                        if (this.To) for (const e of t) this.To.removeItem(this.ko(e.clientId));
        }
    }
    /**
     * Schedules a recurring timer to update the client metadata and to either
     * extend or acquire the primary lease if the client is eligible.
     */    Ro() {
        this.ao = this.eo.Ir("client_metadata_refresh" /* ClientMetadataRefresh */ , 4e3, (() => this.Io().then((() => this.No())).then((() => this.Ro()))));
    }
    /** Checks whether `client` is the local client. */    Co(t) {
        return !!t && t.ownerId === this.clientId;
    }
    /**
     * Evaluate the state of all active clients and determine whether the local
     * client is or can act as the holder of the primary lease. Returns whether
     * the client is eligible for the lease, but does not actually acquire it.
     * May return 'false' even if there is no active leaseholder and another
     * (foreground) client should become leaseholder instead.
     */    vo(t) {
        if (this.so) return As.resolve(!0);
        return er(t).get($s.key).next((e => {
            // A client is eligible for the primary lease if:
            // - its network is enabled and the client's tab is in the foreground.
            // - its network is enabled and no other client's tab is in the
            //   foreground.
            // - every clients network is disabled and the client's tab is in the
            //   foreground.
            // - every clients network is disabled and no other client's tab is in
            //   the foreground.
            // - the `forceOwningTab` setting was passed in.
            if (null !== e && this.Oo(e.leaseTimestampMs, 5e3) && !this.Mo(e.ownerId)) {
                if (this.Co(e) && this.networkEnabled) return !0;
                if (!this.Co(e)) {
                    if (!e.allowTabSynchronization) 
                    // Fail the `canActAsPrimary` check if the current leaseholder has
                    // not opted into multi-tab synchronization. If this happens at
                    // client startup, we reject the Promise returned by
                    // `enablePersistence()` and the user can continue to use Firestore
                    // with in-memory persistence.
                    // If this fails during a lease refresh, we will instead block the
                    // AsyncQueue from executing further operations. Note that this is
                    // acceptable since mixing & matching different `synchronizeTabs`
                    // settings is not supported.
                    // TODO(b/114226234): Remove this check when `synchronizeTabs` can
                    // no longer be turned off.
                    throw new F(O.FAILED_PRECONDITION, Zi);
                    return !1;
                }
            }
            return !(!this.networkEnabled || !this.inForeground) || nr(t).os().next((t => void 0 === this.Fo(t, 5e3).find((t => {
                if (this.clientId !== t.clientId) {
                    const e = !this.networkEnabled && t.networkEnabled, n = !this.inForeground && t.inForeground, s = this.networkEnabled === t.networkEnabled;
                    if (e || n && s) return !0;
                }
                return !1;
            }))));
        })).next((t => (this.isPrimary !== t && R("IndexedDbPersistence", `Client ${t ? "is" : "is not"} eligible for a primary lease.`), 
        t)));
    }
    async Lo() {
        // The shutdown() operations are idempotent and can be called even when
        // start() aborted (e.g. because it couldn't acquire the persistence lease).
        this.ro = !1, this.$o(), this.ao && (this.ao.cancel(), this.ao = null), this.Bo(), 
        this.qo(), 
        // Use `SimpleDb.runTransaction` directly to avoid failing if another tab
        // has obtained the primary lease.
        await this._o.runTransaction("shutdown", "readwrite", [ $s.store, Ys.store ], (t => {
            const e = new ei(t, z.U);
            return this.So(e).next((() => this.xo(e)));
        })), this._o.close(), 
        // Remove the entry marking the client as zombied from LocalStorage since
        // we successfully deleted its metadata from IndexedDb.
        this.Uo();
    }
    /**
     * Returns clients that are not zombied and have an updateTime within the
     * provided threshold.
     */    Fo(t, e) {
        return t.filter((t => this.Oo(t.updateTimeMs, e) && !this.Mo(t.clientId)));
    }
    /**
     * Returns the IDs of the clients that are currently active. If multi-tab
     * is not supported, returns an array that only contains the local client's
     * ID.
     *
     * PORTING NOTE: This is only used for Web multi-tab.
     */    Qo() {
        return this.runTransaction("getActiveClients", "readonly", (t => nr(t).os().next((t => this.Fo(t, 18e5).map((t => t.clientId))))));
    }
    get Tr() {
        return this.ro;
    }
    Ko(t) {
        return Di.Ai(t, this.Kt, this.Ti, this.Ii);
    }
    Dr() {
        return this.fo;
    }
    Fr() {
        return this.wo;
    }
    jo() {
        return this.Ti;
    }
    Wo() {
        return this.Eo;
    }
    runTransaction(t, e, n) {
        R("IndexedDbPersistence", "Starting transaction:", t);
        const s = "readonly" === e ? "readonly" : "readwrite";
        let i;
        // Do all transactions as readwrite against all object stores, since we
        // are the only reader/writer.
                return this._o.runTransaction(t, s, ti, (s => (i = new ei(s, this.io ? this.io.next() : z.U), 
        "readwrite-primary" === e ? this.po(i).next((t => !!t || this.vo(i))).next((e => {
            if (!e) throw P(`Failed to obtain primary lease for action '${t}'.`), this.isPrimary = !1, 
            this.eo.bo((() => this.ho(!1))), new F(O.FAILED_PRECONDITION, xs);
            return n(i);
        })).next((t => this.Do(i).next((() => t)))) : this.Go(i).next((() => n(i)))))).then((t => (i.ps(), 
        t)));
    }
    /**
     * Verifies that the current tab is the primary leaseholder or alternatively
     * that the leaseholder has opted into multi-tab synchronization.
     */
    // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer
    // be turned off.
    Go(t) {
        return er(t).get($s.key).next((t => {
            if (null !== t && this.Oo(t.leaseTimestampMs, 5e3) && !this.Mo(t.ownerId) && !this.Co(t) && !(this.so || this.allowTabSynchronization && t.allowTabSynchronization)) throw new F(O.FAILED_PRECONDITION, Zi);
        }));
    }
    /**
     * Obtains or extends the new primary lease for the local client. This
     * method does not verify that the client is eligible for this lease.
     */    Do(t) {
        const e = new $s(this.clientId, this.allowTabSynchronization, Date.now());
        return er(t).put($s.key, e);
    }
    static jn() {
        return Ps.jn();
    }
    /** Checks the primary lease and removes it if we are the current primary. */    So(t) {
        const e = er(t);
        return e.get($s.key).next((t => this.Co(t) ? (R("IndexedDbPersistence", "Releasing primary lease."), 
        e.delete($s.key)) : As.resolve()));
    }
    /** Verifies that `updateTimeMs` is within `maxAgeMs`. */    Oo(t, e) {
        const n = Date.now();
        return !(t < n - e) && (!(t > n) || (P(`Detected an update time that is in the future: ${t} > ${n}`), 
        !1));
    }
    mo() {
        null !== this.document && "function" == typeof this.document.addEventListener && (this.co = () => {
            this.eo.ys((() => (this.inForeground = "visible" === this.document.visibilityState, 
            this.Io())));
        }, this.document.addEventListener("visibilitychange", this.co), this.inForeground = "visible" === this.document.visibilityState);
    }
    Bo() {
        this.co && (this.document.removeEventListener("visibilitychange", this.co), this.co = null);
    }
    /**
     * Attaches a window.unload handler that will synchronously write our
     * clientId to a "zombie client id" location in LocalStorage. This can be used
     * by tabs trying to acquire the primary lease to determine that the lease
     * is no longer valid even if the timestamp is recent. This is particularly
     * important for the refresh case (so the tab correctly re-acquires the
     * primary lease). LocalStorage is used for this rather than IndexedDb because
     * it is a synchronous API and so can be used reliably from  an unload
     * handler.
     */    Ao() {
        var t;
        "function" == typeof (null === (t = this.window) || void 0 === t ? void 0 : t.addEventListener) && (this.oo = () => {
            // Note: In theory, this should be scheduled on the AsyncQueue since it
            // accesses internal state. We execute this code directly during shutdown
            // to make sure it gets a chance to run.
            this.$o(), this.eo.ys((() => this.Lo()));
        }, this.window.addEventListener("unload", this.oo));
    }
    qo() {
        this.oo && (this.window.removeEventListener("unload", this.oo), this.oo = null);
    }
    /**
     * Returns whether a client is "zombied" based on its LocalStorage entry.
     * Clients become zombied when their tab closes without running all of the
     * cleanup logic in `shutdown()`.
     */    Mo(t) {
        var e;
        try {
            const n = null !== (null === (e = this.To) || void 0 === e ? void 0 : e.getItem(this.ko(t)));
            return R("IndexedDbPersistence", `Client '${t}' ${n ? "is" : "is not"} zombied in LocalStorage`), 
            n;
        } catch (t) {
            // Gracefully handle if LocalStorage isn't working.
            return P("IndexedDbPersistence", "Failed to get zombied client id.", t), !1;
        }
    }
    /**
     * Record client as zombied (a client that had its tab closed). Zombied
     * clients are ignored during primary tab selection.
     */    $o() {
        if (this.To) try {
            this.To.setItem(this.ko(this.clientId), String(Date.now()));
        } catch (t) {
            // Gracefully handle if LocalStorage isn't available / working.
            P("Failed to set zombie client id.", t);
        }
    }
    /** Removes the zombied client entry if it exists. */    Uo() {
        if (this.To) try {
            this.To.removeItem(this.ko(this.clientId));
        } catch (t) {
            // Ignore
        }
    }
    ko(t) {
        return `firestore_zombie_${this.persistenceKey}_${t}`;
    }
}

/**
 * Helper to get a typed SimpleDbStore for the primary client object store.
 */ function er(t) {
    return ni(t, $s.store);
}

/**
 * Helper to get a typed SimpleDbStore for the client metadata object store.
 */ function nr(t) {
    return ni(t, Ys.store);
}

/**
 * Generates a string used as a prefix when storing data in IndexedDB and
 * LocalStorage.
 */ function sr(t, e) {
    // Use two different prefix formats:
    //   * firestore / persistenceKey / projectID . databaseID / ...
    //   * firestore / persistenceKey / projectID / ...
    // projectIDs are DNS-compatible names and cannot contain dots
    // so there's no danger of collisions.
    let n = t.projectId;
    return t.m || (n += "." + t.database), "firestore/" + e + "/" + n + "/";
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class ir {
    constructor(t, e) {
        this.progress = t, this.zo = e;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A readonly view of the local state of all documents we're tracking (i.e. we
 * have a cached version in remoteDocumentCache or local mutations for the
 * document). The view is computed by applying the mutations in the
 * MutationQueue to the RemoteDocumentCache.
 */ class rr {
    constructor(t, e, n) {
        this.wo = t, this.Ho = e, this.Ti = n;
    }
    /**
     * Get the local view of the document identified by `key`.
     *
     * @returns Local view of the document or null if we don't have any cached
     * state for it.
     */    Jo(t, e) {
        return this.Ho.vi(t, e).next((n => this.Yo(t, e, n)));
    }
    /** Internal version of `getDocument` that allows reusing batches. */    Yo(t, e, n) {
        return this.wo.fi(t, e).next((t => {
            for (const s of n) t = s.xs(e, t);
            return t;
        }));
    }
    // Returns the view of the given `docs` as they would appear after applying
    // all mutations in the given `batches`.
    Xo(t, e, n) {
        let s = wn();
        return e.forEach(((t, e) => {
            for (const s of n) e = s.xs(t, e);
            s = s.Ht(t, e);
        })), s;
    }
    /**
     * Gets the local view of the documents identified by `keys`.
     *
     * If we don't have cached state for a document in `keys`, a NoDocument will
     * be stored for that key in the resulting set.
     */    Zo(t, e) {
        return this.wo.getEntries(t, e).next((e => this.tc(t, e)));
    }
    /**
     * Similar to `getDocuments`, but creates the local view from the given
     * `baseDocs` without retrieving documents from the local store.
     */    tc(t, e) {
        return this.Ho.Si(t, e).next((n => {
            const s = this.Xo(t, e, n);
            let i = dn();
            return s.forEach(((t, e) => {
                // TODO(http://b/32275378): Don't conflate missing / deleted.
                e || (e = new Ot(t, J.min())), i = i.Ht(t, e);
            })), i;
        }));
    }
    /**
     * Performs a query against the local view of all documents.
     *
     * @param transaction - The persistence transaction.
     * @param query - The query to match documents against.
     * @param sinceReadTime - If not set to SnapshotVersion.min(), return only
     *     documents that have been read since this snapshot version (exclusive).
     */    jr(t, e, n) {
        /**
 * Returns whether the query matches a single document by path (rather than a
 * collection).
 */
        return function(t) {
            return et.Et(t.path) && null === t.collectionGroup && 0 === t.filters.length;
        }(e) ? this.ec(t, e.path) : le(e) ? this.nc(t, e, n) : this.sc(t, e, n);
    }
    ec(t, e) {
        // Just do a simple document lookup.
        return this.Jo(t, new et(e)).next((t => {
            let e = Tn();
            return t instanceof Nt && (e = e.Ht(t.key, t)), e;
        }));
    }
    nc(t, e, n) {
        const s = e.collectionGroup;
        let i = Tn();
        return this.Ti.Qs(t, s).next((r => As.forEach(r, (r => {
            const o = function(t, e) {
                return new ie(e, 
                /*collectionGroup=*/ null, t.Nt.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
            }
            /**
 * Returns true if this query does not specify any query constraints that
 * could remove results.
 */ (e, r.child(s));
            return this.sc(t, o, n).next((t => {
                t.forEach(((t, e) => {
                    i = i.Ht(t, e);
                }));
            }));
        })).next((() => i))));
    }
    sc(t, e, n) {
        // Query the remote documents and overlay mutations.
        let s, i;
        return this.wo.jr(t, e, n).next((n => (s = n, this.Ho.Ci(t, e)))).next((e => (i = e, 
        this.ic(t, i, s).next((t => {
            s = t;
            for (const t of i) for (const e of t.mutations) {
                const n = e.key, i = s.get(n), r = Ke(e, i, 0, t.Ss);
                s = r instanceof Nt ? s.Ht(n, r) : s.remove(n);
            }
        }))))).next((() => (
        // Finally, filter out any documents that don't actually match
        // the query.
        s.forEach(((t, n) => {
            Ie(e, n) || (s = s.remove(t));
        })), s)));
    }
    ic(t, e, n) {
        let s = Rn();
        for (const t of e) for (const e of t.mutations) e instanceof He && null === n.get(e.key) && (s = s.add(e.key));
        let i = n;
        return this.wo.getEntries(t, s).next((t => (t.forEach(((t, e) => {
            null !== e && e instanceof Nt && (i = i.Ht(t, e));
        })), i)));
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A set of changes to what documents are currently in view and out of view for
 * a given query. These changes are sent to the LocalStore by the View (via
 * the SyncEngine) and are used to pin / unpin documents as appropriate.
 */ class or {
    constructor(t, e, n, s) {
        this.targetId = t, this.fromCache = e, this.rc = n, this.oc = s;
    }
    static cc(t, e) {
        let n = Rn(), s = Rn();
        for (const t of e.docChanges) switch (t.type) {
          case 0 /* Added */ :
            n = n.add(t.doc.key);
            break;

          case 1 /* Removed */ :
            s = s.add(t.doc.key);
 // do nothing
                }
        return new or(t, e.fromCache, n, s);
    }
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A query engine that takes advantage of the target document mapping in the
 * QueryCache. Query execution is optimized by only reading the documents that
 * previously matched a query plus any documents that were edited after the
 * query was last listened to.
 *
 * There are some cases when this optimization is not guaranteed to produce
 * the same results as full collection scans. In these cases, query
 * processing falls back to full scans. These cases are:
 *
 * - Limit queries where a document that matched the query previously no longer
 *   matches the query.
 *
 * - Limit queries where a document edit may cause the document to sort below
 *   another document that is in the local cache.
 *
 * - Queries that have never been CURRENT or free of limbo documents.
 */ class cr {
    /** Sets the document view to query against. */
    ac(t) {
        this.uc = t;
    }
    /** Returns all local documents matching the specified query. */    jr(t, e, n, s) {
        // Queries that match all documents don't benefit from using
        // key-based lookups. It is more efficient to scan all documents in a
        // collection, rather than to perform individual lookups.
        return function(t) {
            return 0 === t.filters.length && null === t.limit && null == t.startAt && null == t.endAt && (0 === t.Nt.length || 1 === t.Nt.length && t.Nt[0].field.ht());
        }(e) || n.isEqual(J.min()) ? this.hc(t, e) : this.uc.Zo(t, s).next((i => {
            const r = this.lc(e, i);
            return (ce(e) || ae(e)) && this._c(e.limitType, r, s, n) ? this.hc(t, e) : (A() <= u.DEBUG && R("QueryEngine", "Re-using previous result from %s to execute query: %s", n.toString(), Te(e)), 
            this.uc.jr(t, e, n).next((t => (
            // We merge `previousResults` into `updateResults`, since
            // `updateResults` is already a DocumentMap. If a document is
            // contained in both lists, then its contents are the same.
            r.forEach((e => {
                t = t.Ht(e.key, e);
            })), t))));
        }));
        // Queries that have never seen a snapshot without limbo free documents
        // should also be run as a full collection scan.
        }
    /** Applies the query filter and sorting to the provided documents.  */    lc(t, e) {
        // Sort the documents and re-apply the query filter since previously
        // matching documents do not necessarily still match the query.
        let n = new ln(me(t));
        return e.forEach(((e, s) => {
            s instanceof Nt && Ie(t, s) && (n = n.add(s));
        })), n;
    }
    /**
     * Determines if a limit query needs to be refilled from cache, making it
     * ineligible for index-free execution.
     *
     * @param sortedPreviousResults - The documents that matched the query when it
     * was last synchronized, sorted by the query's comparator.
     * @param remoteKeys - The document keys that matched the query at the last
     * snapshot.
     * @param limboFreeSnapshotVersion - The version of the snapshot when the
     * query was last synchronized.
     */    _c(t, e, n, s) {
        // The query needs to be refilled if a previously matching document no
        // longer matches.
        if (n.size !== e.size) return !0;
        // Limit queries are not eligible for index-free query execution if there is
        // a potential that an older document from cache now sorts before a document
        // that was previously part of the limit. This, however, can only happen if
        // the document at the edge of the limit goes out of limit.
        // If a document that is not the limit boundary sorts differently,
        // the boundary of the limit itself did not change and documents from cache
        // will continue to be "rejected" by this boundary. Therefore, we can ignore
        // any modifications that don't affect the last document.
                const i = "F" /* First */ === t ? e.last() : e.first();
        return !!i && (i.hasPendingWrites || i.version.u(s) > 0);
    }
    hc(t, e) {
        return A() <= u.DEBUG && R("QueryEngine", "Using full collection scan to execute query:", Te(e)), 
        this.uc.jr(t, e, J.min());
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Implements `LocalStore` interface.
 *
 * Note: some field defined in this class might have public access level, but
 * the class is not exported so they are only accessible from this module.
 * This is useful to implement optional features (like bundles) in free
 * functions, such that they are tree-shakeable.
 */
class ar {
    constructor(
    /** Manages our in-memory or durable persistence. */
    t, e, n, s) {
        this.persistence = t, this.fc = e, this.Kt = s, 
        /**
         * Maps a targetID to data about its target.
         *
         * PORTING NOTE: We are using an immutable data structure on Web to make re-runs
         * of `applyRemoteEvent()` idempotent.
         */
        this.dc = new an(D), 
        /** Maps a target to its targetID. */
        // TODO(wuandy): Evaluate if TargetId can be part of Target.
        this.wc = new pi((t => Lt(t)), Bt), 
        /**
         * The read time of the last entry processed by `getNewDocumentChanges()`.
         *
         * PORTING NOTE: This is only used for multi-tab synchronization.
         */
        this.Ec = J.min(), this.Ho = t.Ko(n), this.Tc = t.Fr(), this.fo = t.Dr(), this.Ic = new rr(this.Tc, this.Ho, this.persistence.jo()), 
        this.Eo = t.Wo(), this.fc.ac(this.Ic);
    }
    mr(t) {
        return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (e => t.pr(e, this.dc)));
    }
}

function ur(
/** Manages our in-memory or durable persistence. */
t, e, n, s) {
    return new ar(t, e, n, s);
}

/**
 * Tells the LocalStore that the currently authenticated user has changed.
 *
 * In response the local store switches the mutation queue to the new user and
 * returns any resulting document changes.
 */
// PORTING NOTE: Android and iOS only return the documents affected by the
// change.
async function hr(t, e) {
    const n = b(t);
    let s = n.Ho, i = n.Ic;
    const r = await n.persistence.runTransaction("Handle user change", "readonly", (t => {
        // Swap out the mutation queue, grabbing the pending mutation batches
        // before and after.
        let r;
        return n.Ho.bi(t).next((o => (r = o, s = n.persistence.Ko(e), 
        // Recreate our LocalDocumentsView using the new
        // MutationQueue.
        i = new rr(n.Tc, s, n.persistence.jo()), s.bi(t)))).next((e => {
            const n = [], s = [];
            // Union the old/new changed keys.
            let o = Rn();
            for (const t of r) {
                n.push(t.batchId);
                for (const e of t.mutations) o = o.add(e.key);
            }
            for (const t of e) {
                s.push(t.batchId);
                for (const e of t.mutations) o = o.add(e.key);
            }
            // Return the set of all (potentially) changed documents and the list
            // of mutation batch IDs that were affected by change.
                        return i.Zo(t, o).next((t => ({
                mc: t,
                Ac: n,
                Rc: s
            })));
        }));
    }));
    return n.Ho = s, n.Ic = i, n.fc.ac(n.Ic), r;
}

/* Accepts locally generated Mutations and commit them to storage. */
/**
 * Acknowledges the given batch.
 *
 * On the happy path when a batch is acknowledged, the local store will
 *
 *  + remove the batch from the mutation queue;
 *  + apply the changes to the remote document cache;
 *  + recalculate the latency compensated view implied by those changes (there
 *    may be mutations in the queue that affect the documents but haven't been
 *    acknowledged yet); and
 *  + give the changed documents back the sync engine
 *
 * @returns The resulting (modified) documents.
 */
function lr(t, e) {
    const n = b(t);
    return n.persistence.runTransaction("Acknowledge batch", "readwrite-primary", (t => {
        const s = e.batch.keys(), i = n.Tc.Or({
            Wr: !0
        });
        return function(t, e, n, s) {
            const i = n.batch, r = i.keys();
            let o = As.resolve();
            return r.forEach((t => {
                o = o.next((() => s.fi(e, t))).next((e => {
                    let r = e;
                    const o = n.Fs.get(t);
                    p(null !== o), (!r || r.version.u(o) < 0) && (r = i.Ds(t, r, n), r && 
                    // We use the commitVersion as the readTime rather than the
                    // document's updateTime since the updateTime is not advanced
                    // for updates that do not modify the underlying document.
                    s.ui(r, n.Os));
                }));
            })), o.next((() => t.Ho.xi(e, i)));
        }
        /** Returns the local view of the documents affected by a mutation batch. */
        // PORTING NOTE: Multi-Tab only.
        (n, t, e, i).next((() => i.apply(t))).next((() => n.Ho.Fi(t))).next((() => n.Ic.Zo(t, s)));
    }));
}

/**
 * Removes mutations from the MutationQueue for the specified batch;
 * LocalDocuments will be recalculated.
 *
 * @returns The resulting modified documents.
 */
/**
 * Returns the last consistent snapshot processed (used by the RemoteStore to
 * determine whether to buffer incoming snapshots from the backend).
 */
function _r(t) {
    const e = b(t);
    return e.persistence.runTransaction("Get last remote snapshot version", "readonly", (t => e.fo.Ki(t)));
}

/**
 * Updates the "ground-state" (remote) documents. We assume that the remote
 * event reflects any write batches that have been acknowledged or rejected
 * (i.e. we do not re-apply local mutations to updates from this event).
 *
 * LocalDocuments are re-calculated if there are remaining mutations in the
 * queue.
 */ function fr(t, e) {
    const n = b(t), s = e.Mt;
    let i = n.dc;
    return n.persistence.runTransaction("Apply remote event", "readwrite-primary", (t => {
        const r = n.Tc.Or({
            Wr: !0
        });
        // Reset newTargetDataByTargetMap in case this transaction gets re-run.
                i = n.dc;
        const o = [];
        e.Fe.forEach(((e, r) => {
            const c = i.get(r);
            if (!c) return;
            // Only update the remote keys if the target is still active. This
            // ensures that we can persist the updated target data along with
            // the updated assignment.
                        o.push(n.fo.ir(t, e.Ke, r).next((() => n.fo.nr(t, e.Ue, r))));
            const a = e.resumeToken;
            // Update the resume token if the change includes one.
                        if (a.o() > 0) {
                const u = c.$t(a, s).Lt(t.vs);
                i = i.Ht(r, u), 
                // Update the target data if there are target changes (or if
                // sufficient time has passed since the last update).
                /**
 * Returns true if the newTargetData should be persisted during an update of
 * an active target. TargetData should always be persisted when a target is
 * being released and should not call this function.
 *
 * While the target is active, TargetData updates can be omitted when nothing
 * about the target has changed except metadata like the resume token or
 * snapshot version. Occasionally it's worth the extra write to prevent these
 * values from getting too stale after a crash, but this doesn't have to be
 * too frequent.
 */
                function(t, e, n) {
                    // Always persist target data if we don't already have a resume token.
                    if (p(e.resumeToken.o() > 0), 0 === t.resumeToken.o()) return !0;
                    // Don't allow resume token changes to be buffered indefinitely. This
                    // allows us to be reasonably up-to-date after a crash and avoids needing
                    // to loop over all active queries on shutdown. Especially in the browser
                    // we may not get time to do anything interesting while the current tab is
                    // closing.
                                        if (e.Mt.W() - t.Mt.W() >= 3e8) return !0;
                    // Otherwise if the only thing that has changed about a target is its resume
                    // token it's not worth persisting. Note that the RemoteStore keeps an
                    // in-memory view of the currently active targets which includes the current
                    // resume token, so stream failure or user changes will still use an
                    // up-to-date resume token regardless of what we do here.
                                        return n.Ue.size + n.Qe.size + n.Ke.size > 0;
                }
                /**
 * Notifies local store of the changed views to locally pin documents.
 */ (c, u, e) && o.push(n.fo.Ji(t, u));
            }
        }));
        let c = dn();
        // HACK: The only reason we allow a null snapshot version is so that we
        // can synthesize remote events when we get permission denied errors while
        // trying to resolve the state of a locally cached document that is in
        // limbo.
        if (e.Me.forEach(((s, i) => {
            e.Le.has(s) && o.push(n.persistence.Ii.kr(t, s));
        })), 
        // Each loop iteration only affects its "own" doc, so it's safe to get all the remote
        // documents in advance in a single call.
        o.push(dr(t, r, e.Me, s, void 0).next((t => {
            c = t;
        }))), !s.isEqual(J.min())) {
            const e = n.fo.Ki(t).next((e => n.fo.Wi(t, t.vs, s)));
            o.push(e);
        }
        return As.$n(o).next((() => r.apply(t))).next((() => n.Ic.tc(t, c)));
    })).then((t => (n.dc = i, t)));
}

/**
 * Populates document change buffer with documents from backend or a bundle.
 * Returns the document changes resulting from applying those documents.
 *
 * @param txn - Transaction to use to read existing documents from storage.
 * @param documentBuffer - Document buffer to collect the resulted changes to be
 *        applied to storage.
 * @param documents - Documents to be applied.
 * @param globalVersion - A `SnapshotVersion` representing the read time if all
 *        documents have the same read time.
 * @param documentVersions - A DocumentKey-to-SnapshotVersion map if documents
 *        have their own read time.
 *
 * Note: this function will use `documentVersions` if it is defined;
 * when it is not defined, resorts to `globalVersion`.
 */ function dr(t, e, n, s, 
// TODO(wuandy): We could add `readTime` to MaybeDocument instead to remove
// this parameter.
i) {
    let r = Rn();
    return n.forEach((t => r = r.add(t))), e.getEntries(t, r).next((t => {
        let r = dn();
        return n.forEach(((n, o) => {
            const c = t.get(n), a = (null == i ? void 0 : i.get(n)) || s;
            // Note: The order of the steps below is important, since we want
            // to ensure that rejected limbo resolutions (which fabricate
            // NoDocuments with SnapshotVersion.min()) never add documents to
            // cache.
            o instanceof Ot && o.version.isEqual(J.min()) ? (
            // NoDocuments with SnapshotVersion.min() are used in manufactured
            // events. We remove these documents from cache since we lost
            // access.
            e._i(n, a), r = r.Ht(n, o)) : null == c || o.version.u(c.version) > 0 || 0 === o.version.u(c.version) && c.hasPendingWrites ? (e.ui(o, a), 
            r = r.Ht(n, o)) : R("LocalStore", "Ignoring outdated watch update for ", n, ". Current version:", c.version, " Watch version:", o.version);
        })), r;
    }));
}

/**
 * Gets the mutation batch after the passed in batchId in the mutation queue
 * or null if empty.
 * @param afterBatchId - If provided, the batch to search after.
 * @returns The next mutation or null if there wasn't one.
 */
function wr(t, e) {
    const n = b(t);
    return n.persistence.runTransaction("Get next mutation batch", "readonly", (t => (void 0 === e && (e = -1), 
    n.Ho.Vi(t, e))));
}

/**
 * Reads the current value of a Document with a given key or null if not
 * found - used for testing.
 */
/**
 * Assigns the given target an internal ID so that its results can be pinned so
 * they don't get GC'd. A target must be allocated in the local store before
 * the store can be used to manage its view.
 *
 * Allocating an already allocated `Target` will return the existing `TargetData`
 * for that `Target`.
 */
function Er(t, e) {
    const n = b(t);
    return n.persistence.runTransaction("Allocate target", "readwrite", (t => {
        let s;
        return n.fo.er(t, e).next((i => i ? (
        // This target has been listened to previously, so reuse the
        // previous targetID.
        // TODO(mcg): freshen last accessed date?
        s = i, As.resolve(s)) : n.fo.qi(t).next((i => (s = new Re(e, i, 0 /* Listen */ , t.vs), 
        n.fo.Gi(t, s).next((() => s)))))));
    })).then((t => {
        // If Multi-Tab is enabled, the existing target data may be newer than
        // the in-memory data
        const s = n.dc.get(t.targetId);
        return (null === s || t.Mt.u(s.Mt) > 0) && (n.dc = n.dc.Ht(t.targetId, t), n.wc.set(e, t.targetId)), 
        t;
    }));
}

/**
 * Returns the TargetData as seen by the LocalStore, including updates that may
 * have not yet been persisted to the TargetCache.
 */
// Visible for testing.
/**
 * Unpins all the documents associated with the given target. If
 * `keepPersistedTargetData` is set to false and Eager GC enabled, the method
 * directly removes the associated target data from the target cache.
 *
 * Releasing a non-existing `Target` is a no-op.
 */
// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.
async function Tr(t, e, n) {
    const s = b(t), i = s.dc.get(e), r = n ? "readwrite" : "readwrite-primary";
    try {
        n || await s.persistence.runTransaction("Release target", r, (t => s.persistence.Ii.removeTarget(t, i)));
    } catch (t) {
        if (!Vs(t)) throw t;
        // All `releaseTarget` does is record the final metadata state for the
        // target, but we've been recording this periodically during target
        // activity. If we lose this write this could cause a very slight
        // difference in the order of target deletion during GC, but we
        // don't define exact LRU semantics so this is acceptable.
        R("LocalStore", `Failed to update sequence numbers for target ${e}: ${t}`);
    }
    s.dc = s.dc.remove(e), s.wc.delete(i.target);
}

/**
 * Runs the specified query against the local store and returns the results,
 * potentially taking advantage of query data from previous executions (such
 * as the set of remote keys).
 *
 * @param usePreviousResults - Whether results from previous executions can
 * be used to optimize this query execution.
 */ function Ir(t, e, n) {
    const s = b(t);
    let i = J.min(), r = Rn();
    return s.persistence.runTransaction("Execute query", "readonly", (t => function(t, e, n) {
        const s = b(t), i = s.wc.get(n);
        return void 0 !== i ? As.resolve(s.dc.get(i)) : s.fo.er(e, n);
    }(s, t, fe(e)).next((e => {
        if (e) return i = e.lastLimboFreeSnapshotVersion, s.fo.cr(t, e.targetId).next((t => {
            r = t;
        }));
    })).next((() => s.fc.jr(t, e, n ? i : J.min(), n ? r : Rn()))).next((t => ({
        documents: t,
        Pc: r
    })))));
}

// PORTING NOTE: Multi-Tab only.
function mr(t, e) {
    const n = b(t), s = b(n.fo), i = n.dc.get(e);
    return i ? Promise.resolve(i.target) : n.persistence.runTransaction("Get target data", "readonly", (t => s.Dn(t, e).next((t => t ? t.target : null))));
}

/**
 * Returns the set of documents that have been updated since the last call.
 * If this is the first call, returns the set of changes since client
 * initialization. Further invocations will return document that have changed
 * since the prior call.
 */
// PORTING NOTE: Multi-Tab only.
function Ar(t) {
    const e = b(t);
    return e.persistence.runTransaction("Get new document changes", "readonly", (t => function(t, e, n) {
        const s = b(t);
        let i = dn(), r = ai(n);
        const o = Hi(e), c = IDBKeyRange.lowerBound(r, !0);
        return o.ls({
            index: js.readTimeIndex,
            range: c
        }, ((t, e) => {
            // Unlike `getEntry()` and others, `getNewDocumentChanges()` parses
            // the documents directly since we want to keep sentinel deletes.
            const n = oi(s.Kt, e);
            i = i.Ht(n.key, n), r = e.readTime;
        })).next((() => ({
            zo: i,
            readTime: ui(r)
        })));
    }
    /**
 * Returns the read time of the most recently read document in the cache, or
 * SnapshotVersion.min() if not available.
 */
    // PORTING NOTE: This is only used for multi-tab synchronization.
    (e.Tc, t, e.Ec))).then((({zo: t, readTime: n}) => (e.Ec = n, t)));
}

/**
 * Reads the newest document change from persistence and moves the internal
 * synchronization marker forward so that calls to `getNewDocumentChanges()`
 * only return changes that happened after client initialization.
 */
// PORTING NOTE: Multi-Tab only.
async function Rr(t) {
    const e = b(t);
    return e.persistence.runTransaction("Synchronize last document change read time", "readonly", (t => function(t) {
        const e = Hi(t);
        // If there are no existing entries, we return SnapshotVersion.min().
                let n = J.min();
        return e.ls({
            index: js.readTimeIndex,
            reverse: !0
        }, ((t, e, s) => {
            e.readTime && (n = ui(e.readTime)), s.done();
        })).next((() => n));
    }(t))).then((t => {
        e.Ec = t;
    }));
}

/**
 * Creates a new target using the given bundle name, which will be used to
 * hold the keys of all documents from the bundle in query-document mappings.
 * This ensures that the loaded documents do not get garbage collected
 * right away.
 */
/**
 * Applies the documents from a bundle to the "ground-state" (remote)
 * documents.
 *
 * LocalDocuments are re-calculated if there are remaining mutations in the
 * queue.
 */
async function Pr(t, e, n, s) {
    const i = b(t);
    let r = Rn(), o = dn(), c = mn();
    for (const t of n) {
        const n = e.yc(t.metadata.name);
        t.document && (r = r.add(n)), o = o.Ht(n, e.gc(t)), c = c.Ht(n, e.Vc(t.metadata.readTime));
    }
    const a = i.Tc.Or({
        Wr: !0
    }), u = await Er(i, function(t) {
        // It is OK that the path used for the query is not valid, because this will
        // not be read and queried.
        return fe(oe(X.ct("__bundle__/docs/" + t)));
    }(s));
    // Allocates a target to hold all document keys from the bundle, such that
    // they will not get garbage collected right away.
        return i.persistence.runTransaction("Apply bundle documents", "readwrite", (t => dr(t, a, o, J.min(), c).next((e => (a.apply(t), 
    e))).next((e => i.fo.Xi(t, u.targetId).next((() => i.fo.nr(t, r, u.targetId))).next((() => i.Ic.tc(t, e)))))));
}

/**
 * Returns a promise of a boolean to indicate if the given bundle has already
 * been loaded and the create time is newer than the current loading bundle.
 */
/**
 * Saves the given `NamedQuery` to local persistence.
 */
async function yr(t, e, n = Rn()) {
    // Allocate a target for the named query such that it can be resumed
    // from associated read time if users use it to listen.
    // NOTE: this also means if no corresponding target exists, the new target
    // will remain active and will not get collected, unless users happen to
    // unlisten the query somehow.
    const s = await Er(t, fe(wi(e.bundledQuery))), i = b(t);
    return i.persistence.runTransaction("Save named query", "readwrite", (t => {
        const r = Un(e.readTime);
        // Simply save the query itself if it is older than what the SDK already
        // has.
                if (s.Mt.u(r) >= 0) return i.Eo.Bs(t, e);
        // Update existing target data because the query from the bundle is newer.
                const o = s.$t(N.h, r);
        return i.dc = i.dc.Ht(o.targetId, o), i.fo.Ji(t, o).next((() => i.fo.Xi(t, s.targetId))).next((() => i.fo.nr(t, n, s.targetId))).next((() => i.Eo.Bs(t, e)));
    }));
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class gr {
    constructor(t) {
        this.Kt = t, this.bc = new Map, this.vc = new Map;
    }
    Ms(t, e) {
        return As.resolve(this.bc.get(e));
    }
    Ls(t, e) {
        /** Decodes a BundleMetadata proto into a BundleMetadata object. */
        var n;
        return this.bc.set(e.id, {
            id: (n = e).id,
            version: n.version,
            createTime: Un(n.createTime)
        }), As.resolve();
    }
    $s(t, e) {
        return As.resolve(this.vc.get(e));
    }
    Bs(t, e) {
        return this.vc.set(e.name, function(t) {
            return {
                name: t.name,
                query: wi(t.bundledQuery),
                readTime: Un(t.readTime)
            };
        }(e)), As.resolve();
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A collection of references to a document from some kind of numbered entity
 * (either a target ID or batch ID). As references are added to or removed from
 * the set corresponding events are emitted to a registered garbage collector.
 *
 * Each reference is represented by a DocumentReference object. Each of them
 * contains enough information to uniquely identify the reference. They are all
 * stored primarily in a set sorted by key. A document is considered garbage if
 * there's no references in that set (this can be efficiently checked thanks to
 * sorting by key).
 *
 * ReferenceSet also keeps a secondary set that contains references sorted by
 * IDs. This one is used to efficiently implement removal of all references by
 * some target ID.
 */ class Vr {
    constructor() {
        // A set of outstanding references to a document sorted by key.
        this.Sc = new ln(pr.Dc), 
        // A set of outstanding references to a document sorted by target id.
        this.Cc = new ln(pr.xc);
    }
    /** Returns true if the reference set contains no references. */    nt() {
        return this.Sc.nt();
    }
    /** Adds a reference to the given document key for the given ID. */    sr(t, e) {
        const n = new pr(t, e);
        this.Sc = this.Sc.add(n), this.Cc = this.Cc.add(n);
    }
    /** Add references to the given document keys for the given ID. */    Nc(t, e) {
        t.forEach((t => this.sr(t, e)));
    }
    /**
     * Removes a reference to the given document key for the given
     * ID.
     */    rr(t, e) {
        this.Oc(new pr(t, e));
    }
    Fc(t, e) {
        t.forEach((t => this.rr(t, e)));
    }
    /**
     * Clears all references with a given ID. Calls removeRef() for each key
     * removed.
     */    kc(t) {
        const e = new et(new X([])), n = new pr(e, t), s = new pr(e, t + 1), i = [];
        return this.Cc.Ae([ n, s ], (t => {
            this.Oc(t), i.push(t.key);
        })), i;
    }
    Mc() {
        this.Sc.forEach((t => this.Oc(t)));
    }
    Oc(t) {
        this.Sc = this.Sc.delete(t), this.Cc = this.Cc.delete(t);
    }
    Lc(t) {
        const e = new et(new X([])), n = new pr(e, t), s = new pr(e, t + 1);
        let i = Rn();
        return this.Cc.Ae([ n, s ], (t => {
            i = i.add(t.key);
        })), i;
    }
    ki(t) {
        const e = new pr(t, 0), n = this.Sc.Pe(e);
        return null !== n && t.isEqual(n.key);
    }
}

class pr {
    constructor(t, e) {
        this.key = t, this.$c = e;
    }
    /** Compare by key then by ID */    static Dc(t, e) {
        return et.J(t.key, e.key) || D(t.$c, e.$c);
    }
    /** Compare by ID then by key */    static xc(t, e) {
        return D(t.$c, e.$c) || et.J(t.key, e.key);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class br {
    constructor(t, e) {
        this.Ti = t, this.Ii = e, 
        /**
         * The set of all mutations that have been sent but not yet been applied to
         * the backend.
         */
        this.Ho = [], 
        /** Next value to use when assigning sequential IDs to each mutation batch. */
        this.Bc = 1, 
        /** An ordered mapping between documents and the mutations batch IDs. */
        this.qc = new ln(pr.Dc);
    }
    Ri(t) {
        return As.resolve(0 === this.Ho.length);
    }
    Pi(t, e, n, s) {
        const i = this.Bc;
        if (this.Bc++, this.Ho.length > 0) {
            this.Ho[this.Ho.length - 1];
        }
        const r = new si(i, e, n, s);
        this.Ho.push(r);
        // Track references by document key and index collection parents.
        for (const e of s) this.qc = this.qc.add(new pr(e.key, i)), this.Ti.Us(t, e.key.path.Z());
        return As.resolve(r);
    }
    yi(t, e) {
        return As.resolve(this.Uc(e));
    }
    Vi(t, e) {
        const n = e + 1, s = this.Qc(n), i = s < 0 ? 0 : s;
        // The requested batchId may still be out of range so normalize it to the
        // start of the queue.
                return As.resolve(this.Ho.length > i ? this.Ho[i] : null);
    }
    pi() {
        return As.resolve(0 === this.Ho.length ? -1 : this.Bc - 1);
    }
    bi(t) {
        return As.resolve(this.Ho.slice());
    }
    vi(t, e) {
        const n = new pr(e, 0), s = new pr(e, Number.POSITIVE_INFINITY), i = [];
        return this.qc.Ae([ n, s ], (t => {
            const e = this.Uc(t.$c);
            i.push(e);
        })), As.resolve(i);
    }
    Si(t, e) {
        let n = new ln(D);
        return e.forEach((t => {
            const e = new pr(t, 0), s = new pr(t, Number.POSITIVE_INFINITY);
            this.qc.Ae([ e, s ], (t => {
                n = n.add(t.$c);
            }));
        })), As.resolve(this.Kc(n));
    }
    Ci(t, e) {
        // Use the query path as a prefix for testing if a document matches the
        // query.
        const n = e.path, s = n.length + 1;
        // Construct a document reference for actually scanning the index. Unlike
        // the prefix the document key in this reference must have an even number of
        // segments. The empty segment can be used a suffix of the query path
        // because it precedes all other segments in an ordered traversal.
        let i = n;
        et.Et(i) || (i = i.child(""));
        const r = new pr(new et(i), 0);
        // Find unique batchIDs referenced by all documents potentially matching the
        // query.
                let o = new ln(D);
        return this.qc.Re((t => {
            const e = t.key.path;
            return !!n.st(e) && (
            // Rows with document keys more than one segment longer than the query
            // path can't be matches. For example, a query on 'rooms' can't match
            // the document /rooms/abc/messages/xyx.
            // TODO(mcg): we'll need a different scanner when we implement
            // ancestor queries.
            e.length === s && (o = o.add(t.$c)), !0);
        }), r), As.resolve(this.Kc(o));
    }
    Kc(t) {
        // Construct an array of matching batches, sorted by batchID to ensure that
        // multiple mutations affecting the same document key are applied in order.
        const e = [];
        return t.forEach((t => {
            const n = this.Uc(t);
            null !== n && e.push(n);
        })), e;
    }
    xi(t, e) {
        p(0 === this.jc(e.batchId, "removed")), this.Ho.shift();
        let n = this.qc;
        return As.forEach(e.mutations, (s => {
            const i = new pr(s.key, e.batchId);
            return n = n.delete(i), this.Ii.Oi(t, s.key);
        })).next((() => {
            this.qc = n;
        }));
    }
    Ni(t) {
        // No-op since the memory mutation queue does not maintain a separate cache.
    }
    ki(t, e) {
        const n = new pr(e, 0), s = this.qc.Pe(n);
        return As.resolve(e.isEqual(s && s.key));
    }
    Fi(t) {
        return this.Ho.length, As.resolve();
    }
    /**
     * Finds the index of the given batchId in the mutation queue and asserts that
     * the resulting index is within the bounds of the queue.
     *
     * @param batchId - The batchId to search for
     * @param action - A description of what the caller is doing, phrased in passive
     * form (e.g. "acknowledged" in a routine that acknowledges batches).
     */    jc(t, e) {
        return this.Qc(t);
    }
    /**
     * Finds the index of the given batchId in the mutation queue. This operation
     * is O(1).
     *
     * @returns The computed index of the batch with the given batchId, based on
     * the state of the queue. Note this index can be negative if the requested
     * batchId has already been remvoed from the queue or past the end of the
     * queue if the batchId is larger than the last added batch.
     */    Qc(t) {
        if (0 === this.Ho.length) 
        // As an index this is past the end of the queue
        return 0;
        // Examine the front of the queue to figure out the difference between the
        // batchId and indexes in the array. Note that since the queue is ordered
        // by batchId, if the first batch has a larger batchId then the requested
        // batchId doesn't exist in the queue.
                return t - this.Ho[0].batchId;
    }
    /**
     * A version of lookupMutationBatch that doesn't return a promise, this makes
     * other functions that uses this code easier to read and more efficent.
     */    Uc(t) {
        const e = this.Qc(t);
        if (e < 0 || e >= this.Ho.length) return null;
        return this.Ho[e];
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke
 * `newMemoryRemoteDocumentCache()`.
 */
class vr {
    /**
     * @param sizer - Used to assess the size of a document. For eager GC, this is
     * expected to just return 0 to avoid unnecessarily doing the work of
     * calculating the size.
     */
    constructor(t, e) {
        this.Ti = t, this.Wc = e, 
        /** Underlying cache of documents and their read times. */
        this.docs = new an(et.J), 
        /** Size of all cached documents. */
        this.size = 0;
    }
    /**
     * Adds the supplied entry to the cache and updates the cache size as appropriate.
     *
     * All calls of `addEntry`  are required to go through the RemoteDocumentChangeBuffer
     * returned by `newChangeBuffer()`.
     */    ui(t, e, n) {
        const s = e.key, i = this.docs.get(s), r = i ? i.size : 0, o = this.Wc(e);
        return this.docs = this.docs.Ht(s, {
            li: e,
            size: o,
            readTime: n
        }), this.size += o - r, this.Ti.Us(t, s.path.Z());
    }
    /**
     * Removes the specified entry from the cache and updates the cache size as appropriate.
     *
     * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
     * returned by `newChangeBuffer()`.
     */    _i(t) {
        const e = this.docs.get(t);
        e && (this.docs = this.docs.remove(t), this.size -= e.size);
    }
    fi(t, e) {
        const n = this.docs.get(e);
        return As.resolve(n ? n.li : null);
    }
    getEntries(t, e) {
        let n = wn();
        return e.forEach((t => {
            const e = this.docs.get(t);
            n = n.Ht(t, e ? e.li : null);
        })), As.resolve(n);
    }
    jr(t, e, n) {
        let s = Tn();
        // Documents are ordered by key, so we can use a prefix scan to narrow down
        // the documents we need to match the query against.
                const i = new et(e.path.child("")), r = this.docs.ne(i);
        for (;r.ae(); ) {
            const {key: t, value: {li: i, readTime: o}} = r.ce();
            if (!e.path.st(t.path)) break;
            o.u(n) <= 0 || i instanceof Nt && Ie(e, i) && (s = s.Ht(i.key, i));
        }
        return As.resolve(s);
    }
    Gc(t, e) {
        return As.forEach(this.docs, (t => e(t)));
    }
    Or(t) {
        // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps
        // a separate changelog and does not need special handling for removals.
        return new Sr(this);
    }
    Mr(t) {
        return As.resolve(this.size);
    }
}

/**
 * Creates a new memory-only RemoteDocumentCache.
 *
 * @param indexManager - A class that manages collection group indices.
 * @param sizer - Used to assess the size of a document. For eager GC, this is
 * expected to just return 0 to avoid unnecessarily doing the work of
 * calculating the size.
 */
/**
 * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.
 */
class Sr extends bi {
    constructor(t) {
        super(), this.Gr = t;
    }
    Ei(t) {
        const e = [];
        return this.oi.forEach(((n, s) => {
            s && s.li ? e.push(this.Gr.ui(t, s.li, this.ai(n))) : this.Gr._i(n);
        })), As.$n(e);
    }
    di(t, e) {
        return this.Gr.fi(t, e);
    }
    wi(t, e) {
        return this.Gr.getEntries(t, e);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class Dr {
    constructor(t) {
        this.persistence = t, 
        /**
         * Maps a target to the data about that target
         */
        this.zc = new pi((t => Lt(t)), Bt), 
        /** The last received snapshot version. */
        this.lastRemoteSnapshotVersion = J.min(), 
        /** The highest numbered target ID encountered. */
        this.highestTargetId = 0, 
        /** The highest sequence number encountered. */
        this.Hc = 0, 
        /**
         * A ordered bidirectional mapping between documents and the remote target
         * IDs.
         */
        this.Jc = new Vr, this.targetCount = 0, this.Yc = Fi.$i();
    }
    mn(t, e) {
        return this.zc.forEach(((t, n) => e(n))), As.resolve();
    }
    Ki(t) {
        return As.resolve(this.lastRemoteSnapshotVersion);
    }
    ji(t) {
        return As.resolve(this.Hc);
    }
    qi(t) {
        return this.highestTargetId = this.Yc.next(), As.resolve(this.highestTargetId);
    }
    Wi(t, e, n) {
        return n && (this.lastRemoteSnapshotVersion = n), e > this.Hc && (this.Hc = e), 
        As.resolve();
    }
    zi(t) {
        this.zc.set(t.target, t);
        const e = t.targetId;
        e > this.highestTargetId && (this.Yc = new Fi(e), this.highestTargetId = e), t.sequenceNumber > this.Hc && (this.Hc = t.sequenceNumber);
    }
    Gi(t, e) {
        return this.zi(e), this.targetCount += 1, As.resolve();
    }
    Ji(t, e) {
        return this.zi(e), As.resolve();
    }
    Yi(t, e) {
        return this.zc.delete(e.target), this.Jc.kc(e.targetId), this.targetCount -= 1, 
        As.resolve();
    }
    Zi(t, e, n) {
        let s = 0;
        const i = [];
        return this.zc.forEach(((r, o) => {
            o.sequenceNumber <= e && null === n.get(o.targetId) && (this.zc.delete(r), i.push(this.Xi(t, o.targetId)), 
            s++);
        })), As.$n(i).next((() => s));
    }
    tr(t) {
        return As.resolve(this.targetCount);
    }
    er(t, e) {
        const n = this.zc.get(e) || null;
        return As.resolve(n);
    }
    nr(t, e, n) {
        return this.Jc.Nc(e, n), As.resolve();
    }
    ir(t, e, n) {
        this.Jc.Fc(e, n);
        const s = this.persistence.Ii, i = [];
        return s && e.forEach((e => {
            i.push(s.Oi(t, e));
        })), As.$n(i);
    }
    Xi(t, e) {
        return this.Jc.kc(e), As.resolve();
    }
    cr(t, e) {
        const n = this.Jc.Lc(e);
        return As.resolve(n);
    }
    ki(t, e) {
        return As.resolve(this.Jc.ki(e));
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A memory-backed instance of Persistence. Data is stored only in RAM and
 * not persisted across sessions.
 */
class Cr {
    /**
     * The constructor accepts a factory for creating a reference delegate. This
     * allows both the delegate and this instance to have strong references to
     * each other without having nullable fields that would then need to be
     * checked or asserted on every access.
     */
    constructor(t, e) {
        this.Xc = {}, this.io = new z(0), this.ro = !1, this.ro = !0, this.Ii = t(this), 
        this.fo = new Dr(this);
        this.Ti = new mi, this.wo = function(t, e) {
            return new vr(t, e);
        }(this.Ti, (t => this.Ii.Zc(t))), this.Kt = new ri(e), this.Eo = new gr(this.Kt);
    }
    start() {
        return Promise.resolve();
    }
    Lo() {
        // No durable state to ensure is closed on shutdown.
        return this.ro = !1, Promise.resolve();
    }
    get Tr() {
        return this.ro;
    }
    yo() {
        // No op.
    }
    Vo() {
        // No op.
    }
    jo() {
        return this.Ti;
    }
    Ko(t) {
        let e = this.Xc[t.R()];
        return e || (e = new br(this.Ti, this.Ii), this.Xc[t.R()] = e), e;
    }
    Dr() {
        return this.fo;
    }
    Fr() {
        return this.wo;
    }
    Wo() {
        return this.Eo;
    }
    runTransaction(t, e, n) {
        R("MemoryPersistence", "Starting transaction:", t);
        const s = new xr(this.io.next());
        return this.Ii.ta(), n(s).next((t => this.Ii.ea(s).next((() => t)))).Mn().then((t => (s.ps(), 
        t)));
    }
    na(t, e) {
        return As.Bn(Object.values(this.Xc).map((n => () => n.ki(t, e))));
    }
}

/**
 * Memory persistence is not actually transactional, but future implementations
 * may have transaction-scoped state.
 */ class xr extends Ns {
    constructor(t) {
        super(), this.vs = t;
    }
}

class Nr {
    constructor(t) {
        this.persistence = t, 
        /** Tracks all documents that are active in Query views. */
        this.sa = new Vr, 
        /** The list of documents that are potentially GCed after each transaction. */
        this.ia = null;
    }
    static ra(t) {
        return new Nr(t);
    }
    get oa() {
        if (this.ia) return this.ia;
        throw V();
    }
    sr(t, e, n) {
        return this.sa.sr(n, e), this.oa.delete(n.toString()), As.resolve();
    }
    rr(t, e, n) {
        return this.sa.rr(n, e), this.oa.add(n.toString()), As.resolve();
    }
    Oi(t, e) {
        return this.oa.add(e.toString()), As.resolve();
    }
    removeTarget(t, e) {
        this.sa.kc(e.targetId).forEach((t => this.oa.add(t.toString())));
        const n = this.persistence.Dr();
        return n.cr(t, e.targetId).next((t => {
            t.forEach((t => this.oa.add(t.toString())));
        })).next((() => n.Yi(t, e)));
    }
    ta() {
        this.ia = new Set;
    }
    ea(t) {
        // Remove newly orphaned documents.
        const e = this.persistence.Fr().Or();
        return As.forEach(this.oa, (n => {
            const s = et.ft(n);
            return this.ca(t, s).next((t => {
                t || e._i(s);
            }));
        })).next((() => (this.ia = null, e.apply(t))));
    }
    kr(t, e) {
        return this.ca(t, e).next((t => {
            t ? this.oa.delete(e.toString()) : this.oa.add(e.toString());
        }));
    }
    Zc(t) {
        // For eager GC, we don't care about the document size, there are no size thresholds.
        return 0;
    }
    ca(t, e) {
        return As.Bn([ () => As.resolve(this.sa.ki(e)), () => this.persistence.Dr().ki(t, e), () => this.persistence.na(t, e) ]);
    }
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// The format of the LocalStorage key that stores the client state is:
//     firestore_clients_<persistence_prefix>_<instance_key>
/** Assembles the key for a client state in WebStorage */
function Or(t, e) {
    return `firestore_clients_${t}_${e}`;
}

// The format of the WebStorage key that stores the mutation state is:
//     firestore_mutations_<persistence_prefix>_<batch_id>
//     (for unauthenticated users)
// or: firestore_mutations_<persistence_prefix>_<batch_id>_<user_uid>

// 'user_uid' is last to avoid needing to escape '_' characters that it might
// contain.
/** Assembles the key for a mutation batch in WebStorage */
function Fr(t, e, n) {
    let s = `firestore_mutations_${t}_${n}`;
    return e.A() && (s += "_" + e.uid), s;
}

// The format of the WebStorage key that stores a query target's metadata is:
//     firestore_targets_<persistence_prefix>_<target_id>
/** Assembles the key for a query state in WebStorage */
function kr(t, e) {
    return `firestore_targets_${t}_${e}`;
}

// The WebStorage prefix that stores the primary tab's online state. The
// format of the key is:
//     firestore_online_state_<persistence_prefix>
/**
 * Holds the state of a mutation batch, including its user ID, batch ID and
 * whether the batch is 'pending', 'acknowledged' or 'rejected'.
 */
// Visible for testing
class Mr {
    constructor(t, e, n, s) {
        this.user = t, this.batchId = e, this.state = n, this.error = s;
    }
    /**
     * Parses a MutationMetadata from its JSON representation in WebStorage.
     * Logs a warning and returns null if the format of the data is not valid.
     */    static aa(t, e, n) {
        const s = JSON.parse(n);
        let i = "object" == typeof s && -1 !== [ "pending", "acknowledged", "rejected" ].indexOf(s.state) && (void 0 === s.error || "object" == typeof s.error), r = void 0;
        return i && s.error && (i = "string" == typeof s.error.message && "string" == typeof s.error.code, 
        i && (r = new F(s.error.code, s.error.message))), i ? new Mr(t, e, s.state, r) : (P("SharedClientState", `Failed to parse mutation state for ID '${e}': ${n}`), 
        null);
    }
    ua() {
        const t = {
            state: this.state,
            updateTimeMs: Date.now()
        };
        return this.error && (t.error = {
            code: this.error.code,
            message: this.error.message
        }), JSON.stringify(t);
    }
}

/**
 * Holds the state of a query target, including its target ID and whether the
 * target is 'not-current', 'current' or 'rejected'.
 */
// Visible for testing
class Lr {
    constructor(t, e, n) {
        this.targetId = t, this.state = e, this.error = n;
    }
    /**
     * Parses a QueryTargetMetadata from its JSON representation in WebStorage.
     * Logs a warning and returns null if the format of the data is not valid.
     */    static aa(t, e) {
        const n = JSON.parse(e);
        let s = "object" == typeof n && -1 !== [ "not-current", "current", "rejected" ].indexOf(n.state) && (void 0 === n.error || "object" == typeof n.error), i = void 0;
        return s && n.error && (s = "string" == typeof n.error.message && "string" == typeof n.error.code, 
        s && (i = new F(n.error.code, n.error.message))), s ? new Lr(t, n.state, i) : (P("SharedClientState", `Failed to parse target state for ID '${t}': ${e}`), 
        null);
    }
    ua() {
        const t = {
            state: this.state,
            updateTimeMs: Date.now()
        };
        return this.error && (t.error = {
            code: this.error.code,
            message: this.error.message
        }), JSON.stringify(t);
    }
}

/**
 * This class represents the immutable ClientState for a client read from
 * WebStorage, containing the list of active query targets.
 */ class $r {
    constructor(t, e) {
        this.clientId = t, this.activeTargetIds = e;
    }
    /**
     * Parses a RemoteClientState from the JSON representation in WebStorage.
     * Logs a warning and returns null if the format of the data is not valid.
     */    static aa(t, e) {
        const n = JSON.parse(e);
        let s = "object" == typeof n && n.activeTargetIds instanceof Array, i = yn();
        for (let t = 0; s && t < n.activeTargetIds.length; ++t) s = wt(n.activeTargetIds[t]), 
        i = i.add(n.activeTargetIds[t]);
        return s ? new $r(t, i) : (P("SharedClientState", `Failed to parse client data for instance '${t}': ${e}`), 
        null);
    }
}

/**
 * This class represents the online state for all clients participating in
 * multi-tab. The online state is only written to by the primary client, and
 * used in secondary clients to update their query views.
 */ class Br {
    constructor(t, e) {
        this.clientId = t, this.onlineState = e;
    }
    /**
     * Parses a SharedOnlineState from its JSON representation in WebStorage.
     * Logs a warning and returns null if the format of the data is not valid.
     */    static aa(t) {
        const e = JSON.parse(t);
        return "object" == typeof e && -1 !== [ "Unknown", "Online", "Offline" ].indexOf(e.onlineState) && "string" == typeof e.clientId ? new Br(e.clientId, e.onlineState) : (P("SharedClientState", "Failed to parse online state: " + t), 
        null);
    }
}

/**
 * Metadata state of the local client. Unlike `RemoteClientState`, this class is
 * mutable and keeps track of all pending mutations, which allows us to
 * update the range of pending mutation batch IDs as new mutations are added or
 * removed.
 *
 * The data in `LocalClientState` is not read from WebStorage and instead
 * updated via its instance methods. The updated state can be serialized via
 * `toWebStorageJSON()`.
 */
// Visible for testing.
class qr {
    constructor() {
        this.activeTargetIds = yn();
    }
    ha(t) {
        this.activeTargetIds = this.activeTargetIds.add(t);
    }
    la(t) {
        this.activeTargetIds = this.activeTargetIds.delete(t);
    }
    /**
     * Converts this entry into a JSON-encoded format we can use for WebStorage.
     * Does not encode `clientId` as it is part of the key in WebStorage.
     */    ua() {
        const t = {
            activeTargetIds: this.activeTargetIds.rt(),
            updateTimeMs: Date.now()
        };
        return JSON.stringify(t);
    }
}

/**
 * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the
 * backing store for the SharedClientState. It keeps track of all active
 * clients and supports modifications of the local client's data.
 */ class Ur {
    constructor(t, e, n, s, i) {
        this.window = t, this.eo = e, this.persistenceKey = n, this._a = s, this.fa = null, 
        this.da = null, this.L = null, this.wa = this.Ea.bind(this), this.Ta = new an(D), 
        this.Tr = !1, 
        /**
         * Captures WebStorage events that occur before `start()` is called. These
         * events are replayed once `WebStorageSharedClientState` is started.
         */
        this.Ia = [];
        // Escape the special characters mentioned here:
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
        const r = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        this.storage = this.window.localStorage, this.currentUser = i, this.ma = Or(this.persistenceKey, this._a), 
        this.Aa = 
        /** Assembles the key for the current sequence number. */
        function(t) {
            return "firestore_sequence_number_" + t;
        }
        /**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ (this.persistenceKey), this.Ta = this.Ta.Ht(this._a, new qr), this.Ra = new RegExp(`^firestore_clients_${r}_([^_]*)$`), 
        this.Pa = new RegExp(`^firestore_mutations_${r}_(\\d+)(?:_(.*))?$`), this.ya = new RegExp(`^firestore_targets_${r}_(\\d+)$`), 
        this.ga = 
        /** Assembles the key for the online state of the primary tab. */
        function(t) {
            return "firestore_online_state_" + t;
        }
        // The WebStorage prefix that plays as a event to indicate the remote documents
        // might have changed due to some secondary tabs loading a bundle.
        // format of the key is:
        //     firestore_bundle_loaded_<persistenceKey>
        (this.persistenceKey), this.Va = function(t) {
            return "firestore_bundle_loaded_" + t;
        }
        // The WebStorage key prefix for the key that stores the last sequence number allocated. The key
        // looks like 'firestore_sequence_number_<persistence_prefix>'.
        (this.persistenceKey), 
        // Rather than adding the storage observer during start(), we add the
        // storage observer during initialization. This ensures that we collect
        // events before other components populate their initial state (during their
        // respective start() calls). Otherwise, we might for example miss a
        // mutation that is added after LocalStore's start() processed the existing
        // mutations but before we observe WebStorage events.
        this.window.addEventListener("storage", this.wa);
    }
    /** Returns 'true' if WebStorage is available in the current environment. */    static jn(t) {
        return !(!t || !t.localStorage);
    }
    async start() {
        // Retrieve the list of existing clients to backfill the data in
        // SharedClientState.
        const t = await this.fa.Qo();
        for (const e of t) {
            if (e === this._a) continue;
            const t = this.getItem(Or(this.persistenceKey, e));
            if (t) {
                const n = $r.aa(e, t);
                n && (this.Ta = this.Ta.Ht(n.clientId, n));
            }
        }
        this.pa();
        // Check if there is an existing online state and call the callback handler
        // if applicable.
        const e = this.storage.getItem(this.ga);
        if (e) {
            const t = this.ba(e);
            t && this.va(t);
        }
        for (const t of this.Ia) this.Ea(t);
        this.Ia = [], 
        // Register a window unload hook to remove the client metadata entry from
        // WebStorage even if `shutdown()` was not called.
        this.window.addEventListener("unload", (() => this.Lo())), this.Tr = !0;
    }
    q(t) {
        this.setItem(this.Aa, JSON.stringify(t));
    }
    Sa() {
        return this.Da(this.Ta);
    }
    Ca(t) {
        let e = !1;
        return this.Ta.forEach(((n, s) => {
            s.activeTargetIds.has(t) && (e = !0);
        })), e;
    }
    xa(t) {
        this.Na(t, "pending");
    }
    Oa(t, e, n) {
        this.Na(t, e, n), 
        // Once a final mutation result is observed by other clients, they no longer
        // access the mutation's metadata entry. Since WebStorage replays events
        // in order, it is safe to delete the entry right after updating it.
        this.Fa(t);
    }
    ka(t) {
        let e = "not-current";
        // Lookup an existing query state if the target ID was already registered
        // by another tab
                if (this.Ca(t)) {
            const n = this.storage.getItem(kr(this.persistenceKey, t));
            if (n) {
                const s = Lr.aa(t, n);
                s && (e = s.state);
            }
        }
        return this.Ma.ha(t), this.pa(), e;
    }
    La(t) {
        this.Ma.la(t), this.pa();
    }
    $a(t) {
        return this.Ma.activeTargetIds.has(t);
    }
    Ba(t) {
        this.removeItem(kr(this.persistenceKey, t));
    }
    qa(t, e, n) {
        this.Ua(t, e, n);
    }
    Qa(t, e, n) {
        e.forEach((t => {
            this.Fa(t);
        })), this.currentUser = t, n.forEach((t => {
            this.xa(t);
        }));
    }
    Ka(t) {
        this.ja(t);
    }
    Wa() {
        this.Ga();
    }
    Lo() {
        this.Tr && (this.window.removeEventListener("storage", this.wa), this.removeItem(this.ma), 
        this.Tr = !1);
    }
    getItem(t) {
        const e = this.storage.getItem(t);
        return R("SharedClientState", "READ", t, e), e;
    }
    setItem(t, e) {
        R("SharedClientState", "SET", t, e), this.storage.setItem(t, e);
    }
    removeItem(t) {
        R("SharedClientState", "REMOVE", t), this.storage.removeItem(t);
    }
    Ea(t) {
        // Note: The function is typed to take Event to be interface-compatible with
        // `Window.addEventListener`.
        const e = t;
        if (e.storageArea === this.storage) {
            if (R("SharedClientState", "EVENT", e.key, e.newValue), e.key === this.ma) return void P("Received WebStorage notification for local change. Another client might have garbage-collected our state");
            this.eo.bo((async () => {
                if (this.Tr) {
                    if (null !== e.key) if (this.Ra.test(e.key)) {
                        if (null == e.newValue) {
                            const t = this.za(e.key);
                            return this.Ha(t, null);
                        }
                        {
                            const t = this.Ja(e.key, e.newValue);
                            if (t) return this.Ha(t.clientId, t);
                        }
                    } else if (this.Pa.test(e.key)) {
                        if (null !== e.newValue) {
                            const t = this.Ya(e.key, e.newValue);
                            if (t) return this.Xa(t);
                        }
                    } else if (this.ya.test(e.key)) {
                        if (null !== e.newValue) {
                            const t = this.Za(e.key, e.newValue);
                            if (t) return this.tu(t);
                        }
                    } else if (e.key === this.ga) {
                        if (null !== e.newValue) {
                            const t = this.ba(e.newValue);
                            if (t) return this.va(t);
                        }
                    } else if (e.key === this.Aa) {
                        const t = function(t) {
                            let e = z.U;
                            if (null != t) try {
                                const n = JSON.parse(t);
                                p("number" == typeof n), e = n;
                            } catch (t) {
                                P("SharedClientState", "Failed to read sequence number from WebStorage", t);
                            }
                            return e;
                        }
                        /**
 * `MemorySharedClientState` is a simple implementation of SharedClientState for
 * clients using memory persistence. The state in this class remains fully
 * isolated and no synchronization is performed.
 */ (e.newValue);
                        t !== z.U && this.L(t);
                    } else if (e.key === this.Va) return this.fa.eu();
                } else this.Ia.push(e);
            }));
        }
    }
    get Ma() {
        return this.Ta.get(this._a);
    }
    pa() {
        this.setItem(this.ma, this.Ma.ua());
    }
    Na(t, e, n) {
        const s = new Mr(this.currentUser, t, e, n), i = Fr(this.persistenceKey, this.currentUser, t);
        this.setItem(i, s.ua());
    }
    Fa(t) {
        const e = Fr(this.persistenceKey, this.currentUser, t);
        this.removeItem(e);
    }
    ja(t) {
        const e = {
            clientId: this._a,
            onlineState: t
        };
        this.storage.setItem(this.ga, JSON.stringify(e));
    }
    Ua(t, e, n) {
        const s = kr(this.persistenceKey, t), i = new Lr(t, e, n);
        this.setItem(s, i.ua());
    }
    Ga() {
        this.setItem(this.Va, "value-not-used");
    }
    /**
     * Parses a client state key in WebStorage. Returns null if the key does not
     * match the expected key format.
     */    za(t) {
        const e = this.Ra.exec(t);
        return e ? e[1] : null;
    }
    /**
     * Parses a client state in WebStorage. Returns 'null' if the value could not
     * be parsed.
     */    Ja(t, e) {
        const n = this.za(t);
        return $r.aa(n, e);
    }
    /**
     * Parses a mutation batch state in WebStorage. Returns 'null' if the value
     * could not be parsed.
     */    Ya(t, e) {
        const n = this.Pa.exec(t), s = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;
        return Mr.aa(new U(i), s, e);
    }
    /**
     * Parses a query target state from WebStorage. Returns 'null' if the value
     * could not be parsed.
     */    Za(t, e) {
        const n = this.ya.exec(t), s = Number(n[1]);
        return Lr.aa(s, e);
    }
    /**
     * Parses an online state from WebStorage. Returns 'null' if the value
     * could not be parsed.
     */    ba(t) {
        return Br.aa(t);
    }
    async Xa(t) {
        if (t.user.uid === this.currentUser.uid) return this.fa.nu(t.batchId, t.state, t.error);
        R("SharedClientState", "Ignoring mutation for non-active user " + t.user.uid);
    }
    tu(t) {
        return this.fa.su(t.targetId, t.state, t.error);
    }
    Ha(t, e) {
        const n = e ? this.Ta.Ht(t, e) : this.Ta.remove(t), s = this.Da(this.Ta), i = this.Da(n), r = [], o = [];
        return i.forEach((t => {
            s.has(t) || r.push(t);
        })), s.forEach((t => {
            i.has(t) || o.push(t);
        })), this.fa.iu(r, o).then((() => {
            this.Ta = n;
        }));
    }
    va(t) {
        // We check whether the client that wrote this online state is still active
        // by comparing its client ID to the list of clients kept active in
        // IndexedDb. If a client does not update their IndexedDb client state
        // within 5 seconds, it is considered inactive and we don't emit an online
        // state event.
        this.Ta.get(t.clientId) && this.da(t.onlineState);
    }
    Da(t) {
        let e = yn();
        return t.forEach(((t, n) => {
            e = e.ye(n.activeTargetIds);
        })), e;
    }
}

class Qr {
    constructor() {
        this.ru = new qr, this.ou = {}, this.da = null, this.L = null;
    }
    xa(t) {
        // No op.
    }
    Oa(t, e, n) {
        // No op.
    }
    ka(t) {
        return this.ru.ha(t), this.ou[t] || "not-current";
    }
    qa(t, e, n) {
        this.ou[t] = e;
    }
    La(t) {
        this.ru.la(t);
    }
    $a(t) {
        return this.ru.activeTargetIds.has(t);
    }
    Ba(t) {
        delete this.ou[t];
    }
    Sa() {
        return this.ru.activeTargetIds;
    }
    Ca(t) {
        return this.ru.activeTargetIds.has(t);
    }
    start() {
        return this.ru = new qr, Promise.resolve();
    }
    Qa(t, e, n) {
        // No op.
    }
    Ka(t) {
        // No op.
    }
    Lo() {}
    q(t) {}
    Wa() {
        // No op.
    }
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class Kr {
    cu(t) {
        // No-op.
    }
    Lo() {
        // No-op.
    }
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()
/* eslint-disable no-restricted-globals */
/**
 * Browser implementation of ConnectivityMonitor.
 */
class jr {
    constructor() {
        this.au = () => this.uu(), this.hu = () => this.lu(), this._u = [], this.fu();
    }
    cu(t) {
        this._u.push(t);
    }
    Lo() {
        window.removeEventListener("online", this.au), window.removeEventListener("offline", this.hu);
    }
    fu() {
        window.addEventListener("online", this.au), window.addEventListener("offline", this.hu);
    }
    uu() {
        R("ConnectivityMonitor", "Network connectivity changed: AVAILABLE");
        for (const t of this._u) t(0 /* AVAILABLE */);
    }
    lu() {
        R("ConnectivityMonitor", "Network connectivity changed: UNAVAILABLE");
        for (const t of this._u) t(1 /* UNAVAILABLE */);
    }
    // TODO(chenbrian): Consider passing in window either into this component or
    // here for testing via FakeWindow.
    /** Checks that all used attributes of window are available. */
    static jn() {
        return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const Wr = {
    BatchGetDocuments: "batchGet",
    Commit: "commit",
    RunQuery: "runQuery"
};

/**
 * Maps RPC names to the corresponding REST endpoint name.
 *
 * We use array notation to avoid mangling.
 */
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Provides a simple helper class that implements the Stream interface to
 * bridge to other implementations that are streams but do not implement the
 * interface. The stream callbacks are invoked with the callOn... methods.
 */
class Gr {
    constructor(t) {
        this.du = t.du, this.wu = t.wu;
    }
    Eu(t) {
        this.Tu = t;
    }
    Iu(t) {
        this.mu = t;
    }
    onMessage(t) {
        this.Au = t;
    }
    close() {
        this.wu();
    }
    send(t) {
        this.du(t);
    }
    Ru() {
        this.Tu();
    }
    Pu(t) {
        this.mu(t);
    }
    yu(t) {
        this.Au(t);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class zr extends 
/**
 * Base class for all Rest-based connections to the backend (WebChannel and
 * HTTP).
 */
class {
    constructor(t) {
        this.gu = t, this.T = t.T;
        const e = t.ssl ? "https" : "http";
        this.Vu = e + "://" + t.host, this.pu = "projects/" + this.T.projectId + "/databases/" + this.T.database + "/documents";
    }
    bu(t, e, n, s) {
        const i = this.vu(t, e);
        R("RestConnection", "Sending: ", i, n);
        const r = {};
        return this.Su(r, s), this.Du(t, i, r, n).then((t => (R("RestConnection", "Received: ", t), 
        t)), (e => {
            throw y("RestConnection", t + " failed with error: ", e, "url: ", i, "request:", n), 
            e;
        }));
    }
    Cu(t, e, n, s) {
        // The REST API automatically aggregates all of the streamed results, so we
        // can just use the normal invoke() method.
        return this.bu(t, e, n, s);
    }
    /**
     * Modifies the headers for a request, adding any authorization token if
     * present and any additional headers for the request.
     */    Su(t, e) {
        if (t["X-Goog-Api-Client"] = "gl-js/ fire/8.2.2", 
        // Content-Type: text/plain will avoid preflight requests which might
        // mess with CORS and redirects by proxies. If we add custom headers
        // we will need to change this code to potentially use the $httpOverwrite
        // parameter supported by ESF to avoid triggering preflight requests.
        t["Content-Type"] = "text/plain", e) for (const n in e.V) e.V.hasOwnProperty(n) && (t[n] = e.V[n]);
    }
    vu(t, e) {
        const n = Wr[t];
        return `${this.Vu}/v1/${e}:${n}`;
    }
} {
    constructor(t) {
        super(t), this.forceLongPolling = t.forceLongPolling, this.I = t.I;
    }
    Du(t, e, n, s) {
        return new Promise(((i, r) => {
            const o = new h;
            o.listenOnce(l.COMPLETE, (() => {
                try {
                    switch (o.getLastErrorCode()) {
                      case _.NO_ERROR:
                        const e = o.getResponseJson();
                        R("Connection", "XHR received:", JSON.stringify(e)), i(e);
                        break;

                      case _.TIMEOUT:
                        R("Connection", 'RPC "' + t + '" timed out'), r(new F(O.DEADLINE_EXCEEDED, "Request time out"));
                        break;

                      case _.HTTP_ERROR:
                        const n = o.getStatus();
                        if (R("Connection", 'RPC "' + t + '" failed with status:', n, "response text:", o.getResponseText()), 
                        n > 0) {
                            const t = o.getResponseJson().error;
                            if (t && t.status && t.message) {
                                const e = function(t) {
                                    const e = t.toLowerCase().replace(/_/g, "-");
                                    return Object.values(O).indexOf(e) >= 0 ? e : O.UNKNOWN;
                                }(t.status);
                                r(new F(e, t.message));
                            } else r(new F(O.UNKNOWN, "Server responded with status " + o.getStatus()));
                        } else 
                        // If we received an HTTP_ERROR but there's no status code,
                        // it's most probably a connection issue
                        r(new F(O.UNAVAILABLE, "Connection failed."));
                        break;

                      default:
                        V();
                    }
                } finally {
                    R("Connection", 'RPC "' + t + '" completed.');
                }
            }));
            const c = JSON.stringify(s);
            o.send(e, "POST", c, n, 15);
        }));
    }
    xu(t, e) {
        const a = [ this.Vu, "/", "google.firestore.v1.Firestore", "/", t, "/channel" ], u = f(), h = d(), l = {
            // Required for backend stickiness, routing behavior is based on this
            // parameter.
            httpSessionIdParam: "gsessionid",
            initMessageHeaders: {},
            messageUrlParams: {
                // This param is used to improve routing and project isolation by the
                // backend and must be included in every request.
                database: `projects/${this.T.projectId}/databases/${this.T.database}`
            },
            sendRawJson: !0,
            supportsCrossDomainXhr: !0,
            internalChannelParams: {
                // Override the default timeout (randomized between 10-20 seconds) since
                // a large write batch on a slow internet connection may take a long
                // time to send to the backend. Rather than have WebChannel impose a
                // tight timeout which could lead to infinite timeouts and retries, we
                // set it very large (5-10 minutes) and rely on the browser's builtin
                // timeouts to kick in if the request isn't working.
                forwardChannelRequestTimeoutMs: 6e5
            },
            forceLongPolling: this.forceLongPolling,
            detectBufferingProxy: this.I
        };
        this.Su(l.initMessageHeaders, e), 
        // Sending the custom headers we just added to request.initMessageHeaders
        // (Authorization, etc.) will trigger the browser to make a CORS preflight
        // request because the XHR will no longer meet the criteria for a "simple"
        // CORS request:
        // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
        // Therefore to avoid the CORS preflight request (an extra network
        // roundtrip), we use the httpHeadersOverwriteParam option to specify that
        // the headers should instead be encoded into a special "$httpHeaders" query
        // parameter, which is recognized by the webchannel backend. This is
        // formally defined here:
        // https://github.com/google/closure-library/blob/b0e1815b13fb92a46d7c9b3c30de5d6a396a3245/closure/goog/net/rpc/httpcors.js#L32
        // TODO(b/145624756): There is a backend bug where $httpHeaders isn't respected if the request
        // doesn't have an Origin header. So we have to exclude a few browser environments that are
        // known to (sometimes) not include an Origin. See
        // https://github.com/firebase/firebase-js-sdk/issues/1491.
        n() || s() || i() || r() || o() || c() || (l.httpHeadersOverwriteParam = "$httpHeaders");
        const _ = a.join("");
        R("Connection", "Creating WebChannel: " + _, l);
        const I = u.createWebChannel(_, l);
        // WebChannel supports sending the first message with the handshake - saving
        // a network round trip. However, it will have to call send in the same
        // JS event loop as open. In order to enforce this, we delay actually
        // opening the WebChannel until send is called. Whether we have called
        // open is tracked with this variable.
                let m = !1, A = !1;
        // A flag to determine whether the stream was closed (by us or through an
        // error/close event) to avoid delivering multiple close events or sending
        // on a closed stream
                const P = new Gr({
            du: t => {
                A ? R("Connection", "Not sending because WebChannel is closed:", t) : (m || (R("Connection", "Opening WebChannel transport."), 
                I.open(), m = !0), R("Connection", "WebChannel sending:", t), I.send(t));
            },
            wu: () => I.close()
        }), g = (t, e, n) => {
            // TODO(dimond): closure typing seems broken because WebChannel does
            // not implement goog.events.Listenable
            t.listen(e, (t => {
                try {
                    n(t);
                } catch (t) {
                    setTimeout((() => {
                        throw t;
                    }), 0);
                }
            }));
        };
        // Closure events are guarded and exceptions are swallowed, so catch any
        // exception and rethrow using a setTimeout so they become visible again.
        // Note that eventually this function could go away if we are confident
        // enough the code is exception free.
                return g(I, w.EventType.OPEN, (() => {
            A || R("Connection", "WebChannel transport opened.");
        })), g(I, w.EventType.CLOSE, (() => {
            A || (A = !0, R("Connection", "WebChannel transport closed"), P.Pu());
        })), g(I, w.EventType.ERROR, (t => {
            A || (A = !0, y("Connection", "WebChannel transport errored:", t), P.Pu(new F(O.UNAVAILABLE, "The operation could not be completed")));
        })), g(I, w.EventType.MESSAGE, (t => {
            var e;
            if (!A) {
                const n = t.data[0];
                p(!!n);
                // TODO(b/35143891): There is a bug in One Platform that caused errors
                // (and only errors) to be wrapped in an extra array. To be forward
                // compatible with the bug we need to check either condition. The latter
                // can be removed once the fix has been rolled out.
                // Use any because msgData.error is not typed.
                const s = n, i = s.error || (null === (e = s[0]) || void 0 === e ? void 0 : e.error);
                if (i) {
                    R("Connection", "WebChannel received error:", i);
                    // error.status will be a string like 'OK' or 'NOT_FOUND'.
                    const t = i.status;
                    let e = 
                    /**
 * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.
 *
 * @returns The Code equivalent to the given status string or undefined if
 *     there is no match.
 */
                    function(t) {
                        // lookup by string
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        const e = sn[t];
                        if (void 0 !== e) return cn(e);
                    }(t), n = i.message;
                    void 0 === e && (e = O.INTERNAL, n = "Unknown error status: " + t + " with message " + i.message), 
                    // Mark closed so no further events are propagated
                    A = !0, P.Pu(new F(e, n)), I.close();
                } else R("Connection", "WebChannel received:", n), P.yu(n);
            }
        })), g(h, E.STAT_EVENT, (t => {
            t.stat === T.PROXY ? R("Connection", "Detected buffering proxy") : t.stat === T.NOPROXY && R("Connection", "Detected no buffering proxy");
        })), setTimeout((() => {
            // Technically we could/should wait for the WebChannel opened event,
            // but because we want to send the first message with the WebChannel
            // handshake we pretend the channel opened here (asynchronously), and
            // then delay the actual open until the first message is sent.
            P.Ru();
        }), 0), P;
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Initializes the WebChannelConnection for the browser. */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** The Platform's 'window' implementation or null if not available. */
function Hr() {
    // `window` is not always available, e.g. in ReactNative and WebWorkers.
    // eslint-disable-next-line no-restricted-globals
    return "undefined" != typeof window ? window : null;
}

/** The Platform's 'document' implementation or null if not available. */ function Jr() {
    // `document` is not always available, e.g. in ReactNative and WebWorkers.
    // eslint-disable-next-line no-restricted-globals
    return "undefined" != typeof document ? document : null;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ function Yr(t) {
    return new Ln(t, /* useProto3Json= */ !0);
}

/**
 * An instance of the Platform's 'TextEncoder' implementation.
 */
/**
 * A helper for running delayed tasks following an exponential backoff curve
 * between attempts.
 *
 * Each delay is made up of a "base" delay which follows the exponential
 * backoff curve, and a +/- 50% "jitter" that is calculated and added to the
 * base delay. This prevents clients from accidentally synchronizing their
 * delays causing spikes of load to the backend.
 */
class Xr {
    constructor(
    /**
     * The AsyncQueue to run backoff operations on.
     */
    t, 
    /**
     * The ID to use when scheduling backoff operations on the AsyncQueue.
     */
    e, 
    /**
     * The initial delay (used as the base delay on the first retry attempt).
     * Note that jitter will still be applied, so the actual delay could be as
     * little as 0.5*initialDelayMs.
     */
    n = 1e3
    /**
     * The multiplier to use to determine the extended base delay after each
     * attempt.
     */ , s = 1.5
    /**
     * The maximum base delay after which no further backoff is performed.
     * Note that jitter will still be applied, so the actual delay could be as
     * much as 1.5*maxDelayMs.
     */ , i = 6e4) {
        this.eo = t, this.ds = e, this.Nu = n, this.Ou = s, this.Fu = i, this.ku = 0, this.Mu = null, 
        /** The last backoff attempt, as epoch milliseconds. */
        this.Lu = Date.now(), this.reset();
    }
    /**
     * Resets the backoff delay.
     *
     * The very next backoffAndWait() will have no delay. If it is called again
     * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
     * subsequent ones will increase according to the backoffFactor.
     */    reset() {
        this.ku = 0;
    }
    /**
     * Resets the backoff delay to the maximum delay (e.g. for use after a
     * RESOURCE_EXHAUSTED error).
     */    $u() {
        this.ku = this.Fu;
    }
    /**
     * Returns a promise that resolves after currentDelayMs, and increases the
     * delay for any subsequent attempts. If there was a pending backoff operation
     * already, it will be canceled.
     */    Bu(t) {
        // Cancel any pending backoff operation.
        this.cancel();
        // First schedule using the current base (which may be 0 and should be
        // honored as such).
        const e = Math.floor(this.ku + this.qu()), n = Math.max(0, Date.now() - this.Lu), s = Math.max(0, e - n);
        // Guard against lastAttemptTime being in the future due to a clock change.
                s > 0 && R("ExponentialBackoff", `Backing off for ${s} ms (base delay: ${this.ku} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`), 
        this.Mu = this.eo.Ir(this.ds, s, (() => (this.Lu = Date.now(), t()))), 
        // Apply backoff factor to determine next delay and ensure it is within
        // bounds.
        this.ku *= this.Ou, this.ku < this.Nu && (this.ku = this.Nu), this.ku > this.Fu && (this.ku = this.Fu);
    }
    Uu() {
        null !== this.Mu && (this.Mu.Ps(), this.Mu = null);
    }
    cancel() {
        null !== this.Mu && (this.Mu.cancel(), this.Mu = null);
    }
    /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */    qu() {
        return (Math.random() - .5) * this.ku;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A PersistentStream is an abstract base class that represents a streaming RPC
 * to the Firestore backend. It's built on top of the connections own support
 * for streaming RPCs, and adds several critical features for our clients:
 *
 *   - Exponential backoff on failure
 *   - Authentication via CredentialsProvider
 *   - Dispatching all callbacks into the shared worker queue
 *   - Closing idle streams after 60 seconds of inactivity
 *
 * Subclasses of PersistentStream implement serialization of models to and
 * from the JSON representation of the protocol buffers for a specific
 * streaming RPC.
 *
 * ## Starting and Stopping
 *
 * Streaming RPCs are stateful and need to be start()ed before messages can
 * be sent and received. The PersistentStream will call the onOpen() function
 * of the listener once the stream is ready to accept requests.
 *
 * Should a start() fail, PersistentStream will call the registered onClose()
 * listener with a FirestoreError indicating what went wrong.
 *
 * A PersistentStream can be started and stopped repeatedly.
 *
 * Generic types:
 *  SendType: The type of the outgoing message of the underlying
 *    connection stream
 *  ReceiveType: The type of the incoming message of the underlying
 *    connection stream
 *  ListenerType: The type of the listener that will be used for callbacks
 */
class Zr {
    constructor(t, e, n, s, i, r) {
        this.eo = t, this.Qu = n, this.Ku = s, this.ju = i, this.listener = r, this.state = 0 /* Initial */ , 
        /**
         * A close count that's incremented every time the stream is closed; used by
         * getCloseGuardedDispatcher() to invalidate callbacks that happen after
         * close.
         */
        this.Wu = 0, this.Gu = null, this.stream = null, this.zu = new Xr(t, e);
    }
    /**
     * Returns true if start() has been called and no error has occurred. True
     * indicates the stream is open or in the process of opening (which
     * encompasses respecting backoff, getting auth tokens, and starting the
     * actual RPC). Use isOpen() to determine if the stream is open and ready for
     * outbound requests.
     */    Hu() {
        return 1 /* Starting */ === this.state || 2 /* Open */ === this.state || 4 /* Backoff */ === this.state;
    }
    /**
     * Returns true if the underlying RPC is open (the onOpen() listener has been
     * called) and the stream is ready for outbound requests.
     */    Ju() {
        return 2 /* Open */ === this.state;
    }
    /**
     * Starts the RPC. Only allowed if isStarted() returns false. The stream is
     * not immediately ready for use: onOpen() will be invoked when the RPC is
     * ready for outbound requests, at which point isOpen() will return true.
     *
     * When start returns, isStarted() will return true.
     */    start() {
        3 /* Error */ !== this.state ? this.auth() : this.Yu();
    }
    /**
     * Stops the RPC. This call is idempotent and allowed regardless of the
     * current isStarted() state.
     *
     * When stop returns, isStarted() and isOpen() will both return false.
     */    async stop() {
        this.Hu() && await this.close(0 /* Initial */);
    }
    /**
     * After an error the stream will usually back off on the next attempt to
     * start it. If the error warrants an immediate restart of the stream, the
     * sender can use this to indicate that the receiver should not back off.
     *
     * Each error will call the onClose() listener. That function can decide to
     * inhibit backoff if required.
     */    Xu() {
        this.state = 0 /* Initial */ , this.zu.reset();
    }
    /**
     * Marks this stream as idle. If no further actions are performed on the
     * stream for one minute, the stream will automatically close itself and
     * notify the stream's onClose() handler with Status.OK. The stream will then
     * be in a !isStarted() state, requiring the caller to start the stream again
     * before further use.
     *
     * Only streams that are in state 'Open' can be marked idle, as all other
     * states imply pending network operations.
     */    Zu() {
        // Starts the idle time if we are in state 'Open' and are not yet already
        // running a timer (in which case the previous idle timeout still applies).
        this.Ju() && null === this.Gu && (this.Gu = this.eo.Ir(this.Qu, 6e4, (() => this.th())));
    }
    /** Sends a message to the underlying stream. */    eh(t) {
        this.nh(), this.stream.send(t);
    }
    /** Called by the idle timer when the stream should close due to inactivity. */    async th() {
        if (this.Ju()) 
        // When timing out an idle stream there's no reason to force the stream into backoff when
        // it restarts so set the stream state to Initial instead of Error.
        return this.close(0 /* Initial */);
    }
    /** Marks the stream as active again. */    nh() {
        this.Gu && (this.Gu.cancel(), this.Gu = null);
    }
    /**
     * Closes the stream and cleans up as necessary:
     *
     * * closes the underlying GRPC stream;
     * * calls the onClose handler with the given 'error';
     * * sets internal stream state to 'finalState';
     * * adjusts the backoff timer based on the error
     *
     * A new stream can be opened by calling start().
     *
     * @param finalState - the intended state of the stream after closing.
     * @param error - the error the connection was closed with.
     */    async close(t, e) {
        // Cancel any outstanding timers (they're guaranteed not to execute).
        this.nh(), this.zu.cancel(), 
        // Invalidates any stream-related callbacks (e.g. from auth or the
        // underlying stream), guaranteeing they won't execute.
        this.Wu++, 3 /* Error */ !== t ? 
        // If this is an intentional close ensure we don't delay our next connection attempt.
        this.zu.reset() : e && e.code === O.RESOURCE_EXHAUSTED ? (
        // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)
        P(e.toString()), P("Using maximum backoff delay to prevent overloading the backend."), 
        this.zu.$u()) : e && e.code === O.UNAUTHENTICATED && 
        // "unauthenticated" error means the token was rejected. Try force refreshing it in case it
        // just expired.
        this.ju.v(), 
        // Clean up the underlying stream because we are no longer interested in events.
        null !== this.stream && (this.sh(), this.stream.close(), this.stream = null), 
        // This state must be assigned before calling onClose() to allow the callback to
        // inhibit backoff or otherwise manipulate the state in its non-started state.
        this.state = t, 
        // Notify the listener that the stream closed.
        await this.listener.Iu(e);
    }
    /**
     * Can be overridden to perform additional cleanup before the stream is closed.
     * Calling super.tearDown() is not required.
     */    sh() {}
    auth() {
        this.state = 1 /* Starting */;
        const t = this.ih(this.Wu), e = this.Wu;
        // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.
                this.ju.getToken().then((t => {
            // Stream can be stopped while waiting for authentication.
            // TODO(mikelehen): We really should just use dispatchIfNotClosed
            // and let this dispatch onto the queue, but that opened a spec test can
            // of worms that I don't want to deal with in this PR.
            this.Wu === e && 
            // Normally we'd have to schedule the callback on the AsyncQueue.
            // However, the following calls are safe to be called outside the
            // AsyncQueue since they don't chain asynchronous calls
            this.rh(t);
        }), (e => {
            t((() => {
                const t = new F(O.UNKNOWN, "Fetching auth token failed: " + e.message);
                return this.oh(t);
            }));
        }));
    }
    rh(t) {
        const e = this.ih(this.Wu);
        this.stream = this.ah(t), this.stream.Eu((() => {
            e((() => (this.state = 2 /* Open */ , this.listener.Eu())));
        })), this.stream.Iu((t => {
            e((() => this.oh(t)));
        })), this.stream.onMessage((t => {
            e((() => this.onMessage(t)));
        }));
    }
    Yu() {
        this.state = 4 /* Backoff */ , this.zu.Bu((async () => {
            this.state = 0 /* Initial */ , this.start();
        }));
    }
    // Visible for tests
    oh(t) {
        // In theory the stream could close cleanly, however, in our current model
        // we never expect this to happen because if we stop a stream ourselves,
        // this callback will never be called. To prevent cases where we retry
        // without a backoff accidentally, we set the stream to error in all cases.
        return R("PersistentStream", "close with error: " + t), this.stream = null, this.close(3 /* Error */ , t);
    }
    /**
     * Returns a "dispatcher" function that dispatches operations onto the
     * AsyncQueue but only runs them if closeCount remains unchanged. This allows
     * us to turn auth / stream callbacks into no-ops if the stream is closed /
     * re-opened, etc.
     */    ih(t) {
        return e => {
            this.eo.ys((() => this.Wu === t ? e() : (R("PersistentStream", "stream callback skipped by getCloseGuardedDispatcher."), 
            Promise.resolve())));
        };
    }
}

/**
 * A PersistentStream that implements the Listen RPC.
 *
 * Once the Listen stream has called the onOpen() listener, any number of
 * listen() and unlisten() calls can be made to control what changes will be
 * sent from the server for ListenResponses.
 */ class to extends Zr {
    constructor(t, e, n, s, i) {
        super(t, "listen_stream_connection_backoff" /* ListenStreamConnectionBackoff */ , "listen_stream_idle" /* ListenStreamIdle */ , e, n, i), 
        this.Kt = s;
    }
    ah(t) {
        return this.Ku.xu("Listen", t);
    }
    onMessage(t) {
        // A successful response means the stream is healthy
        this.zu.reset();
        const e = ts(this.Kt, t), n = function(t) {
            // We have only reached a consistent snapshot for the entire stream if there
            // is a read_time set and it applies to all targets (i.e. the list of
            // targets is empty). The backend is guaranteed to send such responses.
            if (!("targetChange" in t)) return J.min();
            const e = t.targetChange;
            return e.targetIds && e.targetIds.length ? J.min() : e.readTime ? Un(e.readTime) : J.min();
        }(t);
        return this.listener.uh(e, n);
    }
    /**
     * Registers interest in the results of the given target. If the target
     * includes a resumeToken it will be included in the request. Results that
     * affect the target will be streamed back as WatchChange messages that
     * reference the targetId.
     */    hh(t) {
        const e = {};
        e.database = Hn(this.Kt), e.addTarget = function(t, e) {
            let n;
            const s = e.target;
            return n = qt(s) ? {
                documents: is(t, s)
            } : {
                query: rs(t, s)
            }, n.targetId = e.targetId, e.resumeToken.o() > 0 ? n.resumeToken = Bn(t, e.resumeToken) : e.Mt.u(J.min()) > 0 && (
            // TODO(wuandy): Consider removing above check because it is most likely true.
            // Right now, many tests depend on this behaviour though (leaving min() out
            // of serialization).
            n.readTime = $n(t, e.Mt.G())), n;
        }(this.Kt, t);
        const n = cs(this.Kt, t);
        n && (e.labels = n), this.eh(e);
    }
    /**
     * Unregisters interest in the results of the target associated with the
     * given targetId.
     */    lh(t) {
        const e = {};
        e.database = Hn(this.Kt), e.removeTarget = t, this.eh(e);
    }
}

/**
 * A Stream that implements the Write RPC.
 *
 * The Write RPC requires the caller to maintain special streamToken
 * state in between calls, to help the server understand which responses the
 * client has processed by the time the next request is made. Every response
 * will contain a streamToken; this value must be passed to the next
 * request.
 *
 * After calling start() on this stream, the next request must be a handshake,
 * containing whatever streamToken is on hand. Once a response to this
 * request is received, all pending mutations may be submitted. When
 * submitting multiple batches of mutations at the same time, it's
 * okay to use the same streamToken for the calls to writeMutations.
 *
 * TODO(b/33271235): Use proto types
 */ class eo extends Zr {
    constructor(t, e, n, s, i) {
        super(t, "write_stream_connection_backoff" /* WriteStreamConnectionBackoff */ , "write_stream_idle" /* WriteStreamIdle */ , e, n, i), 
        this.Kt = s, this._h = !1;
    }
    /**
     * Tracks whether or not a handshake has been successfully exchanged and
     * the stream is ready to accept mutations.
     */    get fh() {
        return this._h;
    }
    // Override of PersistentStream.start
    start() {
        this._h = !1, this.lastStreamToken = void 0, super.start();
    }
    sh() {
        this._h && this.dh([]);
    }
    ah(t) {
        return this.Ku.xu("Write", t);
    }
    onMessage(t) {
        if (
        // Always capture the last stream token.
        p(!!t.streamToken), this.lastStreamToken = t.streamToken, this._h) {
            // A successful first write response means the stream is healthy,
            // Note, that we could consider a successful handshake healthy, however,
            // the write itself might be causing an error we want to back off from.
            this.zu.reset();
            const e = ss(t.writeResults, t.commitTime), n = Un(t.commitTime);
            return this.listener.wh(n, e);
        }
        // The first response is always the handshake response
        return p(!t.writeResults || 0 === t.writeResults.length), this._h = !0, this.listener.Eh();
    }
    /**
     * Sends an initial streamToken to the server, performing the handshake
     * required to make the StreamingWrite RPC work. Subsequent
     * calls should wait until onHandshakeComplete was called.
     */    Th() {
        // TODO(dimond): Support stream resumption. We intentionally do not set the
        // stream token on the handshake, ignoring any stream token we might have.
        const t = {};
        t.database = Hn(this.Kt), this.eh(t);
    }
    /** Sends a group of mutations to the Firestore backend to apply. */    dh(t) {
        const e = {
            streamToken: this.lastStreamToken,
            writes: t.map((t => es(this.Kt, t)))
        };
        this.eh(e);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Datastore and its related methods are a wrapper around the external Google
 * Cloud Datastore grpc API, which provides an interface that is more convenient
 * for the rest of the client SDK architecture to consume.
 */
/**
 * An implementation of Datastore that exposes additional state for internal
 * consumption.
 */
class no extends class {} {
    constructor(t, e, n) {
        super(), this.credentials = t, this.Ku = e, this.Kt = n, this.Ih = !1;
    }
    mh() {
        if (this.Ih) throw new F(O.FAILED_PRECONDITION, "The client has already been terminated.");
    }
    /** Gets an auth token and invokes the provided RPC. */    bu(t, e, n) {
        return this.mh(), this.credentials.getToken().then((s => this.Ku.bu(t, e, n, s))).catch((t => {
            throw t.code === O.UNAUTHENTICATED && this.credentials.v(), t;
        }));
    }
    /** Gets an auth token and invokes the provided RPC with streamed results. */    Cu(t, e, n) {
        return this.mh(), this.credentials.getToken().then((s => this.Ku.Cu(t, e, n, s))).catch((t => {
            throw t.code === O.UNAUTHENTICATED && this.credentials.v(), t;
        }));
    }
    terminate() {
        this.Ih = !1;
    }
}

// TODO(firestorexp): Make sure there is only one Datastore instance per
// firestore-exp client.
/**
 * A component used by the RemoteStore to track the OnlineState (that is,
 * whether or not the client as a whole should be considered to be online or
 * offline), implementing the appropriate heuristics.
 *
 * In particular, when the client is trying to connect to the backend, we
 * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for
 * a connection to succeed. If we have too many failures or the timeout elapses,
 * then we set the OnlineState to Offline, and the client will behave as if
 * it is offline (get()s will return cached data, etc.).
 */
class so {
    constructor(t, e) {
        this.fs = t, this.da = e, 
        /** The current OnlineState. */
        this.state = "Unknown" /* Unknown */ , 
        /**
         * A count of consecutive failures to open the stream. If it reaches the
         * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to
         * Offline.
         */
        this.Ah = 0, 
        /**
         * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we
         * transition from OnlineState.Unknown to OnlineState.Offline without waiting
         * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).
         */
        this.Rh = null, 
        /**
         * Whether the client should log a warning message if it fails to connect to
         * the backend (initially true, cleared after a successful stream, or if we've
         * logged the message already).
         */
        this.Ph = !0;
    }
    /**
     * Called by RemoteStore when a watch stream is started (including on each
     * backoff attempt).
     *
     * If this is the first attempt, it sets the OnlineState to Unknown and starts
     * the onlineStateTimer.
     */    yh() {
        0 === this.Ah && (this.gh("Unknown" /* Unknown */), this.Rh = this.fs.Ir("online_state_timeout" /* OnlineStateTimeout */ , 1e4, (() => (this.Rh = null, 
        this.Vh("Backend didn't respond within 10 seconds."), this.gh("Offline" /* Offline */), 
        Promise.resolve()))));
    }
    /**
     * Updates our OnlineState as appropriate after the watch stream reports a
     * failure. The first failure moves us to the 'Unknown' state. We then may
     * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we
     * actually transition to the 'Offline' state.
     */    ph(t) {
        "Online" /* Online */ === this.state ? this.gh("Unknown" /* Unknown */) : (this.Ah++, 
        this.Ah >= 1 && (this.bh(), this.Vh("Connection failed 1 times. Most recent error: " + t.toString()), 
        this.gh("Offline" /* Offline */)));
    }
    /**
     * Explicitly sets the OnlineState to the specified state.
     *
     * Note that this resets our timers / failure counters, etc. used by our
     * Offline heuristics, so must not be used in place of
     * handleWatchStreamStart() and handleWatchStreamFailure().
     */    set(t) {
        this.bh(), this.Ah = 0, "Online" /* Online */ === t && (
        // We've connected to watch at least once. Don't warn the developer
        // about being offline going forward.
        this.Ph = !1), this.gh(t);
    }
    gh(t) {
        t !== this.state && (this.state = t, this.da(t));
    }
    Vh(t) {
        const e = `Could not reach Cloud Firestore backend. ${t}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;
        this.Ph ? (P(e), this.Ph = !1) : R("OnlineStateTracker", e);
    }
    bh() {
        null !== this.Rh && (this.Rh.cancel(), this.Rh = null);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class io {
    constructor(
    /**
     * The local store, used to fill the write pipeline with outbound mutations.
     */
    t, 
    /** The client-side proxy for interacting with the backend. */
    e, n, s, i) {
        this.Sh = t, this.Dh = e, this.fs = n, this.Ch = {}, 
        /**
         * A list of up to MAX_PENDING_WRITES writes that we have fetched from the
         * LocalStore via fillWritePipeline() and have or will send to the write
         * stream.
         *
         * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or
         * restart the write stream. When the stream is established the writes in the
         * pipeline will be sent in order.
         *
         * Writes remain in writePipeline until they are acknowledged by the backend
         * and thus will automatically be re-sent if the stream is interrupted /
         * restarted before they're acknowledged.
         *
         * Write responses from the backend are linked to their originating request
         * purely based on order, and so we can just shift() writes from the front of
         * the writePipeline as we receive responses.
         */
        this.xh = [], 
        /**
         * A mapping of watched targets that the client cares about tracking and the
         * user has explicitly called a 'listen' for this target.
         *
         * These targets may or may not have been sent to or acknowledged by the
         * server. On re-establishing the listen stream, these targets should be sent
         * to the server. The targets removed with unlistens are removed eagerly
         * without waiting for confirmation from the listen stream.
         */
        this.Nh = new Map, 
        /**
         * A set of reasons for why the RemoteStore may be offline. If empty, the
         * RemoteStore may start its network connections.
         */
        this.Oh = new Set, 
        /**
         * Event handlers that get called when the network is disabled or enabled.
         *
         * PORTING NOTE: These functions are used on the Web client to create the
         * underlying streams (to support tree-shakeable streams). On Android and iOS,
         * the streams are created during construction of RemoteStore.
         */
        this.Fh = [], this.kh = i, this.kh.cu((t => {
            n.ys((async () => {
                // Porting Note: Unlike iOS, `restartNetwork()` is called even when the
                // network becomes unreachable as we don't have any other way to tear
                // down our streams.
                fo(this) && (R("RemoteStore", "Restarting streams for network reachability change."), 
                await async function(t) {
                    const e = b(t);
                    e.Oh.add(4 /* ConnectivityChange */), await oo(e), e.Mh.set("Unknown" /* Unknown */), 
                    e.Oh.delete(4 /* ConnectivityChange */), await ro(e);
                }(this));
            }));
        })), this.Mh = new so(n, s);
    }
}

async function ro(t) {
    if (fo(t)) for (const e of t.Fh) await e(/* enabled= */ !0);
}

/**
 * Temporarily disables the network. The network can be re-enabled using
 * enableNetwork().
 */ async function oo(t) {
    for (const e of t.Fh) await e(/* enabled= */ !1);
}

/**
 * Starts new listen for the given target. Uses resume token if provided. It
 * is a no-op if the target of given `TargetData` is already being listened to.
 */
function co(t, e) {
    const n = b(t);
    n.Nh.has(e.targetId) || (
    // Mark this as something the client is currently listening for.
    n.Nh.set(e.targetId, e), _o(n) ? 
    // The listen will be sent in onWatchStreamOpen
    lo(n) : Co(n).Ju() && uo(n, e));
}

/**
 * Removes the listen from server. It is a no-op if the given target id is
 * not being listened to.
 */ function ao(t, e) {
    const n = b(t), s = Co(n);
    n.Nh.delete(e), s.Ju() && ho(n, e), 0 === n.Nh.size && (s.Ju() ? s.Zu() : fo(n) && 
    // Revert to OnlineState.Unknown if the watch stream is not open and we
    // have no listeners, since without any listens to send we cannot
    // confirm if the stream is healthy and upgrade to OnlineState.Online.
    n.Mh.set("Unknown" /* Unknown */));
}

/**
 * We need to increment the the expected number of pending responses we're due
 * from watch so we wait for the ack to process any messages from this target.
 */ function uo(t, e) {
    t.Lh.cn(e.targetId), Co(t).hh(e);
}

/**
 * We need to increment the expected number of pending responses we're due
 * from watch so we wait for the removal on the server before we process any
 * messages from this target.
 */ function ho(t, e) {
    t.Lh.cn(e), Co(t).lh(e);
}

function lo(t) {
    t.Lh = new Nn({
        Sn: e => t.Ch.Sn(e),
        Dn: e => t.Nh.get(e) || null
    }), Co(t).start(), t.Mh.yh();
}

/**
 * Returns whether the watch stream should be started because it's necessary
 * and has not yet been started.
 */ function _o(t) {
    return fo(t) && !Co(t).Hu() && t.Nh.size > 0;
}

function fo(t) {
    return 0 === b(t).Oh.size;
}

function wo(t) {
    t.Lh = void 0;
}

async function Eo(t) {
    t.Nh.forEach(((e, n) => {
        uo(t, e);
    }));
}

async function To(t, e) {
    wo(t), 
    // If we still need the watch stream, retry the connection.
    _o(t) ? (t.Mh.ph(e), lo(t)) : 
    // No need to restart watch stream because there are no active targets.
    // The online state is set to unknown because there is no active attempt
    // at establishing a connection
    t.Mh.set("Unknown" /* Unknown */);
}

async function Io(t, e, n) {
    if (
    // Mark the client as online since we got a message from the server
    t.Mh.set("Online" /* Online */), e instanceof Cn && 2 /* Removed */ === e.state && e.cause) 
    // There was an error on a target, don't wait for a consistent snapshot
    // to raise events
    try {
        await 
        /** Handles an error on a target */
        async function(t, e) {
            const n = e.cause;
            for (const s of e.targetIds) 
            // A watched target might have been removed already.
            t.Nh.has(s) && (await t.Ch.$h(s, n), t.Nh.delete(s), t.Lh.removeTarget(s));
        }
        /**
 * Attempts to fill our write pipeline with writes from the LocalStore.
 *
 * Called internally to bootstrap or refill the write pipeline and by
 * SyncEngine whenever there are new mutations to process.
 *
 * Starts the write stream if necessary.
 */ (t, e);
    } catch (n) {
        R("RemoteStore", "Failed to remove targets %s: %s ", e.targetIds.join(","), n), 
        await mo(t, n);
    } else if (e instanceof Sn ? t.Lh.wn(e) : e instanceof Dn ? t.Lh.yn(e) : t.Lh.In(e), 
    !n.isEqual(J.min())) try {
        const e = await _r(t.Sh);
        n.u(e) >= 0 && 
        // We have received a target change with a global snapshot if the snapshot
        // version is not equal to SnapshotVersion.min().
        await 
        /**
 * Takes a batch of changes from the Datastore, repackages them as a
 * RemoteEvent, and passes that on to the listener, which is typically the
 * SyncEngine.
 */
        function(t, e) {
            const n = t.Lh.pn(e);
            // Update in-memory resume tokens. LocalStore will update the
            // persistent view of these when applying the completed RemoteEvent.
                        return n.Fe.forEach(((n, s) => {
                if (n.resumeToken.o() > 0) {
                    const i = t.Nh.get(s);
                    // A watched target might have been removed already.
                                        i && t.Nh.set(s, i.$t(n.resumeToken, e));
                }
            })), 
            // Re-establish listens for the targets that have been invalidated by
            // existence filter mismatches.
            n.ke.forEach((e => {
                const n = t.Nh.get(e);
                if (!n) 
                // A watched target might have been removed already.
                return;
                // Clear the resume token for the target, since we're in a known mismatch
                // state.
                                t.Nh.set(e, n.$t(N.h, n.Mt)), 
                // Cause a hard reset by unwatching and rewatching immediately, but
                // deliberately don't send a resume token so that we get a full update.
                ho(t, e);
                // Mark the target we send as being on behalf of an existence filter
                // mismatch, but don't actually retain that in listenTargets. This ensures
                // that we flag the first re-listen this way without impacting future
                // listens of this target (that might happen e.g. on reconnect).
                const s = new Re(n.target, e, 1 /* ExistenceFilterMismatch */ , n.sequenceNumber);
                uo(t, s);
            })), t.Ch.Bh(n);
        }(t, n);
    } catch (e) {
        R("RemoteStore", "Failed to raise snapshot:", e), await mo(t, e);
    }
}

/**
 * Recovery logic for IndexedDB errors that takes the network offline until
 * `op` succeeds. Retries are scheduled with backoff using
 * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is
 * validated via a generic operation.
 *
 * The returned Promise is resolved once the network is disabled and before
 * any retry attempt.
 */ async function mo(t, e, n) {
    if (!Vs(e)) throw e;
    t.Oh.add(1 /* IndexedDbFailed */), 
    // Disable network and raise offline snapshots
    await oo(t), t.Mh.set("Offline" /* Offline */), n || (
    // Use a simple read operation to determine if IndexedDB recovered.
    // Ideally, we would expose a health check directly on SimpleDb, but
    // RemoteStore only has access to persistence through LocalStore.
    n = () => _r(t.Sh)), 
    // Probe IndexedDB periodically and re-enable network
    t.fs.bo((async () => {
        R("RemoteStore", "Retrying IndexedDB access"), await n(), t.Oh.delete(1 /* IndexedDbFailed */), 
        await ro(t);
    }));
}

/**
 * Executes `op`. If `op` fails, takes the network offline until `op`
 * succeeds. Returns after the first attempt.
 */ function Ao(t, e) {
    return e().catch((n => mo(t, n, e)));
}

async function Ro(t) {
    const e = b(t), n = xo(e);
    let s = e.xh.length > 0 ? e.xh[e.xh.length - 1].batchId : -1;
    for (;Po(e); ) try {
        const t = await wr(e.Sh, s);
        if (null === t) {
            0 === e.xh.length && n.Zu();
            break;
        }
        s = t.batchId, yo(e, t);
    } catch (t) {
        await mo(e, t);
    }
    go(e) && Vo(e);
}

/**
 * Returns true if we can add to the write pipeline (i.e. the network is
 * enabled and the write pipeline is not full).
 */ function Po(t) {
    return fo(t) && t.xh.length < 10;
}

/**
 * Queues additional writes to be sent to the write stream, sending them
 * immediately if the write stream is established.
 */ function yo(t, e) {
    t.xh.push(e);
    const n = xo(t);
    n.Ju() && n.fh && n.dh(e.mutations);
}

function go(t) {
    return fo(t) && !xo(t).Hu() && t.xh.length > 0;
}

function Vo(t) {
    xo(t).start();
}

async function po(t) {
    xo(t).Th();
}

async function bo(t) {
    const e = xo(t);
    // Send the write pipeline now that the stream is established.
        for (const n of t.xh) e.dh(n.mutations);
}

async function vo(t, e, n) {
    const s = t.xh.shift(), i = ii.from(s, e, n);
    await Ao(t, (() => t.Ch.qh(i))), 
    // It's possible that with the completion of this mutation another
    // slot has freed up.
    await Ro(t);
}

async function So(t, e) {
    // If the write stream closed after the write handshake completes, a write
    // operation failed and we fail the pending operation.
    e && xo(t).fh && 
    // This error affects the actual write.
    await async function(t, e) {
        // Only handle permanent errors here. If it's transient, just let the retry
        // logic kick in.
        if (n = e.code, on(n) && n !== O.ABORTED) {
            // This was a permanent error, the request itself was the problem
            // so it's not going to succeed if we resend it.
            const n = t.xh.shift();
            // In this case it's also unlikely that the server itself is melting
            // down -- this was just a bad request so inhibit backoff on the next
            // restart.
                        xo(t).Xu(), await Ao(t, (() => t.Ch.Uh(n.batchId, e))), 
            // It's possible that with the completion of this mutation
            // another slot has freed up.
            await Ro(t);
        }
        var n;
    }(t, e), 
    // The write stream might have been started by refilling the write
    // pipeline for failed writes
    go(t) && Vo(t);
}

/**
 * Toggles the network state when the client gains or loses its primary lease.
 */
async function Do(t, e) {
    const n = b(t);
    e ? (n.Oh.delete(2 /* IsSecondary */), await ro(n)) : e || (n.Oh.add(2 /* IsSecondary */), 
    await oo(n), n.Mh.set("Unknown" /* Unknown */));
}

/**
 * If not yet initialized, registers the WatchStream and its network state
 * callback with `remoteStoreImpl`. Returns the existing stream if one is
 * already available.
 *
 * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.
 * This is not done on Web to allow it to be tree-shaken.
 */ function Co(t) {
    return t.Qh || (
    // Create stream (but note that it is not started yet).
    t.Qh = function(t, e, n) {
        const s = b(t);
        return s.mh(), new to(e, s.Ku, s.credentials, s.Kt, n);
    }
    /**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ (t.Dh, t.fs, {
        Eu: Eo.bind(null, t),
        Iu: To.bind(null, t),
        uh: Io.bind(null, t)
    }), t.Fh.push((async e => {
        e ? (t.Qh.Xu(), _o(t) ? lo(t) : t.Mh.set("Unknown" /* Unknown */)) : (await t.Qh.stop(), 
        wo(t));
    }))), t.Qh;
}

/**
 * If not yet initialized, registers the WriteStream and its network state
 * callback with `remoteStoreImpl`. Returns the existing stream if one is
 * already available.
 *
 * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.
 * This is not done on Web to allow it to be tree-shaken.
 */ function xo(t) {
    return t.Kh || (
    // Create stream (but note that it is not started yet).
    t.Kh = function(t, e, n) {
        const s = b(t);
        return s.mh(), new eo(e, s.Ku, s.credentials, s.Kt, n);
    }(t.Dh, t.fs, {
        Eu: po.bind(null, t),
        Iu: So.bind(null, t),
        Eh: bo.bind(null, t),
        wh: vo.bind(null, t)
    }), t.Fh.push((async e => {
        e ? (t.Kh.Xu(), 
        // This will start the write stream if necessary.
        await Ro(t)) : (await t.Kh.stop(), t.xh.length > 0 && (R("RemoteStore", `Stopping write stream with ${t.xh.length} pending writes`), 
        t.xh = []));
    }))), t.Kh;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Holds the listeners and the last received ViewSnapshot for a query being
 * tracked by EventManager.
 */ class No {
    constructor() {
        this.jh = void 0, this.listeners = [];
    }
}

class Oo {
    constructor() {
        this.queries = new pi((t => Ee(t)), we), this.onlineState = "Unknown" /* Unknown */ , 
        this.Wh = new Set;
    }
}

async function Fo(t, e) {
    const n = b(t), s = e.query;
    let i = !1, r = n.queries.get(s);
    if (r || (i = !0, r = new No), i) try {
        r.jh = await n.Gh(s);
    } catch (t) {
        const n = Cs(t, `Initialization of query '${Te(e.query)}' failed`);
        return void e.onError(n);
    }
    n.queries.set(s, r), r.listeners.push(e);
    // Run global snapshot listeners if a consistent snapshot has been emitted.
    e.zh(n.onlineState);
    if (r.jh) {
        e.Hh(r.jh) && $o(n);
    }
}

async function ko(t, e) {
    const n = b(t), s = e.query;
    let i = !1;
    const r = n.queries.get(s);
    if (r) {
        const t = r.listeners.indexOf(e);
        t >= 0 && (r.listeners.splice(t, 1), i = 0 === r.listeners.length);
    }
    if (i) return n.queries.delete(s), n.Jh(s);
}

function Mo(t, e) {
    const n = b(t);
    let s = !1;
    for (const t of e) {
        const e = t.query, i = n.queries.get(e);
        if (i) {
            for (const e of i.listeners) e.Hh(t) && (s = !0);
            i.jh = t;
        }
    }
    s && $o(n);
}

function Lo(t, e, n) {
    const s = b(t), i = s.queries.get(e);
    if (i) for (const t of i.listeners) t.onError(n);
    // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()
    // after an error.
        s.queries.delete(e);
}

// Call all global snapshot listeners that have been set.
function $o(t) {
    t.Wh.forEach((t => {
        t.next();
    }));
}

/**
 * QueryListener takes a series of internal view snapshots and determines
 * when to raise the event.
 *
 * It uses an Observer to dispatch events.
 */ class Bo {
    constructor(t, e, n) {
        this.query = t, this.Yh = e, 
        /**
         * Initial snapshots (e.g. from cache) may not be propagated to the wrapped
         * observer. This flag is set to true once we've actually raised an event.
         */
        this.Xh = !1, this.Zh = null, this.onlineState = "Unknown" /* Unknown */ , this.options = n || {};
    }
    /**
     * Applies the new ViewSnapshot to this listener, raising a user-facing event
     * if applicable (depending on what changed, whether the user has opted into
     * metadata-only changes, etc.). Returns true if a user-facing event was
     * indeed raised.
     */    Hh(t) {
        if (!this.options.includeMetadataChanges) {
            // Remove the metadata only changes.
            const e = [];
            for (const n of t.docChanges) 3 /* Metadata */ !== n.type && e.push(n);
            t = new pn(t.query, t.docs, t.De, e, t.Ce, t.fromCache, t.xe, 
            /* excludesMetadataChanges= */ !0);
        }
        let e = !1;
        return this.Xh ? this.tl(t) && (this.Yh.next(t), e = !0) : this.el(t, this.onlineState) && (this.nl(t), 
        e = !0), this.Zh = t, e;
    }
    onError(t) {
        this.Yh.error(t);
    }
    /** Returns whether a snapshot was raised. */    zh(t) {
        this.onlineState = t;
        let e = !1;
        return this.Zh && !this.Xh && this.el(this.Zh, t) && (this.nl(this.Zh), e = !0), 
        e;
    }
    el(t, e) {
        // Always raise the first event when we're synced
        if (!t.fromCache) return !0;
        // NOTE: We consider OnlineState.Unknown as online (it should become Offline
        // or Online if we wait long enough).
                const n = "Offline" /* Offline */ !== e;
        // Don't raise the event if we're online, aren't synced yet (checked
        // above) and are waiting for a sync.
                return (!this.options.sl || !n) && (!t.docs.nt() || "Offline" /* Offline */ === e);
        // Raise data from cache if we have any documents or we are offline
        }
    tl(t) {
        // We don't need to handle includeDocumentMetadataChanges here because
        // the Metadata only changes have already been stripped out if needed.
        // At this point the only changes we will see are the ones we should
        // propagate.
        if (t.docChanges.length > 0) return !0;
        const e = this.Zh && this.Zh.hasPendingWrites !== t.hasPendingWrites;
        return !(!t.xe && !e) && !0 === this.options.includeMetadataChanges;
        // Generally we should have hit one of the cases above, but it's possible
        // to get here if there were only metadata docChanges and they got
        // stripped out.
        }
    nl(t) {
        t = pn.Oe(t.query, t.docs, t.Ce, t.fromCache), this.Xh = !0, this.Yh.next(t);
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A complete element in the bundle stream, together with the byte length it
 * occupies in the stream.
 */ class qo {
    constructor(t, 
    // How many bytes this element takes to store in the bundle.
    e) {
        this.payload = t, this.byteLength = e;
    }
    il() {
        return "metadata" in this.payload;
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Helper to convert objects from bundles to model objects in the SDK.
 */ class Uo {
    constructor(t) {
        this.Kt = t;
    }
    yc(t) {
        return Wn(this.Kt, t);
    }
    /**
     * Converts a BundleDocument to a MaybeDocument.
     */    gc(t) {
        return t.metadata.exists ? Xn(this.Kt, t.document, !1) : new Ot(this.yc(t.metadata.name), this.Vc(t.metadata.readTime));
    }
    Vc(t) {
        return Un(t);
    }
}

/**
 * A class to process the elements from a bundle, load them into local
 * storage and provide progress update while loading.
 */ class Qo {
    constructor(t, e, n) {
        this.rl = t, this.Sh = e, this.Kt = n, 
        /** Batched queries to be saved into storage */
        this.queries = [], 
        /** Batched documents to be saved into storage */
        this.documents = [], this.progress = Ko(t);
    }
    /**
     * Adds an element from the bundle to the loader.
     *
     * Returns a new progress if adding the element leads to a new progress,
     * otherwise returns null.
     */    ol(t) {
        this.progress.bytesLoaded += t.byteLength;
        let e = this.progress.documentsLoaded;
        return t.payload.namedQuery ? this.queries.push(t.payload.namedQuery) : t.payload.documentMetadata ? (this.documents.push({
            metadata: t.payload.documentMetadata
        }), t.payload.documentMetadata.exists || ++e) : t.payload.document && (this.documents[this.documents.length - 1].document = t.payload.document, 
        ++e), e !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = e, 
        Object.assign({}, this.progress)) : null;
    }
    cl(t) {
        const e = new Map, n = new Uo(this.Kt);
        for (const s of t) if (s.metadata.queries) {
            const t = n.yc(s.metadata.name);
            for (const n of s.metadata.queries) {
                const s = (e.get(n) || Rn()).add(t);
                e.set(n, s);
            }
        }
        return e;
    }
    /**
     * Update the progress to 'Success' and return the updated progress.
     */    async complete() {
        const t = await Pr(this.Sh, new Uo(this.Kt), this.documents, this.rl.id), e = this.cl(this.documents);
        for (const t of this.queries) await yr(this.Sh, t, e.get(t.name));
        return this.progress.taskState = "Success", new ir(Object.assign({}, this.progress), t);
    }
}

/**
 * Returns a `LoadBundleTaskProgress` representing the initial progress of
 * loading a bundle.
 */ function Ko(t) {
    return {
        taskState: "Running",
        documentsLoaded: 0,
        bytesLoaded: 0,
        totalDocuments: t.totalDocuments,
        totalBytes: t.totalBytes
    };
}

/**
 * Returns a `LoadBundleTaskProgress` representing the progress that the loading
 * has succeeded.
 */
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class jo {
    constructor(t) {
        this.key = t;
    }
}

class Wo {
    constructor(t) {
        this.key = t;
    }
}

/**
 * View is responsible for computing the final merged truth of what docs are in
 * a query. It gets notified of local and remote changes to docs, and applies
 * the query filters and limits to determine the most correct possible results.
 */ class Go {
    constructor(t, 
    /** Documents included in the remote target */
    e) {
        this.query = t, this.al = e, this.ul = null, 
        /**
         * A flag whether the view is current with the backend. A view is considered
         * current after it has seen the current flag from the backend and did not
         * lose consistency within the watch stream (e.g. because of an existence
         * filter mismatch).
         */
        this.qe = !1, 
        /** Documents in the view but not in the remote target */
        this.hl = Rn(), 
        /** Document Keys that have local changes */
        this.Ce = Rn(), this.ll = me(t), this._l = new gn(this.ll);
    }
    /**
     * The set of remote documents that the server has told us belongs to the target associated with
     * this view.
     */    get fl() {
        return this.al;
    }
    /**
     * Iterates over a set of doc changes, applies the query limit, and computes
     * what the new results should be, what the changes were, and whether we may
     * need to go back to the local cache for more results. Does not make any
     * changes to the view.
     * @param docChanges - The doc changes to apply to this view.
     * @param previousChanges - If this is being called with a refill, then start
     *        with this set of docs and changes instead of the current view.
     * @returns a new set of docs, changes, and refill flag.
     */    dl(t, e) {
        const n = e ? e.wl : new Vn, s = e ? e._l : this._l;
        let i = e ? e.Ce : this.Ce, r = s, o = !1;
        // Track the last doc in a (full) limit. This is necessary, because some
        // update (a delete, or an update moving a doc past the old limit) might
        // mean there is some other document in the local cache that either should
        // come (1) between the old last limit doc and the new last document, in the
        // case of updates, or (2) after the new last document, in the case of
        // deletes. So we keep this doc at the old limit to compare the updates to.
        // Note that this should never get used in a refill (when previousChanges is
        // set), because there will only be adds -- no deletes or updates.
        const c = ce(this.query) && s.size === this.query.limit ? s.last() : null, a = ae(this.query) && s.size === this.query.limit ? s.first() : null;
        // Drop documents out to meet limit/limitToLast requirement.
        if (t.Zt(((t, e) => {
            const u = s.get(t);
            let h = e instanceof Nt ? e : null;
            h && (h = Ie(this.query, h) ? h : null);
            const l = !!u && this.Ce.has(u.key), _ = !!h && (h.bt || 
            // We only consider committed mutations for documents that were
            // mutated during the lifetime of the view.
            this.Ce.has(h.key) && h.hasCommittedMutations);
            let f = !1;
            // Calculate change
                        if (u && h) {
                u.data().isEqual(h.data()) ? l !== _ && (n.track({
                    type: 3 /* Metadata */ ,
                    doc: h
                }), f = !0) : this.El(u, h) || (n.track({
                    type: 2 /* Modified */ ,
                    doc: h
                }), f = !0, (c && this.ll(h, c) > 0 || a && this.ll(h, a) < 0) && (
                // This doc moved from inside the limit to outside the limit.
                // That means there may be some other doc in the local cache
                // that should be included instead.
                o = !0));
            } else !u && h ? (n.track({
                type: 0 /* Added */ ,
                doc: h
            }), f = !0) : u && !h && (n.track({
                type: 1 /* Removed */ ,
                doc: u
            }), f = !0, (c || a) && (
            // A doc was removed from a full limit query. We'll need to
            // requery from the local cache to see if we know about some other
            // doc that should be in the results.
            o = !0));
            f && (h ? (r = r.add(h), i = _ ? i.add(t) : i.delete(t)) : (r = r.delete(t), i = i.delete(t)));
        })), ce(this.query) || ae(this.query)) for (;r.size > this.query.limit; ) {
            const t = ce(this.query) ? r.last() : r.first();
            r = r.delete(t.key), i = i.delete(t.key), n.track({
                type: 1 /* Removed */ ,
                doc: t
            });
        }
        return {
            _l: r,
            wl: n,
            _c: o,
            Ce: i
        };
    }
    El(t, e) {
        // We suppress the initial change event for documents that were modified as
        // part of a write acknowledgment (e.g. when the value of a server transform
        // is applied) as Watch will send us the same document again.
        // By suppressing the event, we only raise two user visible events (one with
        // `hasPendingWrites` and the final state of the document) instead of three
        // (one with `hasPendingWrites`, the modified document with
        // `hasPendingWrites` and the final state of the document).
        return t.bt && e.hasCommittedMutations && !e.bt;
    }
    /**
     * Updates the view with the given ViewDocumentChanges and optionally updates
     * limbo docs and sync state from the provided target change.
     * @param docChanges - The set of changes to make to the view's docs.
     * @param updateLimboDocuments - Whether to update limbo documents based on
     *        this change.
     * @param targetChange - A target change to apply for computing limbo docs and
     *        sync state.
     * @returns A new ViewChange with the given docs, changes, and sync state.
     */
    // PORTING NOTE: The iOS/Android clients always compute limbo document changes.
    Ei(t, e, n) {
        const s = this._l;
        this._l = t._l, this.Ce = t.Ce;
        // Sort changes based on type and query comparator
        const i = t.wl.Se();
        i.sort(((t, e) => function(t, e) {
            const n = t => {
                switch (t) {
                  case 0 /* Added */ :
                    return 1;

                  case 2 /* Modified */ :
                  case 3 /* Metadata */ :
                    // A metadata change is converted to a modified change at the public
                    // api layer.  Since we sort by document key and then change type,
                    // metadata and modified changes must be sorted equivalently.
                    return 2;

                  case 1 /* Removed */ :
                    return 0;

                  default:
                    return V();
                }
            };
            return n(t) - n(e);
        }
        /**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ (t.type, e.type) || this.ll(t.doc, e.doc))), this.Tl(n);
        const r = e ? this.Il() : [], o = 0 === this.hl.size && this.qe ? 1 /* Synced */ : 0 /* Local */ , c = o !== this.ul;
        if (this.ul = o, 0 !== i.length || c) {
            return {
                snapshot: new pn(this.query, t._l, s, i, t.Ce, 0 /* Local */ === o, c, 
                /* excludesMetadataChanges= */ !1),
                ml: r
            };
        }
        // no changes
        return {
            ml: r
        };
    }
    /**
     * Applies an OnlineState change to the view, potentially generating a
     * ViewChange if the view's syncState changes as a result.
     */    zh(t) {
        return this.qe && "Offline" /* Offline */ === t ? (
        // If we're offline, set `current` to false and then call applyChanges()
        // to refresh our syncState and generate a ViewChange as appropriate. We
        // are guaranteed to get a new TargetChange that sets `current` back to
        // true once the client is back online.
        this.qe = !1, this.Ei({
            _l: this._l,
            wl: new Vn,
            Ce: this.Ce,
            _c: !1
        }, 
        /* updateLimboDocuments= */ !1)) : {
            ml: []
        };
    }
    /**
     * Returns whether the doc for the given key should be in limbo.
     */    Al(t) {
        // If the remote end says it's part of this query, it's not in limbo.
        return !this.al.has(t) && (
        // The local store doesn't think it's a result, so it shouldn't be in limbo.
        !!this._l.has(t) && !this._l.get(t).bt);
    }
    /**
     * Updates syncedDocuments, current, and limbo docs based on the given change.
     * Returns the list of changes to which docs are in limbo.
     */    Tl(t) {
        t && (t.Ue.forEach((t => this.al = this.al.add(t))), t.Qe.forEach((t => {})), t.Ke.forEach((t => this.al = this.al.delete(t))), 
        this.qe = t.qe);
    }
    Il() {
        // We can only determine limbo documents when we're in-sync with the server.
        if (!this.qe) return [];
        // TODO(klimt): Do this incrementally so that it's not quadratic when
        // updating many documents.
                const t = this.hl;
        this.hl = Rn(), this._l.forEach((t => {
            this.Al(t.key) && (this.hl = this.hl.add(t.key));
        }));
        // Diff the new limbo docs with the old limbo docs.
        const e = [];
        return t.forEach((t => {
            this.hl.has(t) || e.push(new Wo(t));
        })), this.hl.forEach((n => {
            t.has(n) || e.push(new jo(n));
        })), e;
    }
    /**
     * Update the in-memory state of the current view with the state read from
     * persistence.
     *
     * We update the query view whenever a client's primary status changes:
     * - When a client transitions from primary to secondary, it can miss
     *   LocalStorage updates and its query views may temporarily not be
     *   synchronized with the state on disk.
     * - For secondary to primary transitions, the client needs to update the list
     *   of `syncedDocuments` since secondary clients update their query views
     *   based purely on synthesized RemoteEvents.
     *
     * @param queryResult.documents - The documents that match the query according
     * to the LocalStore.
     * @param queryResult.remoteKeys - The keys of the documents that match the
     * query according to the backend.
     *
     * @returns The ViewChange that resulted from this synchronization.
     */
    // PORTING NOTE: Multi-tab only.
    Rl(t) {
        this.al = t.Pc, this.hl = Rn();
        const e = this.dl(t.documents);
        return this.Ei(e, /*updateLimboDocuments=*/ !0);
    }
    /**
     * Returns a view snapshot as if this query was just listened to. Contains
     * a document add for every existing document and the `fromCache` and
     * `hasPendingWrites` status of the already established view.
     */
    // PORTING NOTE: Multi-tab only.
    Pl() {
        return pn.Oe(this.query, this._l, this.Ce, 0 /* Local */ === this.ul);
    }
}

/**
 * QueryView contains all of the data that SyncEngine needs to keep track of for
 * a particular query.
 */
class zo {
    constructor(
    /**
     * The query itself.
     */
    t, 
    /**
     * The target number created by the client that is used in the watch
     * stream to identify this query.
     */
    e, 
    /**
     * The view is responsible for computing the final merged truth of what
     * docs are in the query. It gets notified of local and remote changes,
     * and applies the query filters and limits to determine the most correct
     * possible results.
     */
    n) {
        this.query = t, this.targetId = e, this.view = n;
    }
}

/** Tracks a limbo resolution. */ class Ho {
    constructor(t) {
        this.key = t, 
        /**
         * Set to true once we've received a document. This is used in
         * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to
         * decide whether it needs to manufacture a delete event for the target once
         * the target is CURRENT.
         */
        this.yl = !1;
    }
}

/**
 * An implementation of `SyncEngine` coordinating with other parts of SDK.
 *
 * The parts of SyncEngine that act as a callback to RemoteStore need to be
 * registered individually. This is done in `syncEngineWrite()` and
 * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods
 * serve as entry points to RemoteStore's functionality.
 *
 * Note: some field defined in this class might have public access level, but
 * the class is not exported so they are only accessible from this module.
 * This is useful to implement optional features (like bundles) in free
 * functions, such that they are tree-shakeable.
 */ class Jo {
    constructor(t, e, n, 
    // PORTING NOTE: Manages state synchronization in multi-tab environments.
    s, i, r) {
        this.Sh = t, this.gl = e, this.Vl = n, this.pl = s, this.currentUser = i, this.bl = r, 
        this.vl = {}, this.Sl = new pi((t => Ee(t)), we), this.Dl = new Map, 
        /**
         * The keys of documents that are in limbo for which we haven't yet started a
         * limbo resolution query.
         */
        this.Cl = [], 
        /**
         * Keeps track of the target ID for each document that is in limbo with an
         * active target.
         */
        this.xl = new an(et.J), 
        /**
         * Keeps track of the information about an active limbo resolution for each
         * active target ID that was started for the purpose of limbo resolution.
         */
        this.Nl = new Map, this.Ol = new Vr, 
        /** Stores user completion handlers, indexed by User and BatchId. */
        this.Fl = {}, 
        /** Stores user callbacks waiting for all pending writes to be acknowledged. */
        this.kl = new Map, this.Ml = Fi.Bi(), this.onlineState = "Unknown" /* Unknown */ , 
        // The primary state is set to `true` or `false` immediately after Firestore
        // startup. In the interim, a client should only be considered primary if
        // `isPrimary` is true.
        this.Ll = void 0;
    }
    get $l() {
        return !0 === this.Ll;
    }
}

/**
 * Initiates the new listen, resolves promise when listen enqueued to the
 * server. All the subsequent view snapshots or errors are sent to the
 * subscribed handlers. Returns the initial snapshot.
 */
async function Yo(t, e) {
    const n = pc(t);
    let s, i;
    const r = n.Sl.get(e);
    if (r) 
    // PORTING NOTE: With Multi-Tab Web, it is possible that a query view
    // already exists when EventManager calls us for the first time. This
    // happens when the primary tab is already listening to this query on
    // behalf of another tab and the user of the primary also starts listening
    // to the query. EventManager will not have an assigned target ID in this
    // case and calls `listen` to obtain this ID.
    s = r.targetId, n.pl.ka(s), i = r.view.Pl(); else {
        const t = await Er(n.Sh, fe(e)), r = n.pl.ka(t.targetId);
        s = t.targetId, i = await Xo(n, e, s, "current" === r), n.$l && co(n.gl, t);
    }
    return i;
}

/**
 * Registers a view for a previously unknown query and computes its initial
 * snapshot.
 */ async function Xo(t, e, n, s) {
    // PORTING NOTE: On Web only, we inject the code that registers new Limbo
    // targets based on view changes. This allows us to only depend on Limbo
    // changes when user code includes queries.
    t.Bl = (e, n, s) => async function(t, e, n, s) {
        let i = e.view.dl(n);
        i._c && (
        // The query has a limit and some docs were removed, so we need
        // to re-run the query against the local store to make sure we
        // didn't lose any good docs that had been past the limit.
        i = await Ir(t.Sh, e.query, 
        /* usePreviousResults= */ !1).then((({documents: t}) => e.view.dl(t, i))));
        const r = s && s.Fe.get(e.targetId), o = e.view.Ei(i, 
        /* updateLimboDocuments= */ t.$l, r);
        return lc(t, e.targetId, o.ml), o.snapshot;
    }(t, e, n, s);
    const i = await Ir(t.Sh, e, 
    /* usePreviousResults= */ !0), r = new Go(e, i.Pc), o = r.dl(i.documents), c = vn.Be(n, s && "Offline" /* Offline */ !== t.onlineState), a = r.Ei(o, 
    /* updateLimboDocuments= */ t.$l, c);
    lc(t, n, a.ml);
    const u = new zo(e, n, r);
    return t.Sl.set(e, u), t.Dl.has(n) ? t.Dl.get(n).push(e) : t.Dl.set(n, [ e ]), a.snapshot;
}

/** Stops listening to the query. */ async function Zo(t, e) {
    const n = b(t), s = n.Sl.get(e), i = n.Dl.get(s.targetId);
    if (i.length > 1) return n.Dl.set(s.targetId, i.filter((t => !we(t, e)))), void n.Sl.delete(e);
    // No other queries are mapped to the target, clean up the query and the target.
        if (n.$l) {
        // We need to remove the local query target first to allow us to verify
        // whether any other client is still interested in this target.
        n.pl.La(s.targetId);
        n.pl.Ca(s.targetId) || await Tr(n.Sh, s.targetId, 
        /*keepPersistedTargetData=*/ !1).then((() => {
            n.pl.Ba(s.targetId), ao(n.gl, s.targetId), uc(n, s.targetId);
        })).catch(Vi);
    } else uc(n, s.targetId), await Tr(n.Sh, s.targetId, 
    /*keepPersistedTargetData=*/ !0);
}

/**
 * Initiates the write of local mutation batch which involves adding the
 * writes to the mutation queue, notifying the remote store about new
 * mutations and raising events for any changes this write caused.
 *
 * The promise returned by this call is resolved when the above steps
 * have completed, *not* when the write was acked by the backend. The
 * userCallback is resolved once the write was acked/rejected by the
 * backend (or failed locally for any other reason).
 */ async function tc(t, e, n) {
    const s = bc(t);
    try {
        const t = await function(t, e) {
            const n = b(t), s = H.now(), i = e.reduce(((t, e) => t.add(e.key)), Rn());
            let r;
            return n.persistence.runTransaction("Locally write mutations", "readwrite", (t => n.Ic.Zo(t, i).next((i => {
                r = i;
                // For non-idempotent mutations (such as `FieldValue.increment()`),
                // we record the base state in a separate patch mutation. This is
                // later used to guarantee consistent values and prevents flicker
                // even if the backend sends us an update that already includes our
                // transform.
                const o = [];
                for (const t of e) {
                    const e = je(t, r.get(t.key));
                    null != e && 
                    // NOTE: The base state should only be applied if there's some
                    // existing document to override, so use a Precondition of
                    // exists=true
                    o.push(new He(t.key, e, Ct(e.proto.mapValue), Be.exists(!0)));
                }
                return n.Ho.Pi(t, s, o, e);
            })))).then((t => {
                const e = t.Ns(r);
                return {
                    batchId: t.batchId,
                    oi: e
                };
            }));
        }(s.Sh, e);
        s.pl.xa(t.batchId), function(t, e, n) {
            let s = t.Fl[t.currentUser.R()];
            s || (s = new an(D));
            s = s.Ht(e, n), t.Fl[t.currentUser.R()] = s;
        }
        /**
 * Resolves or rejects the user callback for the given batch and then discards
 * it.
 */ (s, t.batchId, n), await dc(s, t.oi), await Ro(s.gl);
    } catch (t) {
        // If we can't persist the mutation, we reject the user callback and
        // don't send the mutation. The user can then retry the write.
        const e = Cs(t, "Failed to persist write");
        n.reject(e);
    }
}

/**
 * Applies one remote event to the sync engine, notifying any views of the
 * changes, and releasing any pending mutation batches that would become
 * visible because of the snapshot version the remote event contains.
 */ async function ec(t, e) {
    const n = b(t);
    try {
        const t = await fr(n.Sh, e);
        // Update `receivedDocument` as appropriate for any limbo targets.
                e.Fe.forEach(((t, e) => {
            const s = n.Nl.get(e);
            s && (
            // Since this is a limbo resolution lookup, it's for a single document
            // and it could be added, modified, or removed, but not a combination.
            p(t.Ue.size + t.Qe.size + t.Ke.size <= 1), t.Ue.size > 0 ? s.yl = !0 : t.Qe.size > 0 ? p(s.yl) : t.Ke.size > 0 && (p(s.yl), 
            s.yl = !1));
        })), await dc(n, t, e);
    } catch (t) {
        await Vi(t);
    }
}

/**
 * Applies an OnlineState change to the sync engine and notifies any views of
 * the change.
 */ function nc(t, e, n) {
    const s = b(t);
    // If we are the secondary client, we explicitly ignore the remote store's
    // online state (the local client may go offline, even though the primary
    // tab remains online) and only apply the primary tab's online state from
    // SharedClientState.
        if (s.$l && 0 /* RemoteStore */ === n || !s.$l && 1 /* SharedClientState */ === n) {
        const t = [];
        s.Sl.forEach(((n, s) => {
            const i = s.view.zh(e);
            i.snapshot && t.push(i.snapshot);
        })), function(t, e) {
            const n = b(t);
            n.onlineState = e;
            let s = !1;
            n.queries.forEach(((t, n) => {
                for (const t of n.listeners) 
                // Run global snapshot listeners if a consistent snapshot has been emitted.
                t.zh(e) && (s = !0);
            })), s && $o(n);
        }(s.Vl, e), t.length && s.vl.uh(t), s.onlineState = e, s.$l && s.pl.Ka(e);
    }
}

/**
 * Rejects the listen for the given targetID. This can be triggered by the
 * backend for any active target.
 *
 * @param syncEngine - The sync engine implementation.
 * @param targetId - The targetID corresponds to one previously initiated by the
 * user as part of TargetData passed to listen() on RemoteStore.
 * @param err - A description of the condition that has forced the rejection.
 * Nearly always this will be an indication that the user is no longer
 * authorized to see the data matching the target.
 */ async function sc(t, e, n) {
    const s = b(t);
    // PORTING NOTE: Multi-tab only.
        s.pl.qa(e, "rejected", n);
    const i = s.Nl.get(e), r = i && i.key;
    if (r) {
        // TODO(klimt): We really only should do the following on permission
        // denied errors, but we don't have the cause code here.
        // It's a limbo doc. Create a synthetic event saying it was deleted.
        // This is kind of a hack. Ideally, we would have a method in the local
        // store to purge a document. However, it would be tricky to keep all of
        // the local store's invariants with another method.
        let t = new an(et.J);
        t = t.Ht(r, new Ot(r, J.min()));
        const n = Rn().add(r), i = new bn(J.min(), 
        /* targetChanges= */ new Map, 
        /* targetMismatches= */ new ln(D), t, n);
        await ec(s, i), 
        // Since this query failed, we won't want to manually unlisten to it.
        // We only remove it from bookkeeping after we successfully applied the
        // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to
        // this query when the RemoteStore restarts the Watch stream, which should
        // re-trigger the target failure.
        s.xl = s.xl.remove(r), s.Nl.delete(e), fc(s);
    } else await Tr(s.Sh, e, 
    /* keepPersistedTargetData */ !1).then((() => uc(s, e, n))).catch(Vi);
}

async function ic(t, e) {
    const n = b(t), s = e.batch.batchId;
    try {
        const t = await lr(n.Sh, e);
        // The local store may or may not be able to apply the write result and
        // raise events immediately (depending on whether the watcher is caught
        // up), so we raise user callbacks first so that they consistently happen
        // before listen events.
                ac(n, s, /*error=*/ null), cc(n, s), n.pl.Oa(s, "acknowledged"), await dc(n, t);
    } catch (t) {
        await Vi(t);
    }
}

async function rc(t, e, n) {
    const s = b(t);
    try {
        const t = await function(t, e) {
            const n = b(t);
            return n.persistence.runTransaction("Reject batch", "readwrite-primary", (t => {
                let s;
                return n.Ho.yi(t, e).next((e => (p(null !== e), s = e.keys(), n.Ho.xi(t, e)))).next((() => n.Ho.Fi(t))).next((() => n.Ic.Zo(t, s)));
            }));
        }
        /**
 * Returns the largest (latest) batch id in mutation queue that is pending
 * server response.
 *
 * Returns `BATCHID_UNKNOWN` if the queue is empty.
 */ (s.Sh, e);
        // The local store may or may not be able to apply the write result and
        // raise events immediately (depending on whether the watcher is caught up),
        // so we raise user callbacks first so that they consistently happen before
        // listen events.
                ac(s, e, n), cc(s, e), s.pl.Oa(e, "rejected", n), await dc(s, t);
    } catch (n) {
        await Vi(n);
    }
}

/**
 * Registers a user callback that resolves when all pending mutations at the moment of calling
 * are acknowledged .
 */ async function oc(t, e) {
    const n = b(t);
    fo(n.gl) || R("SyncEngine", "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");
    try {
        const t = await function(t) {
            const e = b(t);
            return e.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", (t => e.Ho.pi(t)));
        }(n.Sh);
        if (-1 === t) 
        // Trigger the callback right away if there is no pending writes at the moment.
        return void e.resolve();
        const s = n.kl.get(t) || [];
        s.push(e), n.kl.set(t, s);
    } catch (t) {
        const n = Cs(t, "Initialization of waitForPendingWrites() operation failed");
        e.reject(n);
    }
}

/**
 * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,
 * if there are any.
 */ function cc(t, e) {
    (t.kl.get(e) || []).forEach((t => {
        t.resolve();
    })), t.kl.delete(e);
}

/** Reject all outstanding callbacks waiting for pending writes to complete. */ function ac(t, e, n) {
    const s = b(t);
    let i = s.Fl[s.currentUser.R()];
    // NOTE: Mutations restored from persistence won't have callbacks, so it's
    // okay for there to be no callback for this ID.
        if (i) {
        const t = i.get(e);
        t && (n ? t.reject(n) : t.resolve(), i = i.remove(e)), s.Fl[s.currentUser.R()] = i;
    }
}

function uc(t, e, n = null) {
    t.pl.La(e);
    for (const s of t.Dl.get(e)) t.Sl.delete(s), n && t.vl.ql(s, n);
    if (t.Dl.delete(e), t.$l) {
        t.Ol.kc(e).forEach((e => {
            t.Ol.ki(e) || 
            // We removed the last reference for this key
            hc(t, e);
        }));
    }
}

function hc(t, e) {
    // It's possible that the target already got removed because the query failed. In that case,
    // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.
    const n = t.xl.get(e);
    null !== n && (ao(t.gl, n), t.xl = t.xl.remove(e), t.Nl.delete(n), fc(t));
}

function lc(t, e, n) {
    for (const s of n) if (s instanceof jo) t.Ol.sr(s.key, e), _c(t, s); else if (s instanceof Wo) {
        R("SyncEngine", "Document no longer in limbo: " + s.key), t.Ol.rr(s.key, e);
        t.Ol.ki(s.key) || 
        // We removed the last reference for this key
        hc(t, s.key);
    } else V();
}

function _c(t, e) {
    const n = e.key;
    t.xl.get(n) || (R("SyncEngine", "New document in limbo: " + n), t.Cl.push(n), fc(t));
}

/**
 * Starts listens for documents in limbo that are enqueued for resolution,
 * subject to a maximum number of concurrent resolutions.
 *
 * Without bounding the number of concurrent resolutions, the server can fail
 * with "resource exhausted" errors which can lead to pathological client
 * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.
 */ function fc(t) {
    for (;t.Cl.length > 0 && t.xl.size < t.bl; ) {
        const e = t.Cl.shift(), n = t.Ml.next();
        t.Nl.set(n, new Ho(e)), t.xl = t.xl.Ht(e, n), co(t.gl, new Re(fe(oe(e.path)), n, 2 /* LimboResolution */ , z.U));
    }
}

async function dc(t, e, n) {
    const s = b(t), i = [], r = [], o = [];
    s.Sl.nt() || (s.Sl.forEach(((t, c) => {
        o.push(s.Bl(c, e, n).then((t => {
            if (t) {
                s.$l && s.pl.qa(c.targetId, t.fromCache ? "not-current" : "current"), i.push(t);
                const e = or.cc(c.targetId, t);
                r.push(e);
            }
        })));
    })), await Promise.all(o), s.vl.uh(i), await async function(t, e) {
        const n = b(t);
        try {
            await n.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (t => As.forEach(e, (e => As.forEach(e.rc, (s => n.persistence.Ii.sr(t, e.targetId, s))).next((() => As.forEach(e.oc, (s => n.persistence.Ii.rr(t, e.targetId, s)))))))));
        } catch (t) {
            if (!Vs(t)) throw t;
            // If `notifyLocalViewChanges` fails, we did not advance the sequence
            // number for the documents that were included in this transaction.
            // This might trigger them to be deleted earlier than they otherwise
            // would have, but it should not invalidate the integrity of the data.
            R("LocalStore", "Failed to update sequence numbers: " + t);
        }
        for (const t of e) {
            const e = t.targetId;
            if (!t.fromCache) {
                const t = n.dc.get(e), s = t.Mt, i = t.Bt(s);
                // Advance the last limbo free snapshot version
                                n.dc = n.dc.Ht(e, i);
            }
        }
    }(s.Sh, r));
}

async function wc(t, e) {
    const n = b(t);
    if (!n.currentUser.isEqual(e)) {
        R("SyncEngine", "User change. New user:", e.R());
        const t = await hr(n.Sh, e);
        n.currentUser = e, 
        // Fails tasks waiting for pending writes requested by previous user.
        function(t, e) {
            t.kl.forEach((t => {
                t.forEach((t => {
                    t.reject(new F(O.CANCELLED, e));
                }));
            })), t.kl.clear();
        }(n, "'waitForPendingWrites' promise is rejected due to a user change."), 
        // TODO(b/114226417): Consider calling this only in the primary tab.
        n.pl.Qa(e, t.Ac, t.Rc), await dc(n, t.mc);
    }
}

function Ec(t, e) {
    const n = b(t), s = n.Nl.get(e);
    if (s && s.yl) return Rn().add(s.key);
    {
        let t = Rn();
        const s = n.Dl.get(e);
        if (!s) return t;
        for (const e of s) {
            const s = n.Sl.get(e);
            t = t.ye(s.view.fl);
        }
        return t;
    }
}

/**
 * Reconcile the list of synced documents in an existing view with those
 * from persistence.
 */ async function Tc(t, e) {
    const n = b(t), s = await Ir(n.Sh, e.query, 
    /* usePreviousResults= */ !0), i = e.view.Rl(s);
    return n.$l && lc(n, e.targetId, i.ml), i;
}

/**
 * Retrieves newly changed documents from remote document cache and raises
 * snapshots if needed.
 */
// PORTING NOTE: Multi-Tab only.
async function Ic(t) {
    const e = b(t);
    return Ar(e.Sh).then((t => dc(e, t)));
}

/** Applies a mutation state to an existing batch.  */
// PORTING NOTE: Multi-Tab only.
async function mc(t, e, n, s) {
    const i = b(t), r = await function(t, e) {
        const n = b(t), s = b(n.Ho);
        return n.persistence.runTransaction("Lookup mutation documents", "readonly", (t => s.gi(t, e).next((e => e ? n.Ic.Zo(t, e) : As.resolve(null)))));
    }
    // PORTING NOTE: Multi-Tab only.
    (i.Sh, e);
    null !== r ? ("pending" === n ? 
    // If we are the primary client, we need to send this write to the
    // backend. Secondary clients will ignore these writes since their remote
    // connection is disabled.
    await Ro(i.gl) : "acknowledged" === n || "rejected" === n ? (
    // NOTE: Both these methods are no-ops for batches that originated from
    // other clients.
    ac(i, e, s || null), cc(i, e), function(t, e) {
        b(b(t).Ho).Ni(e);
    }
    // PORTING NOTE: Multi-Tab only.
    (i.Sh, e)) : V(), await dc(i, r)) : 
    // A throttled tab may not have seen the mutation before it was completed
    // and removed from the mutation queue, in which case we won't have cached
    // the affected documents. In this case we can safely ignore the update
    // since that means we didn't apply the mutation locally at all (if we
    // had, we would have cached the affected documents), and so we will just
    // see any resulting document changes via normal remote document updates
    // as applicable.
    R("SyncEngine", "Cannot apply mutation batch with id: " + e);
}

/** Applies a query target change from a different tab. */
// PORTING NOTE: Multi-Tab only.
async function Ac(t, e) {
    const n = b(t);
    if (pc(n), bc(n), !0 === e && !0 !== n.Ll) {
        // Secondary tabs only maintain Views for their local listeners and the
        // Views internal state may not be 100% populated (in particular
        // secondary tabs don't track syncedDocuments, the set of documents the
        // server considers to be in the target). So when a secondary becomes
        // primary, we need to need to make sure that all views for all targets
        // match the state on disk.
        const t = n.pl.Sa(), e = await Rc(n, t.rt());
        n.Ll = !0, await Do(n.gl, !0);
        for (const t of e) co(n.gl, t);
    } else if (!1 === e && !1 !== n.Ll) {
        const t = [];
        let e = Promise.resolve();
        n.Dl.forEach(((s, i) => {
            n.pl.$a(i) ? t.push(i) : e = e.then((() => (uc(n, i), Tr(n.Sh, i, 
            /*keepPersistedTargetData=*/ !0)))), ao(n.gl, i);
        })), await e, await Rc(n, t), 
        // PORTING NOTE: Multi-Tab only.
        function(t) {
            const e = b(t);
            e.Nl.forEach(((t, n) => {
                ao(e.gl, n);
            })), e.Ol.Mc(), e.Nl = new Map, e.xl = new an(et.J);
        }
        /**
 * Reconcile the query views of the provided query targets with the state from
 * persistence. Raises snapshots for any changes that affect the local
 * client and returns the updated state of all target's query data.
 *
 * @param syncEngine - The sync engine implementation
 * @param targets - the list of targets with views that need to be recomputed
 * @param transitionToPrimary - `true` iff the tab transitions from a secondary
 * tab to a primary tab
 */
        // PORTING NOTE: Multi-Tab only.
        (n), n.Ll = !1, await Do(n.gl, !1);
    }
}

async function Rc(t, e, n) {
    const s = b(t), i = [], r = [];
    for (const t of e) {
        let e;
        const n = s.Dl.get(t);
        if (n && 0 !== n.length) {
            // For queries that have a local View, we fetch their current state
            // from LocalStore (as the resume token and the snapshot version
            // might have changed) and reconcile their views with the persisted
            // state (the list of syncedDocuments may have gotten out of sync).
            e = await Er(s.Sh, fe(n[0]));
            for (const t of n) {
                const e = s.Sl.get(t), n = await Tc(s, e);
                n.snapshot && r.push(n.snapshot);
            }
        } else {
            // For queries that never executed on this client, we need to
            // allocate the target in LocalStore and initialize a new View.
            const n = await mr(s.Sh, t);
            e = await Er(s.Sh, n), await Xo(s, Pc(n), t, 
            /*current=*/ !1);
        }
        i.push(e);
    }
    return s.vl.uh(r), i;
}

/**
 * Creates a `Query` object from the specified `Target`. There is no way to
 * obtain the original `Query`, so we synthesize a `Query` from the `Target`
 * object.
 *
 * The synthesized result might be different from the original `Query`, but
 * since the synthesized `Query` should return the same results as the
 * original one (only the presentation of results might differ), the potential
 * difference will not cause issues.
 */
// PORTING NOTE: Multi-Tab only.
function Pc(t) {
    return re(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, "F" /* First */ , t.startAt, t.endAt);
}

/** Returns the IDs of the clients that are currently active. */
// PORTING NOTE: Multi-Tab only.
function yc(t) {
    const e = b(t);
    return b(b(e.Sh).persistence).Qo();
}

/** Applies a query target change from a different tab. */
// PORTING NOTE: Multi-Tab only.
async function gc(t, e, n, s) {
    const i = b(t);
    if (i.Ll) 
    // If we receive a target state notification via WebStorage, we are
    // either already secondary or another tab has taken the primary lease.
    R("SyncEngine", "Ignoring unexpected query state notification."); else if (i.Dl.has(e)) switch (n) {
      case "current":
      case "not-current":
        {
            const t = await Ar(i.Sh), s = bn.$e(e, "current" === n);
            await dc(i, t, s);
            break;
        }

      case "rejected":
        await Tr(i.Sh, e, 
        /* keepPersistedTargetData */ !0), uc(i, e, s);
        break;

      default:
        V();
    }
}

/** Adds or removes Watch targets for queries from different tabs. */ async function Vc(t, e, n) {
    const s = pc(t);
    if (s.Ll) {
        for (const t of e) {
            if (s.Dl.has(t)) {
                // A target might have been added in a previous attempt
                R("SyncEngine", "Adding an already active target " + t);
                continue;
            }
            const e = await mr(s.Sh, t), n = await Er(s.Sh, e);
            await Xo(s, Pc(e), n.targetId, 
            /*current=*/ !1), co(s.gl, n);
        }
        for (const t of n) 
        // Check that the target is still active since the target might have been
        // removed if it has been rejected by the backend.
        s.Dl.has(t) && 
        // Release queries that are still active.
        await Tr(s.Sh, t, 
        /* keepPersistedTargetData */ !1).then((() => {
            ao(s.gl, t), uc(s, t);
        })).catch(Vi);
    }
}

function pc(t) {
    const e = b(t);
    return e.gl.Ch.Bh = ec.bind(null, e), e.gl.Ch.Sn = Ec.bind(null, e), e.gl.Ch.$h = sc.bind(null, e), 
    e.vl.uh = Mo.bind(null, e.Vl), e.vl.ql = Lo.bind(null, e.Vl), e;
}

function bc(t) {
    const e = b(t);
    return e.gl.Ch.qh = ic.bind(null, e), e.gl.Ch.Uh = rc.bind(null, e), e;
}

/**
 * Loads a Firestore bundle into the SDK. The returned promise resolves when
 * the bundle finished loading.
 *
 * @param syncEngine - SyncEngine to use.
 * @param bundleReader - Bundle to load into the SDK.
 * @param task - LoadBundleTask used to update the loading progress to public API.
 */ function vc(t, e, n) {
    const s = b(t);
    // eslint-disable-next-line @typescript-eslint/no-floating-promises
        (async function(t, e, n) {
        try {
            const s = await e.getMetadata();
            if (await function(t, e) {
                const n = b(t), s = Un(e.createTime);
                return n.persistence.runTransaction("hasNewerBundle", "readonly", (t => n.Eo.Ms(t, e.id))).then((t => !!t && t.createTime.u(s) >= 0));
            }
            /**
 * Saves the given `BundleMetadata` to local persistence.
 */ (t.Sh, s)) return await e.close(), void n.Ul(function(t) {
                return {
                    taskState: "Success",
                    documentsLoaded: t.totalDocuments,
                    bytesLoaded: t.totalBytes,
                    totalDocuments: t.totalDocuments,
                    totalBytes: t.totalBytes
                };
            }(s));
            n.Ql(Ko(s));
            const i = new Qo(s, t.Sh, e.Kt);
            let r = await e.Kl();
            for (;r; ) {
                const t = await i.ol(r);
                t && n.Ql(t), r = await e.Kl();
            }
            const o = await i.complete();
            // TODO(b/160876443): This currently raises snapshots with
            // `fromCache=false` if users already listen to some queries and bundles
            // has newer version.
                        await dc(t, o.zo, 
            /* remoteEvent */ void 0), 
            // Save metadata, so loading the same bundle will skip.
            await function(t, e) {
                const n = b(t);
                return n.persistence.runTransaction("Save bundle", "readwrite", (t => n.Eo.Ls(t, e)));
            }
            /**
 * Returns a promise of a `NamedQuery` associated with given query name. Promise
 * resolves to undefined if no persisted data can be found.
 */ (t.Sh, s), n.Ul(o.progress);
        } catch (t) {
            y("SyncEngine", "Loading bundle failed with " + t), n.jl(t);
        }
    }
    /**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
    /**
 * Provides all components needed for Firestore with in-memory persistence.
 * Uses EagerGC garbage collection.
 */)(s, e, n).then((() => {
        s.pl.Wa();
    }));
}

class Sc {
    constructor() {
        this.synchronizeTabs = !1;
    }
    async initialize(t) {
        this.Kt = Yr(t.gu.T), this.pl = this.Wl(t), this.persistence = this.Gl(t), await this.persistence.start(), 
        this.zl = this.Hl(t), this.Sh = this.Jl(t);
    }
    Hl(t) {
        return null;
    }
    Jl(t) {
        return ur(this.persistence, new cr, t.Yl, this.Kt);
    }
    Gl(t) {
        return new Cr(Nr.ra, this.Kt);
    }
    Wl(t) {
        return new Qr;
    }
    async terminate() {
        this.zl && this.zl.stop(), await this.pl.Lo(), await this.persistence.Lo();
    }
}

/**
 * Provides all components needed for Firestore with IndexedDB persistence.
 */ class Dc extends Sc {
    constructor(t, e, n) {
        super(), this.Xl = t, this.cacheSizeBytes = e, this.forceOwnership = n, this.synchronizeTabs = !1;
    }
    async initialize(t) {
        await super.initialize(t), await Rr(this.Sh), await this.Xl.initialize(this, t), 
        // Enqueue writes from a previous session
        await bc(this.Xl.fa), await Ro(this.Xl.gl);
    }
    Jl(t) {
        return ur(this.persistence, new cr, t.Yl, this.Kt);
    }
    Hl(t) {
        const e = this.persistence.Ii._r;
        return new Ui(e, t.fs);
    }
    Gl(t) {
        const e = sr(t.gu.T, t.gu.persistenceKey), n = void 0 !== this.cacheSizeBytes ? gi.Xs(this.cacheSizeBytes) : gi.ei;
        return new tr(this.synchronizeTabs, e, t.clientId, n, t.fs, Hr(), Jr(), this.Kt, this.pl, !!this.forceOwnership);
    }
    Wl(t) {
        return new Qr;
    }
}

/**
 * Provides all components needed for Firestore with multi-tab IndexedDB
 * persistence.
 *
 * In the legacy client, this provider is used to provide both multi-tab and
 * non-multi-tab persistence since we cannot tell at build time whether
 * `synchronizeTabs` will be enabled.
 */ class Cc extends Dc {
    constructor(t, e) {
        super(t, e, /* forceOwnership= */ !1), this.Xl = t, this.cacheSizeBytes = e, this.synchronizeTabs = !0;
    }
    async initialize(t) {
        await super.initialize(t);
        const e = this.Xl.fa;
        this.pl instanceof Ur && (this.pl.fa = {
            nu: mc.bind(null, e),
            su: gc.bind(null, e),
            iu: Vc.bind(null, e),
            Qo: yc.bind(null, e),
            eu: Ic.bind(null, e)
        }, await this.pl.start()), 
        // NOTE: This will immediately call the listener, so we make sure to
        // set it after localStore / remoteStore are started.
        await this.persistence.Po((async t => {
            await Ac(this.Xl.fa, t), this.zl && (t && !this.zl.Tr ? this.zl.start(this.Sh) : t || this.zl.stop());
        }));
    }
    Wl(t) {
        const e = Hr();
        if (!Ur.jn(e)) throw new F(O.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
        const n = sr(t.gu.T, t.gu.persistenceKey);
        return new Ur(e, t.fs, n, t.clientId, t.Yl);
    }
}

/**
 * Initializes and wires the components that are needed to interface with the
 * network.
 */ class xc {
    async initialize(t, e) {
        this.Sh || (this.Sh = t.Sh, this.pl = t.pl, this.Dh = this.Zl(e), this.gl = this.t_(e), 
        this.Vl = this.e_(e), this.fa = this.n_(e, 
        /* startAsPrimary=*/ !t.synchronizeTabs), this.pl.da = t => nc(this.fa, t, 1 /* SharedClientState */), 
        this.gl.Ch.s_ = wc.bind(null, this.fa), await Do(this.gl, this.fa.$l));
    }
    e_(t) {
        return new Oo;
    }
    Zl(t) {
        const e = Yr(t.gu.T), n = (s = t.gu, new zr(s));
        var s;
        /** Return the Platform-specific connectivity monitor. */        return function(t, e, n) {
            return new no(t, e, n);
        }(t.credentials, n, e);
    }
    t_(t) {
        return e = this.Sh, n = this.Dh, s = t.fs, i = t => nc(this.fa, t, 0 /* RemoteStore */), 
        r = jr.jn() ? new jr : new Kr, new io(e, n, s, i, r);
        var e, n, s, i, r;
        /** Re-enables the network. Idempotent. */    }
    n_(t, e) {
        return function(t, e, n, 
        // PORTING NOTE: Manages state synchronization in multi-tab environments.
        s, i, r, o) {
            const c = new Jo(t, e, n, s, i, r);
            return o && (c.Ll = !0), c;
        }(this.Sh, this.gl, this.Vl, this.pl, t.Yl, t.bl, e);
    }
    terminate() {
        return async function(t) {
            const e = b(t);
            R("RemoteStore", "RemoteStore shutting down."), e.Oh.add(5 /* Shutdown */), await oo(e), 
            e.kh.Lo(), 
            // Set the OnlineState to Unknown (rather than Offline) to avoid potentially
            // triggering spurious listener events with cached data, etc.
            e.Mh.set("Unknown" /* Unknown */);
        }(this.gl);
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * How many bytes to read each time when `ReadableStreamReader.read()` is
 * called. Only applicable for byte streams that we control (e.g. those backed
 * by an UInt8Array).
 */
/**
 * Builds a `ByteStreamReader` from a UInt8Array.
 * @param source - The data source to use.
 * @param bytesPerRead - How many bytes each `read()` from the returned reader
 *        will read.
 */
function Nc(t, e = 10240) {
    let n = 0;
    return {
        async read() {
            if (n < t.byteLength) {
                const s = {
                    value: t.slice(n, n + e),
                    done: !1
                };
                return n += e, s;
            }
            // TypesScript's lib.dom.d.ts doesn't have proper typings of
            // ReadableStreamReadResult yet.
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        return {
                done: !0
            };
        },
        async cancel() {},
        releaseLock() {}
    };
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.
 */
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * A wrapper implementation of Observer<T> that will dispatch events
 * asynchronously. To allow immediate silencing, a mute call is added which
 * causes events scheduled to no longer be raised.
 */
class Oc {
    constructor(t) {
        this.observer = t, 
        /**
         * When set to true, will not raise future events. Necessary to deal with
         * async detachment of listener.
         */
        this.muted = !1;
    }
    next(t) {
        this.observer.next && this.i_(this.observer.next, t);
    }
    error(t) {
        this.observer.error ? this.i_(this.observer.error, t) : console.error("Uncaught Error in snapshot listener:", t);
    }
    r_() {
        this.muted = !0;
    }
    i_(t, e) {
        this.muted || setTimeout((() => {
            this.muted || t(e);
        }), 0);
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A class representing a bundle.
 *
 * Takes a bundle stream or buffer, and presents abstractions to read bundled
 * elements out of the underlying content.
 */ class Fc {
    constructor(
    /** The reader to read from underlying binary bundle data source. */
    t, e) {
        this.o_ = t, this.Kt = e, 
        /** Cached bundle metadata. */
        this.metadata = new ms, 
        /**
         * Internal buffer to hold bundle content, accumulating incomplete element
         * content.
         */
        this.buffer = new Uint8Array, this.c_ = new TextDecoder("utf-8"), 
        // Read the metadata (which is the first element).
        this.a_().then((t => {
            t && t.il() ? this.metadata.resolve(t.payload.metadata) : this.metadata.reject(new Error("The first element of the bundle is not a metadata, it is\n             " + JSON.stringify(null == t ? void 0 : t.payload)));
        }), (t => this.metadata.reject(t)));
    }
    close() {
        return this.o_.cancel();
    }
    async getMetadata() {
        return this.metadata.promise;
    }
    async Kl() {
        // Makes sure metadata is read before proceeding.
        return await this.getMetadata(), this.a_();
    }
    /**
     * Reads from the head of internal buffer, and pulling more data from
     * underlying stream if a complete element cannot be found, until an
     * element(including the prefixed length and the JSON string) is found.
     *
     * Once a complete element is read, it is dropped from internal buffer.
     *
     * Returns either the bundled element, or null if we have reached the end of
     * the stream.
     */    async a_() {
        const t = await this.u_();
        if (null === t) return null;
        const e = this.c_.decode(t), n = Number(e);
        isNaN(n) && this.h_(`length string (${e}) is not valid number`);
        const s = await this.l_(n);
        return new qo(JSON.parse(s), t.length + n);
    }
    /** First index of '{' from the underlying buffer. */    __() {
        return this.buffer.findIndex((t => t === "{".charCodeAt(0)));
    }
    /**
     * Reads from the beginning of the internal buffer, until the first '{', and
     * return the content.
     *
     * If reached end of the stream, returns a null.
     */    async u_() {
        for (;this.__() < 0; ) {
            if (await this.f_()) break;
        }
        // Broke out of the loop because underlying stream is closed, and there
        // happens to be no more data to process.
                if (0 === this.buffer.length) return null;
        const t = this.__();
        // Broke out of the loop because underlying stream is closed, but still
        // cannot find an open bracket.
                t < 0 && this.h_("Reached the end of bundle when a length string is expected.");
        const e = this.buffer.slice(0, t);
        // Update the internal buffer to drop the read length.
                return this.buffer = this.buffer.slice(t), e;
    }
    /**
     * Reads from a specified position from the internal buffer, for a specified
     * number of bytes, pulling more data from the underlying stream if needed.
     *
     * Returns a string decoded from the read bytes.
     */    async l_(t) {
        for (;this.buffer.length < t; ) {
            await this.f_() && this.h_("Reached the end of bundle when more is expected.");
        }
        const e = this.c_.decode(this.buffer.slice(0, t));
        // Update the internal buffer to drop the read json string.
                return this.buffer = this.buffer.slice(t), e;
    }
    h_(t) {
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        throw this.o_.cancel(), new Error("Invalid bundle format: " + t);
    }
    /**
     * Pulls more data from underlying stream to internal buffer.
     * Returns a boolean indicating whether the stream is finished.
     */    async f_() {
        const t = await this.o_.read();
        if (!t.done) {
            const e = new Uint8Array(this.buffer.length + t.value.length);
            e.set(this.buffer), e.set(t.value, this.buffer.length), this.buffer = e;
        }
        return t.done;
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A `FieldPath` refers to a field in a document. The path may consist of a
 * single field name (referring to a top-level field in the document), or a
 * list of field names (referring to a nested field in the document).
 *
 * Create a `FieldPath` by providing field names. If more than one field
 * name is provided, the path will point to a nested field in a document.
 */
class kc {
    /**
     * Creates a FieldPath from the provided field names. If more than one field
     * name is provided, the path will point to a nested field in a document.
     *
     * @param fieldNames - A list of field names.
     */
    constructor(...t) {
        for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new F(O.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty.");
        this.d_ = new tt(t);
    }
    /**
     * Returns true if this `FieldPath` is equal to the provided one.
     *
     * @param other - The `FieldPath` to compare against.
     * @returns true if this `FieldPath` is equal to the provided one.
     */    isEqual(t) {
        return this.d_.isEqual(t.d_);
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Sentinel values that can be used when writing document fields with `set()`
 * or `update()`.
 */ class Mc {
    /**
     * @param _methodName - The public API endpoint that returns this class.
     */
    constructor(t) {
        this._methodName = t;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ function Lc(t, e, n) {
    if (!n) throw new F(O.INVALID_ARGUMENT, `Function ${t}() cannot be called with an empty ${e}.`);
}

function $c(t, e) {
    if (void 0 === e) return {
        merge: !1
    };
    if (void 0 !== e.mergeFields && void 0 !== e.merge) throw new F(O.INVALID_ARGUMENT, `Invalid options passed to function ${t}(): You cannot specify both "merge" and "mergeFields".`);
    return e;
}

/**
 * Validates that two boolean options are not set at the same time.
 */ function Bc(t, e, n, s) {
    if (!0 === e && !0 === s) throw new F(O.INVALID_ARGUMENT, `${t} and ${n} cannot be used together.`);
}

/**
 * Validates that `path` refers to a document (indicated by the fact it contains
 * an even numbers of segments).
 */ function qc(t) {
    if (!et.Et(t)) throw new F(O.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`);
}

/**
 * Validates that `path` refers to a collection (indicated by the fact it
 * contains an odd numbers of segments).
 */ function Uc(t) {
    if (et.Et(t)) throw new F(O.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`);
}

/**
 * Returns true if it's a non-null object without a custom prototype
 * (i.e. excludes Array, Date, etc.).
 */
/** Returns a string describing the type / value of the provided input. */
function Qc(t) {
    if (void 0 === t) return "undefined";
    if (null === t) return "null";
    if ("string" == typeof t) return t.length > 20 && (t = t.substring(0, 20) + "..."), 
    JSON.stringify(t);
    if ("number" == typeof t || "boolean" == typeof t) return "" + t;
    if ("object" == typeof t) {
        if (t instanceof Array) return "an array";
        {
            const e = 
            /** Hacky method to try to get the constructor name for an object. */
            function(t) {
                if (t.constructor) {
                    const e = /function\s+([^\s(]+)\s*\(/.exec(t.constructor.toString());
                    if (e && e.length > 1) return e[1];
                }
                return null;
            }
            /**
 * Casts `obj` to `T`, optionally unwrapping Compat types to expose the
 * underlying instance. Throws if  `obj` is not an instance of `T`.
 *
 * This cast is used in the Lite and Full SDK to verify instance types for
 * arguments passed to the public API.
 */ (t);
            return e ? `a custom ${e} object` : "an object";
        }
    }
    return "function" == typeof t ? "a function" : V();
}

function Kc(t, 
// eslint-disable-next-line @typescript-eslint/no-explicit-any
e) {
    if ("_delegate" in t && (
    // Unwrap Compat types
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    t = t._), !(t instanceof e)) {
        if (e.name === t.constructor.name) throw new F(O.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
        {
            const n = Qc(t);
            throw new F(O.INVALID_ARGUMENT, `Expected type '${e.name}', but it was: ${n}`);
        }
    }
    return t;
}

function jc(t, e) {
    if (e <= 0) throw new F(O.INVALID_ARGUMENT, `Function ${t}() requires a positive number, but it was: ${e}.`);
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// settings() defaults:
/**
 * A concrete type describing all the values that can be applied via a
 * user-supplied firestore.Settings object. This is a separate type so that
 * defaults can be supplied and the value can be checked for equality.
 */
class Wc {
    constructor(t) {
        var e;
        if (void 0 === t.host) {
            if (void 0 !== t.ssl) throw new F(O.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
            this.host = "firestore.googleapis.com", this.ssl = true;
        } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;
        if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties, 
        void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {
            if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new F(O.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
            this.cacheSizeBytes = t.cacheSizeBytes;
        }
        this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling, 
        Bc("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling);
    }
    isEqual(t) {
        return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties;
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const Gc = new Map;

/**
 * An instance map that ensures only one Datastore exists per Firestore
 * instance.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * The Cloud Firestore service interface.
 *
 * Do not call this constructor directly. Instead, use {@link getFirestore}.
 */
class zc {
    /** @hideconstructor */
    constructor(t, e) {
        this.w_ = "(lite)", this.E_ = new Wc({}), this.T_ = !1, t instanceof q ? (this.I_ = t, 
        this.m_ = new K) : (this.A_ = t, this.I_ = function(t) {
            if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new F(O.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
            return new q(t.options.projectId);
        }
        /**
 * Modify this instance to communicate with the Cloud Firestore emulator.
 *
 * Note: This must be called before this instance has been used to do any
 * operations.
 *
 * @param firestore - The Firestore instance to configure to connect to the
 * emulator.
 * @param host - the emulator host (ex: localhost).
 * @param port - the emulator port (ex: 9000).
 */ (t), this.m_ = new j(e));
    }
    /**
     * The {@link FirebaseApp} associated with this `Firestore` service
     * instance.
     */    get app() {
        if (!this.A_) throw new F(O.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
        return this.A_;
    }
    get R_() {
        return this.T_;
    }
    get P_() {
        return void 0 !== this.y_;
    }
    g_(t) {
        if (this.T_) throw new F(O.FAILED_PRECONDITION, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");
        this.E_ = new Wc(t), void 0 !== t.credentials && (this.m_ = function(t) {
            if (!t) return new K;
            switch (t.type) {
              case "gapi":
                const e = t.client;
                // Make sure this really is a Gapi client.
                                return p(!("object" != typeof e || null === e || !e.auth || !e.auth.getAuthHeaderValueForFirstParty)), 
                new G(e, t.sessionIndex || "0");

              case "provider":
                return t.client;

              default:
                throw new F(O.INVALID_ARGUMENT, "makeCredentialsProvider failed due to invalid credential type");
            }
        }(t.credentials));
    }
    V_() {
        return this.E_;
    }
    p_() {
        return this.T_ = !0, this.E_;
    }
    _delete() {
        return this.y_ || (this.y_ = this.b_()), this.y_;
    }
    /**
     * Terminates all components used by this client. Subclasses can override
     * this method to clean up their own dependencies, but must also call this
     * method.
     *
     * Only ever called once.
     */    b_() {
        /**
 * Removes all components associated with the provided instance. Must be called
 * when the `Firestore` instance is terminated.
 */
        return function(t) {
            const e = Gc.get(t);
            e && (R("ComponentProvider", "Removing Datastore"), Gc.delete(t), e.terminate());
        }(this), Promise.resolve();
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A `DocumentReference` refers to a document location in a Firestore database
 * and can be used to write, read, or listen to the location. The document at
 * the referenced location may or may not exist.
 */
class Hc {
    /** @hideconstructor */
    constructor(t, e, n) {
        this.v_ = e, this.S_ = n, 
        /** The type of this Firestore reference. */
        this.type = "document", this.firestore = t;
    }
    get D_() {
        return this.S_.path;
    }
    /**
     * The document's identifier within its collection.
     */    get id() {
        return this.S_.path.et();
    }
    /**
     * A string representing the path of the referenced document (relative
     * to the root of the database).
     */    get path() {
        return this.S_.path.ot();
    }
    /**
     * The collection this `DocumentReference` belongs to.
     */    get parent() {
        return new Yc(this.firestore, this.v_, this.S_.path.Z());
    }
    /**
     * Applies a custom data converter to this `DocumentReference`, allowing you
     * to use your own custom model objects with Firestore. When you call {@link
     * setDoc}, {@link getDoc}, etc. with the returned `DocumentReference`
     * instance, the provided converter will convert between Firestore data and
     * your custom type `U`.
     *
     * @param converter - Converts objects to and from Firestore.
     * @returns A `DocumentReference<U>` that uses the provided converter.
     */    withConverter(t) {
        return new Hc(this.firestore, t, this.S_);
    }
}

/**
 * A `Query` refers to a Query which you can read or listen to. You can also
 * construct refined `Query` objects by adding filters and ordering.
 */ class Jc {
    // This is the lite version of the Query class in the main SDK.
    /** @hideconstructor protected */
    constructor(t, e, n) {
        this.v_ = e, this.C_ = n, 
        /** The type of this Firestore reference. */
        this.type = "query", this.firestore = t;
    }
    /**
     * Applies a custom data converter to this query, allowing you to use your own
     * custom model objects with Firestore. When you call {@link getDocs} with
     * the returned query, the provided converter will convert between Firestore
     * data and your custom type `U`.
     *
     * @param converter - Converts objects to and from Firestore.
     * @returns A `Query<U>` that uses the provided converter.
     */    withConverter(t) {
        return new Jc(this.firestore, t, this.C_);
    }
}

/**
 * A `CollectionReference` object can be used for adding documents, getting
 * document references, and querying for documents (using {@link query}).
 */ class Yc extends Jc {
    /** @hideconstructor */
    constructor(t, e, n) {
        super(t, e, oe(n)), this.firestore = t, this.D_ = n, this.type = "collection";
    }
    /** The collection's identifier. */    get id() {
        return this.C_.path.et();
    }
    /**
     * A string representing the path of the referenced collection (relative
     * to the root of the database).
     */    get path() {
        return this.C_.path.ot();
    }
    /**
     * A reference to the containing `DocumentReference` if this is a
     * subcollection. If this isn't a subcollection, the reference is null.
     */    get parent() {
        const t = this.D_.Z();
        return t.nt() ? null : new Hc(this.firestore, 
        /* converter= */ null, new et(t));
    }
    /**
     * Applies a custom data converter to this CollectionReference, allowing you
     * to use your own custom model objects with Firestore. When you call {@link
     * addDoc} with the returned `CollectionReference` instance, the provided
     * converter will convert between Firestore data and your custom type `U`.
     *
     * @param converter - Converts objects to and from Firestore.
     * @returns A `CollectionReference<U>` that uses the provided converter.
     */    withConverter(t) {
        return new Yc(this.firestore, t, this.D_);
    }
}

function Xc(t, e, ...n) {
    if (t instanceof M && (t = t._), Lc("collection", "path", e), t instanceof zc) {
        const s = X.ct(e, ...n);
        return Uc(s), new Yc(t, /* converter= */ null, s);
    }
    {
        if (!(t instanceof Hc || t instanceof Yc)) throw new F(O.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
        const s = X.ct(t.path, ...n).child(X.ct(e));
        return Uc(s), new Yc(t.firestore, 
        /* converter= */ null, s);
    }
}

// TODO(firestorelite): Consider using ErrorFactory -
// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106
/**
 * Creates and returns a new `Query` instance that includes all documents in the
 * database that are contained in a collection or subcollection with the
 * given `collectionId`.
 *
 * @param firestore - A reference to the root Firestore instance.
 * @param collectionId - Identifies the collections to query over. Every
 * collection or subcollection with this ID as the last segment of its path
 * will be included. Cannot contain a slash.
 * @returns The created `Query`.
 */ function Zc(t, e) {
    if (t = Kc(t, zc), Lc("collectionGroup", "collection id", e), e.indexOf("/") >= 0) throw new F(O.INVALID_ARGUMENT, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);
    return new Jc(t, 
    /* converter= */ null, 
    /**
 * Creates a new Query for a collection group query that matches all documents
 * within the provided collection group.
 */
    function(t) {
        return new ie(X.at(), t);
    }(e));
}

function ta(t, e, ...n) {
    if (t instanceof M && (t = t._), 
    // We allow omission of 'pathString' but explicitly prohibit passing in both
    // 'undefined' and 'null'.
    1 === arguments.length && (e = S.t()), Lc("doc", "path", e), t instanceof zc) {
        const s = X.ct(e, ...n);
        return qc(s), new Hc(t, 
        /* converter= */ null, new et(s));
    }
    {
        if (!(t instanceof Hc || t instanceof Yc)) throw new F(O.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
        const s = t.D_.child(X.ct(e, ...n));
        return qc(s), new Hc(t.firestore, t instanceof Yc ? t.v_ : null, new et(s));
    }
}

/**
 * Returns true if the provided references are equal.
 *
 * @param left - A reference to compare.
 * @param right - A reference to compare.
 * @returns true if the references point to the same location in the same
 * Firestore database.
 */ function ea(t, e) {
    return t instanceof M && (t = t._), e instanceof M && (e = e._), (t instanceof Hc || t instanceof Yc) && (e instanceof Hc || e instanceof Yc) && (t.firestore === e.firestore && t.path === e.path && t.v_ === e.v_);
}

/**
 * Returns true if the provided queries point to the same collection and apply
 * the same constraints.
 *
 * @param left - A `Query` to compare.
 * @param right - A `Query` to compare.
 * @returns true if the references point to the same location in the same
 * Firestore database.
 */ function na(t, e) {
    return t instanceof M && (t = t._), e instanceof M && (e = e._), t instanceof Jc && e instanceof Jc && (t.firestore === e.firestore && we(t.C_, e.C_) && t.v_ === e.v_);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An immutable object representing a geographic location in Firestore. The
 * location is represented as latitude/longitude pair.
 *
 * Latitude values are in the range of [-90, 90].
 * Longitude values are in the range of [-180, 180].
 */ class sa {
    /**
     * Creates a new immutable `GeoPoint` object with the provided latitude and
     * longitude values.
     * @param latitude - The latitude as number between -90 and 90.
     * @param longitude - The longitude as number between -180 and 180.
     */
    constructor(t, e) {
        if (!isFinite(t) || t < -90 || t > 90) throw new F(O.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + t);
        if (!isFinite(e) || e < -180 || e > 180) throw new F(O.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + e);
        this.x_ = t, this.N_ = e;
    }
    /**
     * The latitude of this `GeoPoint` instance.
     */    get latitude() {
        return this.x_;
    }
    /**
     * The longitude of this `GeoPoint` instance.
     */    get longitude() {
        return this.N_;
    }
    /**
     * Returns true if this `GeoPoint` is equal to the provided one.
     *
     * @param other - The `GeoPoint` to compare against.
     * @returns true if this `GeoPoint` is equal to the provided one.
     */    isEqual(t) {
        return this.x_ === t.x_ && this.N_ === t.N_;
    }
    toJSON() {
        return {
            latitude: this.x_,
            longitude: this.N_
        };
    }
    /**
     * Actually private to JS consumers of our API, so this function is prefixed
     * with an underscore.
     */    K(t) {
        return D(this.x_, t.x_) || D(this.N_, t.N_);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const ia = /^__.*__$/;

/** The result of parsing document data (e.g. for a setData call). */ class ra {
    constructor(t, e, n) {
        this.data = t, this.zt = e, this.fieldTransforms = n;
    }
    O_(t, e) {
        return null !== this.zt ? new He(t, this.data, this.zt, e, this.fieldTransforms) : new ze(t, this.data, e, this.fieldTransforms);
    }
}

/** The result of parsing "update" data (i.e. for an updateData call). */ class oa {
    constructor(t, 
    // The fieldMask does not include document transforms.
    e, n) {
        this.data = t, this.zt = e, this.fieldTransforms = n;
    }
    O_(t, e) {
        return new He(t, this.data, this.zt, e, this.fieldTransforms);
    }
}

function ca(t) {
    switch (t) {
      case 0 /* Set */ :
 // fall through
              case 2 /* MergeSet */ :
 // fall through
              case 1 /* Update */ :
        return !0;

      case 3 /* Argument */ :
      case 4 /* ArrayArgument */ :
        return !1;

      default:
        throw V();
    }
}

/** A "context" object passed around while parsing user data. */ class aa {
    /**
     * Initializes a ParseContext with the given source and path.
     *
     * @param settings - The settings for the parser.
     * @param databaseId - The database ID of the Firestore instance.
     * @param serializer - The serializer to use to generate the Value proto.
     * @param ignoreUndefinedProperties - Whether to ignore undefined properties
     * rather than throw.
     * @param fieldTransforms - A mutable list of field transforms encountered
     * while parsing the data.
     * @param fieldMask - A mutable list of field paths encountered while parsing
     * the data.
     *
     * TODO(b/34871131): We don't support array paths right now, so path can be
     * null to indicate the context represents any location within an array (in
     * which case certain features will not work and errors will be somewhat
     * compromised).
     */
    constructor(t, e, n, s, i, r) {
        this.settings = t, this.T = e, this.Kt = n, this.ignoreUndefinedProperties = s, 
        // Minor hack: If fieldTransforms is undefined, we assume this is an
        // external call and we need to validate the entire path.
        void 0 === i && this.F_(), this.fieldTransforms = i || [], this.zt = r || [];
    }
    get path() {
        return this.settings.path;
    }
    get k_() {
        return this.settings.k_;
    }
    /** Returns a new context with the specified settings overwritten. */    M_(t) {
        return new aa(Object.assign(Object.assign({}, this.settings), t), this.T, this.Kt, this.ignoreUndefinedProperties, this.fieldTransforms, this.zt);
    }
    L_(t) {
        var e;
        const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.M_({
            path: n,
            B_: !1
        });
        return s.q_(t), s;
    }
    U_(t) {
        var e;
        const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.M_({
            path: n,
            B_: !1
        });
        return s.F_(), s;
    }
    Q_(t) {
        // TODO(b/34871131): We don't support array paths right now; so make path
        // undefined.
        return this.M_({
            path: void 0,
            B_: !0
        });
    }
    K_(t) {
        return va(t, this.settings.methodName, this.settings.j_ || !1, this.path, this.settings.W_);
    }
    /** Returns 'true' if 'fieldPath' was traversed when creating this context. */    contains(t) {
        return void 0 !== this.zt.find((e => t.st(e))) || void 0 !== this.fieldTransforms.find((e => t.st(e.field)));
    }
    F_() {
        // TODO(b/34871131): Remove null check once we have proper paths for fields
        // within arrays.
        if (this.path) for (let t = 0; t < this.path.length; t++) this.q_(this.path.get(t));
    }
    q_(t) {
        if (0 === t.length) throw this.K_("Document fields must not be empty");
        if (ca(this.k_) && ia.test(t)) throw this.K_('Document fields cannot begin and end with "__"');
    }
}

/**
 * Helper for parsing raw user input (provided via the API) into internal model
 * classes.
 */ class ua {
    constructor(t, e, n) {
        this.T = t, this.ignoreUndefinedProperties = e, this.Kt = n || Yr(t);
    }
    /** Creates a new top-level parse context. */    G_(t, e, n, s = !1) {
        return new aa({
            k_: t,
            methodName: e,
            W_: n,
            path: tt.at(),
            B_: !1,
            j_: s
        }, this.T, this.Kt, this.ignoreUndefinedProperties);
    }
}

function ha(t) {
    const e = t.p_(), n = Yr(t.I_);
    return new ua(t.I_, !!e.ignoreUndefinedProperties, n);
}

/** Parse document data from a set() call. */ function la(t, e, n, s, i, r = {}) {
    const o = t.G_(r.merge || r.mergeFields ? 2 /* MergeSet */ : 0 /* Set */ , e, n, i);
    ga("Data must be an object, but it was:", o, s);
    const c = Pa(s, o);
    let a, u;
    if (r.merge) a = new rt(o.zt), u = o.fieldTransforms; else if (r.mergeFields) {
        const t = [];
        for (const s of r.mergeFields) {
            const i = Va(e, s, n);
            if (!o.contains(i)) throw new F(O.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`);
            Sa(t, i) || t.push(i);
        }
        a = new rt(t), u = o.fieldTransforms.filter((t => a.It(t.field)));
    } else a = null, u = o.fieldTransforms;
    return new ra(new St(c), a, u);
}

class _a extends Mc {
    z_(t) {
        if (2 /* MergeSet */ !== t.k_) throw 1 /* Update */ === t.k_ ? t.K_(this._methodName + "() can only appear at the top level of your update data") : t.K_(this._methodName + "() cannot be used with set() unless you pass {merge:true}");
        // No transform to add for a delete, but we need to add it to our
        // fieldMask so it gets deleted.
        return t.zt.push(t.path), null;
    }
    isEqual(t) {
        return t instanceof _a;
    }
}

/**
 * Creates a child context for parsing SerializableFieldValues.
 *
 * This is different than calling `ParseContext.contextWith` because it keeps
 * the fieldTransforms and fieldMask separate.
 *
 * The created context has its `dataSource` set to `UserDataSource.Argument`.
 * Although these values are used with writes, any elements in these FieldValues
 * are not considered writes since they cannot contain any FieldValue sentinels,
 * etc.
 *
 * @param fieldValue - The sentinel FieldValue for which to create a child
 *     context.
 * @param context - The parent context.
 * @param arrayElement - Whether or not the FieldValue has an array.
 */ function fa(t, e, n) {
    return new aa({
        k_: 3 /* Argument */ ,
        W_: e.settings.W_,
        methodName: t._methodName,
        B_: n
    }, e.T, e.Kt, e.ignoreUndefinedProperties);
}

class da extends Mc {
    z_(t) {
        return new Me(t.path, new Se);
    }
    isEqual(t) {
        return t instanceof da;
    }
}

class wa extends Mc {
    constructor(t, e) {
        super(t), this.H_ = e;
    }
    z_(t) {
        const e = fa(this, t, 
        /*array=*/ !0), n = this.H_.map((t => Ra(t, e))), s = new De(n);
        return new Me(t.path, s);
    }
    isEqual(t) {
        // TODO(mrschmidt): Implement isEquals
        return this === t;
    }
}

class Ea extends Mc {
    constructor(t, e) {
        super(t), this.H_ = e;
    }
    z_(t) {
        const e = fa(this, t, 
        /*array=*/ !0), n = this.H_.map((t => Ra(t, e))), s = new xe(n);
        return new Me(t.path, s);
    }
    isEqual(t) {
        // TODO(mrschmidt): Implement isEquals
        return this === t;
    }
}

class Ta extends Mc {
    constructor(t, e) {
        super(t), this.J_ = e;
    }
    z_(t) {
        const e = new Oe(t.Kt, ge(t.Kt, this.J_));
        return new Me(t.path, e);
    }
    isEqual(t) {
        // TODO(mrschmidt): Implement isEquals
        return this === t;
    }
}

/** Parse update data from an update() call. */ function Ia(t, e, n, s) {
    const i = t.G_(1 /* Update */ , e, n);
    ga("Data must be an object, but it was:", i, s);
    const r = [], o = new Dt;
    st(s, ((t, s) => {
        const c = ba(e, t, n);
        // For Compat types, we have to "extract" the underlying types before
        // performing validation.
                s instanceof M && (s = s._);
        const a = i.U_(c);
        if (s instanceof _a) 
        // Add it to the field mask, but don't add anything to updateData.
        r.push(c); else {
            const t = Ra(s, a);
            null != t && (r.push(c), o.set(c, t));
        }
    }));
    const c = new rt(r);
    return new oa(o.yt(), c, i.fieldTransforms);
}

/** Parse update data from a list of field/value arguments. */ function ma(t, e, n, s, i, r) {
    const o = t.G_(1 /* Update */ , e, n), c = [ Va(e, s, n) ], a = [ i ];
    if (r.length % 2 != 0) throw new F(O.INVALID_ARGUMENT, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);
    for (let t = 0; t < r.length; t += 2) c.push(Va(e, r[t])), a.push(r[t + 1]);
    const u = [], h = new Dt;
    // We iterate in reverse order to pick the last value for a field if the
    // user specified the field multiple times.
    for (let t = c.length - 1; t >= 0; --t) if (!Sa(u, c[t])) {
        const e = c[t];
        let n = a[t];
        // For Compat types, we have to "extract" the underlying types before
        // performing validation.
                n instanceof M && (n = n._);
        const s = o.U_(e);
        if (n instanceof _a) 
        // Add it to the field mask, but don't add anything to updateData.
        u.push(e); else {
            const t = Ra(n, s);
            null != t && (u.push(e), h.set(e, t));
        }
    }
    const l = new rt(u);
    return new oa(h.yt(), l, o.fieldTransforms);
}

/**
 * Parse a "query value" (e.g. value in a where filter or a value in a cursor
 * bound).
 *
 * @param allowArrays - Whether the query value is an array that may directly
 * contain additional arrays (e.g. the operand of an `in` query).
 */ function Aa(t, e, n, s = !1) {
    return Ra(n, t.G_(s ? 4 /* ArrayArgument */ : 3 /* Argument */ , e));
}

/**
 * Parses user data to Protobuf Values.
 *
 * @param input - Data to be parsed.
 * @param context - A context object representing the current path being parsed,
 * the source of the data being parsed, etc.
 * @returns The parsed value, or null if the value was a FieldValue sentinel
 * that should not be included in the resulting parsed data.
 */ function Ra(t, e) {
    if (
    // Unwrap the API type from the Compat SDK. This will return the API type
    // from firestore-exp.
    t instanceof M && (t = t._), ya(t)) return ga("Unsupported field value:", e, t), 
    Pa(t, e);
    if (t instanceof Mc) 
    // FieldValues usually parse into transforms (except FieldValue.delete())
    // in which case we do not want to include this field in our parsed data
    // (as doing so will overwrite the field directly prior to the transform
    // trying to transform it). So we don't add this location to
    // context.fieldMask and we return null as our parsing result.
    /**
 * "Parses" the provided FieldValueImpl, adding any necessary transforms to
 * context.fieldTransforms.
 */
    return function(t, e) {
        // Sentinels are only supported with writes, and not within arrays.
        if (!ca(e.k_)) throw e.K_(t._methodName + "() can only be used with update() and set()");
        if (!e.path) throw e.K_(t._methodName + "() is not currently supported inside arrays");
        const n = t.z_(e);
        n && e.fieldTransforms.push(n);
    }
    /**
 * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)
 *
 * @returns The parsed value
 */ (t, e), null;
    if (
    // If context.path is null we are inside an array and we don't support
    // field mask paths more granular than the top-level array.
    e.path && e.zt.push(e.path), t instanceof Array) {
        // TODO(b/34871131): Include the path containing the array in the error
        // message.
        // In the case of IN queries, the parsed data is an array (representing
        // the set of values to be included for the IN query) that may directly
        // contain additional arrays (each representing an individual field
        // value), so we disable this validation.
        if (e.settings.B_ && 4 /* ArrayArgument */ !== e.k_) throw e.K_("Nested arrays are not supported");
        return function(t, e) {
            const n = [];
            let s = 0;
            for (const i of t) {
                let t = Ra(i, e.Q_(s));
                null == t && (
                // Just include nulls in the array for fields being replaced with a
                // sentinel.
                t = {
                    nullValue: "NULL_VALUE"
                }), n.push(t), s++;
            }
            return {
                arrayValue: {
                    values: n
                }
            };
        }(t, e);
    }
    return function(t, e) {
        t instanceof M && (t = t._);
        if (null === t) return {
            nullValue: "NULL_VALUE"
        };
        if ("number" == typeof t) return ge(e.Kt, t);
        if ("boolean" == typeof t) return {
            booleanValue: t
        };
        if ("string" == typeof t) return {
            stringValue: t
        };
        if (t instanceof Date) {
            const n = H.fromDate(t);
            return {
                timestampValue: $n(e.Kt, n)
            };
        }
        if (t instanceof H) {
            // Firestore backend truncates precision down to microseconds. To ensure
            // offline mode works the same with regards to truncation, perform the
            // truncation immediately without waiting for the backend to do that.
            const n = new H(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));
            return {
                timestampValue: $n(e.Kt, n)
            };
        }
        if (t instanceof sa) return {
            geoPointValue: {
                latitude: t.latitude,
                longitude: t.longitude
            }
        };
        if (t instanceof k) return {
            bytesValue: Bn(e.Kt, t.l)
        };
        if (t instanceof Hc) {
            const n = e.T, s = t.firestore.I_;
            if (!s.isEqual(n)) throw e.K_(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${n.projectId}/${n.database}`);
            return {
                referenceValue: Qn(t.firestore.I_ || e.T, t.S_.path)
            };
        }
        if (void 0 === t && e.ignoreUndefinedProperties) return null;
        throw e.K_("Unsupported field value: " + Qc(t));
    }
    /**
 * Checks whether an object looks like a JSON object that should be converted
 * into a struct. Normal class/prototype instances are considered to look like
 * JSON objects since they should be converted to a struct value. Arrays, Dates,
 * GeoPoints, etc. are not considered to look like JSON objects since they map
 * to specific FieldValue types other than ObjectValue.
 */ (t, e);
}

function Pa(t, e) {
    const n = {};
    return it(t) ? 
    // If we encounter an empty object, we explicitly add it to the update
    // mask to ensure that the server creates a map entry.
    e.path && e.path.length > 0 && e.zt.push(e.path) : st(t, ((t, s) => {
        const i = Ra(s, e.L_(t));
        null != i && (n[t] = i);
    })), {
        mapValue: {
            fields: n
        }
    };
}

function ya(t) {
    return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof H || t instanceof sa || t instanceof k || t instanceof Hc || t instanceof Mc);
}

function ga(t, e, n) {
    if (!ya(n) || !function(t) {
        return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));
    }(n)) {
        const s = Qc(n);
        throw "an object" === s ? e.K_(t + " a custom object") : e.K_(t + " " + s);
    }
}

/**
 * Helper that calls fromDotSeparatedString() but wraps any error thrown.
 */ function Va(t, e, n) {
    if (
    // If required, replace the FieldPath Compat class with with the firestore-exp
    // FieldPath.
    e instanceof M && (e = e._), e instanceof kc) return e.d_;
    if ("string" == typeof e) return ba(t, e);
    throw va("Field path arguments must be of type string or FieldPath.", t, 
    /* hasConverter= */ !1, 
    /* path= */ void 0, n);
}

/**
 * Matches any characters in a field path string that are reserved.
 */ const pa = new RegExp("[~\\*/\\[\\]]");

/**
 * Wraps fromDotSeparatedString with an error message about the method that
 * was thrown.
 * @param methodName - The publicly visible method name
 * @param path - The dot-separated string form of a field path which will be
 * split on dots.
 * @param targetDoc - The document against which the field path will be
 * evaluated.
 */ function ba(t, e, n) {
    if (e.search(pa) >= 0) throw va(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t, 
    /* hasConverter= */ !1, 
    /* path= */ void 0, n);
    try {
        return new kc(...e.split(".")).d_;
    } catch (s) {
        throw va(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t, 
        /* hasConverter= */ !1, 
        /* path= */ void 0, n);
    }
}

function va(t, e, n, s, i) {
    const r = s && !s.nt(), o = void 0 !== i;
    let c = `Function ${e}() called with invalid data`;
    n && (c += " (via `toFirestore()`)"), c += ". ";
    let a = "";
    return (r || o) && (a += " (found", r && (a += " in field " + s), o && (a += " in document " + i), 
    a += ")"), new F(O.INVALID_ARGUMENT, c + t + a);
}

/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function Sa(t, e) {
    return t.some((t => t.isEqual(e)));
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Internal transaction object responsible for accumulating the mutations to
 * perform and the base versions for any documents read.
 */ class Da {
    constructor(t) {
        this.Dh = t, 
        // The version of each document that was read during this transaction.
        this.Y_ = new Map, this.mutations = [], this.X_ = !1, 
        /**
         * A deferred usage error that occurred previously in this transaction that
         * will cause the transaction to fail once it actually commits.
         */
        this.Z_ = null, 
        /**
         * Set of documents that have been written in the transaction.
         *
         * When there's more than one write to the same key in a transaction, any
         * writes after the first are handled differently.
         */
        this.tf = new Set;
    }
    async ef(t) {
        if (this.nf(), this.mutations.length > 0) throw new F(O.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes.");
        const e = await async function(t, e) {
            const n = b(t), s = Hn(n.Kt) + "/documents", i = {
                documents: e.map((t => jn(n.Kt, t)))
            }, r = await n.Cu("BatchGetDocuments", s, i), o = new Map;
            r.forEach((t => {
                const e = Zn(n.Kt, t);
                o.set(e.key.toString(), e);
            }));
            const c = [];
            return e.forEach((t => {
                const e = o.get(t.toString());
                p(!!e), c.push(e);
            })), c;
        }(this.Dh, t);
        return e.forEach((t => {
            t instanceof Ot || t instanceof Nt ? this.sf(t) : V();
        })), e;
    }
    set(t, e) {
        this.write(e.O_(t, this.Gt(t))), this.tf.add(t.toString());
    }
    update(t, e) {
        try {
            this.write(e.O_(t, this.rf(t)));
        } catch (t) {
            this.Z_ = t;
        }
        this.tf.add(t.toString());
    }
    delete(t) {
        this.write(new tn(t, this.Gt(t))), this.tf.add(t.toString());
    }
    async commit() {
        if (this.nf(), this.Z_) throw this.Z_;
        const t = this.Y_;
        // For each mutation, note that the doc was written.
                this.mutations.forEach((e => {
            t.delete(e.key.toString());
        })), 
        // For each document that was read but not written to, we want to perform
        // a `verify` operation.
        t.forEach(((t, e) => {
            const n = et.ft(e);
            this.mutations.push(new en(n, this.Gt(n)));
        })), await async function(t, e) {
            const n = b(t), s = Hn(n.Kt) + "/documents", i = {
                writes: e.map((t => es(n.Kt, t)))
            };
            await n.bu("Commit", s, i);
        }(this.Dh, this.mutations), this.X_ = !0;
    }
    sf(t) {
        let e;
        if (t instanceof Nt) e = t.version; else {
            if (!(t instanceof Ot)) throw V();
            // For deleted docs, we must use baseVersion 0 when we overwrite them.
            e = J.min();
        }
        const n = this.Y_.get(t.key.toString());
        if (n) {
            if (!e.isEqual(n)) 
            // This transaction will fail no matter what.
            throw new F(O.ABORTED, "Document version changed between two reads.");
        } else this.Y_.set(t.key.toString(), e);
    }
    /**
     * Returns the version of this document when it was read in this transaction,
     * as a precondition, or no precondition if it was not read.
     */    Gt(t) {
        const e = this.Y_.get(t.toString());
        return !this.tf.has(t.toString()) && e ? Be.updateTime(e) : Be.jt();
    }
    /**
     * Returns the precondition for a document if the operation is an update.
     */    rf(t) {
        const e = this.Y_.get(t.toString());
        // The first time a document is written, we want to take into account the
        // read time and existence
                if (!this.tf.has(t.toString()) && e) {
            if (e.isEqual(J.min())) 
            // The document doesn't exist, so fail the transaction.
            // This has to be validated locally because you can't send a
            // precondition that a document does not exist without changing the
            // semantics of the backend write to be an insert. This is the reverse
            // of what we want, since we want to assert that the document doesn't
            // exist but then send the update and have it fail. Since we can't
            // express that to the backend, we have to validate locally.
            // Note: this can change once we can send separate verify writes in the
            // transaction.
            throw new F(O.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
            // Document exists, base precondition on document update time.
                        return Be.updateTime(e);
        }
        // Document was not read, so we just use the preconditions for a blind
        // update.
        return Be.exists(!0);
    }
    write(t) {
        this.nf(), this.mutations.push(t);
    }
    nf() {}
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * TransactionRunner encapsulates the logic needed to run and retry transactions
 * with backoff.
 */
class Ca {
    constructor(t, e, n, s) {
        this.fs = t, this.Dh = e, this.updateFunction = n, this.Ts = s, this.cf = 5, this.zu = new Xr(this.fs, "transaction_retry" /* TransactionRetry */);
    }
    /** Runs the transaction and sets the result on deferred. */    run() {
        this.af();
    }
    af() {
        this.zu.Bu((async () => {
            const t = new Da(this.Dh), e = this.uf(t);
            e && e.then((e => {
                this.fs.ys((() => t.commit().then((() => {
                    this.Ts.resolve(e);
                })).catch((t => {
                    this.hf(t);
                }))));
            })).catch((t => {
                this.hf(t);
            }));
        }));
    }
    uf(t) {
        try {
            const e = this.updateFunction(t);
            return !ft(e) && e.catch && e.then ? e : (this.Ts.reject(Error("Transaction callback must return a Promise")), 
            null);
        } catch (t) {
            // Do not retry errors thrown by user provided updateFunction.
            return this.Ts.reject(t), null;
        }
    }
    hf(t) {
        this.cf > 0 && this.lf(t) ? (this.cf -= 1, this.fs.ys((() => (this.af(), Promise.resolve())))) : this.Ts.reject(t);
    }
    lf(t) {
        if ("FirebaseError" === t.name) {
            // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and
            // non-matching document versions with ABORTED. These errors should be retried.
            const e = t.code;
            return "aborted" === e || "failed-precondition" === e || !on(e);
        }
        return !1;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * FirestoreClient is a top-level class that constructs and owns all of the
 * pieces of the client SDK architecture. It is responsible for creating the
 * async queue that is shared by all of the other components in the system.
 */
class xa {
    constructor(t, 
    /**
     * Asynchronous queue responsible for all of our internal processing. When
     * we get incoming work from the user (via public API) or the network
     * (incoming GRPC messages), we should always schedule onto this queue.
     * This ensures all of our work is properly serialized (e.g. we don't
     * start processing a new operation while the previous one is waiting for
     * an async I/O to complete).
     */
    e, n) {
        this.credentials = t, this.fs = e, this.gu = n, this.user = U.UNAUTHENTICATED, this.clientId = S.t(), 
        this._f = () => {}, this.N = new ms, this.credentials.S((t => {
            R("FirestoreClient", "Received user=", t.uid), this.user = t, this._f(t), this.N.resolve();
        }));
    }
    async getConfiguration() {
        return await this.N.promise, {
            fs: this.fs,
            gu: this.gu,
            clientId: this.clientId,
            credentials: this.credentials,
            Yl: this.user,
            bl: 100
        };
    }
    ff(t) {
        this._f = t, 
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        this.N.promise.then((() => this._f(this.user)));
    }
    /**
     * Checks that the client has not been terminated. Ensures that other methods on
     * this class cannot be called after the client is terminated.
     */    df() {
        if (this.fs.wf) throw new F(O.FAILED_PRECONDITION, "The client has already been terminated.");
    }
    terminate() {
        this.fs.Ef();
        const t = new ms;
        return this.fs.Tf((async () => {
            try {
                this.If && await this.If.terminate(), this.mf && await this.mf.terminate(), 
                // `removeChangeListener` must be called after shutting down the
                // RemoteStore as it will prevent the RemoteStore from retrieving
                // auth tokens.
                this.credentials.D(), t.resolve();
            } catch (e) {
                const n = Cs(e, "Failed to shutdown persistence");
                t.reject(n);
            }
        })), t.promise;
    }
}

async function Na(t, e) {
    t.fs.Af(), R("FirestoreClient", "Initializing OfflineComponentProvider");
    const n = await t.getConfiguration();
    await e.initialize(n);
    let s = n.Yl;
    t.ff((n => {
        s.isEqual(n) || (s = n, t.fs.bo((async () => {
            await hr(e.Sh, n);
        })));
    })), 
    // When a user calls clearPersistence() in one client, all other clients
    // need to be terminated to allow the delete to succeed.
    e.persistence.yo((() => t.terminate())), t.mf = e;
}

async function Oa(t, e) {
    t.fs.Af();
    const n = await Fa(t);
    R("FirestoreClient", "Initializing OnlineComponentProvider");
    const s = await t.getConfiguration();
    await e.initialize(n, s), 
    // The CredentialChangeListener of the online component provider takes
    // precedence over the offline component provider.
    t.ff((n => t.fs.bo((() => async function(t, e) {
        const n = b(t);
        n.fs.Af(), R("RemoteStore", "RemoteStore received new credentials");
        const s = fo(n);
        // Tear down and re-create our network streams. This will ensure we get a
        // fresh auth token for the new user and re-fill the write pipeline with
        // new mutations from the LocalStore (since mutations are per-user).
                n.Oh.add(3 /* CredentialChange */), await oo(n), s && 
        // Don't set the network status to Unknown if we are offline.
        n.Mh.set("Unknown" /* Unknown */), await n.Ch.s_(e), n.Oh.delete(3 /* CredentialChange */), 
        await ro(n);
    }(e.gl, n))))), t.If = e;
}

async function Fa(t) {
    return t.mf || (R("FirestoreClient", "Using default OfflineComponentProvider"), 
    await Na(t, new Sc)), t.mf;
}

async function ka(t) {
    return t.If || (R("FirestoreClient", "Using default OnlineComponentProvider"), await Oa(t, new xc)), 
    t.If;
}

function Ma(t) {
    return Fa(t).then((t => t.persistence));
}

function La(t) {
    return Fa(t).then((t => t.Sh));
}

function $a(t) {
    return ka(t).then((t => t.gl));
}

function Ba(t) {
    return ka(t).then((t => t.fa));
}

async function qa(t) {
    const e = await ka(t), n = e.Vl;
    return n.Gh = Yo.bind(null, e.fa), n.Jh = Zo.bind(null, e.fa), n;
}

/** Enables the network connection and re-enqueues all pending operations. */ function Ua(t) {
    return t.fs.enqueue((async () => {
        const e = await Ma(t), n = await $a(t);
        return e.Vo(!0), function(t) {
            const e = b(t);
            return e.Oh.delete(0 /* UserDisabled */), ro(e);
        }(n);
    }));
}

/** Disables the network connection. Pending operations will not complete. */ function Qa(t) {
    return t.fs.enqueue((async () => {
        const e = await Ma(t), n = await $a(t);
        return e.Vo(!1), async function(t) {
            const e = b(t);
            e.Oh.add(0 /* UserDisabled */), await oo(e), 
            // Set the OnlineState to Offline so get()s return from cache, etc.
            e.Mh.set("Offline" /* Offline */);
        }(n);
    }));
}

/**
 * Returns a Promise that resolves when all writes that were pending at the time
 * this method was called received server acknowledgement. An acknowledgement
 * can be either acceptance or rejection.
 */ function Ka(t, e) {
    const n = new ms;
    return t.fs.ys((async () => async function(t, e, n) {
        try {
            const s = await function(t, e) {
                const n = b(t);
                return n.persistence.runTransaction("read document", "readonly", (t => n.Ic.Jo(t, e)));
            }(t, e);
            s instanceof Nt ? n.resolve(s) : s instanceof Ot ? n.resolve(null) : n.reject(new F(O.UNAVAILABLE, "Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"));
        } catch (t) {
            const s = Cs(t, `Failed to get document '${e} from cache`);
            n.reject(s);
        }
    }
    /**
 * Retrieves a latency-compensated document from the backend via a
 * SnapshotListener.
 */ (await La(t), e, n))), n.promise;
}

function ja(t, e, n = {}) {
    const s = new ms;
    return t.fs.ys((async () => function(t, e, n, s, i) {
        const r = new Oc({
            next: r => {
                // Remove query first before passing event to user to avoid
                // user actions affecting the now stale query.
                e.ys((() => ko(t, o)));
                const c = r.docs.has(n);
                !c && r.fromCache ? 
                // TODO(dimond): If we're online and the document doesn't
                // exist then we resolve with a doc.exists set to false. If
                // we're offline however, we reject the Promise in this
                // case. Two options: 1) Cache the negative response from
                // the server so we can deliver that even when you're
                // offline 2) Actually reject the Promise in the online case
                // if the document doesn't exist.
                i.reject(new F(O.UNAVAILABLE, "Failed to get document because the client is offline.")) : c && r.fromCache && s && "server" === s.source ? i.reject(new F(O.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')) : i.resolve(r);
            },
            error: t => i.reject(t)
        }), o = new Bo(oe(n.path), r, {
            includeMetadataChanges: !0,
            sl: !0
        });
        return Fo(t, o);
    }(await qa(t), t.fs, e, n, s))), s.promise;
}

function Wa(t, e) {
    const n = new ms;
    return t.fs.ys((async () => async function(t, e, n) {
        try {
            const s = await Ir(t, e, 
            /* usePreviousResults= */ !0), i = new Go(e, s.Pc), r = i.dl(s.documents), o = i.Ei(r, 
            /* updateLimboDocuments= */ !1);
            n.resolve(o.snapshot);
        } catch (t) {
            const s = Cs(t, `Failed to execute query '${e} against cache`);
            n.reject(s);
        }
    }
    /**
 * Retrieves a latency-compensated query snapshot from the backend via a
 * SnapshotListener.
 */ (await La(t), e, n))), n.promise;
}

function Ga(t, e, n = {}) {
    const s = new ms;
    return t.fs.ys((async () => function(t, e, n, s, i) {
        const r = new Oc({
            next: n => {
                // Remove query first before passing event to user to avoid
                // user actions affecting the now stale query.
                e.ys((() => ko(t, o))), n.fromCache && "server" === s.source ? i.reject(new F(O.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')) : i.resolve(n);
            },
            error: t => i.reject(t)
        }), o = new Bo(n, r, {
            includeMetadataChanges: !0,
            sl: !0
        });
        return Fo(t, o);
    }(await qa(t), t.fs, e, n, s))), s.promise;
}

function za(t, e) {
    const n = new Oc(e);
    return t.fs.ys((async () => function(t, e) {
        b(t).Wh.add(e), 
        // Immediately fire an initial event, indicating all existing listeners
        // are in-sync.
        e.next();
    }(await qa(t), n))), () => {
        n.r_(), t.fs.ys((async () => function(t, e) {
            b(t).Wh.delete(e);
        }(await qa(t), n)));
    };
}

/**
 * Takes an updateFunction in which a set of reads and writes can be performed
 * atomically. In the updateFunction, the client can read and write values
 * using the supplied transaction object. After the updateFunction, all
 * changes will be committed. If a retryable error occurs (ex: some other
 * client has changed any of the data referenced), then the updateFunction
 * will be called again after a backoff. If the updateFunction still fails
 * after all retries, then the transaction will be rejected.
 *
 * The transaction object passed to the updateFunction contains methods for
 * accessing documents and collections. Unlike other datastore access, data
 * accessed with the transaction will not reflect local changes that have not
 * been committed. For this reason, it is required that all reads are
 * performed before any writes. Transactions must be performed while online.
 */ function Ha(t, e) {
    const n = new ms;
    return t.fs.ys((async () => {
        const s = await function(t) {
            return ka(t).then((t => t.Dh));
        }(t);
        new Ca(t.fs, s, e, n).run();
    })), n.promise;
}

function Ja(t, e, n, s) {
    const i = function(t, e) {
        let n;
        n = "string" == typeof t ? (new TextEncoder).encode(t) : t;
        return function(t, e) {
            return new Fc(t, e);
        }(function(t, e) {
            if (t instanceof Uint8Array) return Nc(t, e);
            if (t instanceof ArrayBuffer) return Nc(new Uint8Array(t), e);
            if (t instanceof ReadableStream) return t.getReader();
            throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream");
        }(n), e);
    }
    /**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ (n, Yr(e));
    t.fs.ys((async () => {
        vc(await Ba(t), i, s);
    }));
}

function Ya(t, e) {
    return t.fs.enqueue((async () => function(t, e) {
        const n = b(t);
        return n.persistence.runTransaction("Get named query", "readonly", (t => n.Eo.$s(t, e)));
    }(await La(t), e)));
}

class Xa {
    constructor() {
        // The last promise in the queue.
        this.Rf = Promise.resolve(), 
        // A list of retryable operations. Retryable operations are run in order and
        // retried with backoff.
        this.Pf = [], 
        // Is this AsyncQueue being shut down? Once it is set to true, it will not
        // be changed again.
        this.yf = !1, 
        // Operations scheduled to be queued in the future. Operations are
        // automatically removed after they are run or canceled.
        this.gf = [], 
        // visible for testing
        this.Vf = null, 
        // Flag set while there's an outstanding AsyncQueue operation, used for
        // assertion sanity-checks.
        this.pf = !1, 
        // List of TimerIds to fast-forward delays for.
        this.bf = [], 
        // Backoff timer used to schedule retries for retryable operations
        this.zu = new Xr(this, "async_queue_retry" /* AsyncQueueRetry */), 
        // Visibility handler that triggers an immediate retry of all retryable
        // operations. Meant to speed up recovery when we regain file system access
        // after page comes into foreground.
        this.vf = () => {
            const t = Jr();
            t && R("AsyncQueue", "Visibility state changed to " + t.visibilityState), this.zu.Uu();
        };
        const t = Jr();
        t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this.vf);
    }
    get wf() {
        return this.yf;
    }
    /**
     * Adds a new operation to the queue without waiting for it to complete (i.e.
     * we ignore the Promise result).
     */    ys(t) {
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        this.enqueue(t);
    }
    Tf(t) {
        this.Sf(), 
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        this.Df(t);
    }
    Ef() {
        if (!this.yf) {
            this.yf = !0;
            const t = Jr();
            t && "function" == typeof t.removeEventListener && t.removeEventListener("visibilitychange", this.vf);
        }
    }
    enqueue(t) {
        return this.Sf(), this.yf ? new Promise((t => {})) : this.Df(t);
    }
    bo(t) {
        this.ys((() => (this.Pf.push(t), this.Cf())));
    }
    /**
     * Runs the next operation from the retryable queue. If the operation fails,
     * reschedules with backoff.
     */    async Cf() {
        if (0 !== this.Pf.length) {
            try {
                await this.Pf[0](), this.Pf.shift(), this.zu.reset();
            } catch (t) {
                if (!Vs(t)) throw t;
 // Failure will be handled by AsyncQueue
                                R("AsyncQueue", "Operation failed with retryable error: " + t);
            }
            this.Pf.length > 0 && 
            // If there are additional operations, we re-schedule `retryNextOp()`.
            // This is necessary to run retryable operations that failed during
            // their initial attempt since we don't know whether they are already
            // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
            // needs to  be re-run, we will run `op1`, `op1`, `op2` using the
            // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
            // call scheduled here.
            // Since `backoffAndRun()` cancels an existing backoff and schedules a
            // new backoff on every call, there is only ever a single additional
            // operation in the queue.
            this.zu.Bu((() => this.Cf()));
        }
    }
    Df(t) {
        const e = this.Rf.then((() => (this.pf = !0, t().catch((t => {
            this.Vf = t, this.pf = !1;
            // Re-throw the error so that this.tail becomes a rejected Promise and
            // all further attempts to chain (via .then) will just short-circuit
            // and return the rejected Promise.
            throw P("INTERNAL UNHANDLED ERROR: ", 
            /**
 * Chrome includes Error.message in Error.stack. Other browsers do not.
 * This returns expected output of message + stack when available.
 * @param error - Error or FirestoreError
 */
            function(t) {
                let e = t.message || "";
                t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack);
                return e;
            }
            /**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
            /** DOMException error code constants. */ (t)), t;
        })).then((t => (this.pf = !1, t))))));
        return this.Rf = e, e;
    }
    Ir(t, e, n) {
        this.Sf(), 
        // Fast-forward delays for timerIds that have been overriden.
        this.bf.indexOf(t) > -1 && (e = 0);
        const s = Ds.Is(this, t, e, n, (t => this.xf(t)));
        return this.gf.push(s), s;
    }
    Sf() {
        this.Vf && V();
    }
    Af() {}
    /**
     * Waits until all currently queued tasks are finished executing. Delayed
     * operations are not run.
     */    async Nf() {
        // Operations in the queue prior to draining may have enqueued additional
        // operations. Keep draining the queue until the tail is no longer advanced,
        // which indicates that no more new operations were enqueued and that all
        // operations were executed.
        let t;
        do {
            t = this.Rf, await t;
        } while (t !== this.Rf);
    }
    /**
     * For Tests: Determine if a delayed operation with a particular TimerId
     * exists.
     */    Of(t) {
        for (const e of this.gf) if (e.ds === t) return !0;
        return !1;
    }
    /**
     * For Tests: Runs some or all delayed operations early.
     *
     * @param lastTimerId - Delayed operations up to and including this TimerId
     * will be drained. Pass TimerId.All to run all delayed operations.
     * @returns a Promise that resolves once all operations have been run.
     */    Ff(t) {
        // Note that draining may generate more delayed ops, so we do that first.
        return this.Nf().then((() => {
            // Run ops in the same order they'd run if they ran naturally.
            this.gf.sort(((t, e) => t.ws - e.ws));
            for (const e of this.gf) if (e.Ps(), "all" /* All */ !== t && e.ds === t) break;
            return this.Nf();
        }));
    }
    /**
     * For Tests: Skip all subsequent delays for a timer id.
     */    kf(t) {
        this.bf.push(t);
    }
    /** Called once a DelayedOperation is run or canceled. */    xf(t) {
        // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
        const e = this.gf.indexOf(t);
        this.gf.splice(e, 1);
    }
}

const Za = -1;

/**
 * The Cloud Firestore service interface.
 *
 * Do not call this constructor directly. Instead, use {@link getFirestore}.
 */
class tu extends zc {
    /** @hideconstructor */
    constructor(t, e) {
        super(t, e), this.Mf = new Xa, this.w_ = "name" in t ? t.name : "[DEFAULT]";
    }
    b_() {
        return this.Lf || 
        // The client must be initialized to ensure that all subsequent API
        // usage throws an exception.
        nu(this), this.Lf.terminate();
    }
}

function eu(t) {
    return t.Lf || nu(t), t.Lf.df(), t.Lf;
}

function nu(t) {
    const e = t.p_(), n = function(t, e, n) {
        return new B(t, e, n.host, n.ssl, n.experimentalForceLongPolling, n.experimentalAutoDetectLongPolling);
    }(t.I_, t.w_, e);
    t.Lf = new xa(t.m_, t.Mf, n);
}

/**
 * Attempts to enable persistent storage, if possible.
 *
 * Must be called before any other functions (other than
 * {@link initializeFirestore}, {@link getFirestore} or
 * {@link clearIndexedDbPersistence}.
 *
 * If this fails, `enableIndexedDbPersistence()` will reject the promise it
 * returns. Note that even after this failure, the `Firestore` instance will
 * remain usable, however offline persistence will be disabled.
 *
 * There are several reasons why this can fail, which can be identified by
 * the `code` on the error.
 *
 *   * failed-precondition: The app is already open in another browser tab.
 *   * unimplemented: The browser is incompatible with the offline
 *     persistence implementation.
 *
 * @param firestore - The `Firestore` instance to enable persistence for.
 * @param persistenceSettings - Optional settings object to configure
 * persistence.
 * @returns A promise that represents successfully enabling persistent storage.
 */
/**
 * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.
 * If the operation fails with a recoverable error (see
 * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected
 * but the client remains usable.
 */
function su(t, e, n) {
    const s = new ms;
    return t.fs.enqueue((async () => {
        try {
            await Na(t, n), await Oa(t, e), s.resolve();
        } catch (t) {
            if (!
            /**
 * Decides whether the provided error allows us to gracefully disable
 * persistence (as opposed to crashing the client).
 */
            function(t) {
                if ("FirebaseError" === t.name) return t.code === O.FAILED_PRECONDITION || t.code === O.UNIMPLEMENTED;
                if ("undefined" != typeof DOMException && t instanceof DOMException) 
                // There are a few known circumstances where we can open IndexedDb but
                // trying to read/write will fail (e.g. quota exceeded). For
                // well-understood cases, we attempt to detect these and then gracefully
                // fall back to memory persistence.
                // NOTE: Rather than continue to add to this list, we could decide to
                // always fall back, with the risk that we might accidentally hide errors
                // representing actual SDK bugs.
                // When the browser is out of quota we could get either quota exceeded
                // or an aborted error depending on whether the error happened during
                // schema migration.
                return 22 === t.code || 20 === t.code || 
                // Firefox Private Browsing mode disables IndexedDb and returns
                // INVALID_STATE for any usage.
                11 === t.code;
                return !0;
            }
            /**
 * Clears the persistent storage. This includes pending writes and cached
 * documents.
 *
 * Must be called while the `Firestore` instance is not started (after the app is
 * terminated or when the app is first initialized). On startup, this function
 * must be called before other functions (other than {@link
 * initializeFirestore} or {@link getFirestore})). If the `Firestore`
 * instance is still running, the promise will be rejected with the error code
 * of `failed-precondition`.
 *
 * Note: `clearIndexedDbPersistence()` is primarily intended to help write
 * reliable tests that use Cloud Firestore. It uses an efficient mechanism for
 * dropping existing data but does not attempt to securely overwrite or
 * otherwise make cached data unrecoverable. For applications that are sensitive
 * to the disclosure of cached data in between user sessions, we strongly
 * recommend not enabling persistence at all.
 *
 * @param firestore - The `Firestore` instance to clear persistence for.
 * @returns A promise that is resolved when the persistent storage is
 * cleared. Otherwise, the promise is rejected with an error.
 */ (t)) throw t;
            console.warn("Error enabling offline persistence. Falling back to persistence disabled: " + t), 
            s.reject(t);
        }
    })).then((() => s.promise));
}

function iu(t) {
    if (t.R_ && !t.P_) throw new F(O.FAILED_PRECONDITION, "Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");
    const e = new ms;
    return t.Mf.Tf((async () => {
        try {
            await async function(t) {
                if (!Ps.jn()) return Promise.resolve();
                const e = t + "main";
                await Ps.delete(e);
            }(sr(t.I_, t.w_)), e.resolve();
        } catch (t) {
            e.reject(t);
        }
    })), e.promise;
}

/**
 * Waits until all currently pending writes for the active user have been
 * acknowledged by the backend.
 *
 * The returned Promise resolves immediately if there are no outstanding writes.
 * Otherwise, the Promise waits for all previously issued writes (including
 * those written in a previous app session), but it does not wait for writes
 * that were added after the function is called. If you want to wait for
 * additional writes, call `waitForPendingWrites()` again.
 *
 * Any outstanding `waitForPendingWrites()` Promises are rejected during user
 * changes.
 *
 * @returns A Promise which resolves when all currently pending writes have been
 * acknowledged by the backend.
 */ function ru(t) {
    return function(t) {
        const e = new ms;
        return t.fs.ys((async () => oc(await Ba(t), e))), e.promise;
    }(eu(t = Kc(t, tu)));
}

/**
 * Re-enables use of the network for this Firestore instance after a prior
 * call to {@link disableNetwork}.
 *
 * @returns A promise that is resolved once the network has been enabled.
 */ function ou(t) {
    if (t.R_ || t.P_) throw new F(O.FAILED_PRECONDITION, "Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Converts Firestore's internal types to the JavaScript types that we expose
 * to the user.
 */ class cu {
    $f(t, e = "none") {
        switch (Et(t)) {
          case 0 /* NullValue */ :
            return null;

          case 1 /* BooleanValue */ :
            return t.booleanValue;

          case 2 /* NumberValue */ :
            return at(t.integerValue || t.doubleValue);

          case 3 /* TimestampValue */ :
            return this.Bf(t.timestampValue);

          case 4 /* ServerTimestampValue */ :
            return this.qf(t, e);

          case 5 /* StringValue */ :
            return t.stringValue;

          case 6 /* BlobValue */ :
            return this.Uf(ut(t.bytesValue));

          case 7 /* RefValue */ :
            return this.Qf(t.referenceValue);

          case 8 /* GeoPointValue */ :
            return this.Kf(t.geoPointValue);

          case 9 /* ArrayValue */ :
            return this.jf(t.arrayValue, e);

          case 10 /* ObjectValue */ :
            return this.Wf(t.mapValue, e);

          default:
            throw V();
        }
    }
    Wf(t, e) {
        const n = {};
        return st(t.fields || {}, ((t, s) => {
            n[t] = this.$f(s, e);
        })), n;
    }
    Kf(t) {
        return new sa(at(t.latitude), at(t.longitude));
    }
    jf(t, e) {
        return (t.values || []).map((t => this.$f(t, e)));
    }
    qf(t, e) {
        switch (e) {
          case "previous":
            const n = lt(t);
            return null == n ? null : this.$f(n, e);

          case "estimate":
            return this.Bf(_t(t));

          default:
            return null;
        }
    }
    Bf(t) {
        const e = ct(t);
        return new H(e.seconds, e.nanos);
    }
    Gf(t, e) {
        const n = X.ct(t);
        p(Is(n));
        const s = new q(n.get(1), n.get(3)), i = new et(n.X(5));
        return s.isEqual(e) || 
        // TODO(b/64130202): Somehow support foreign references.
        P(`Document ${i} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`), 
        i;
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A `DocumentSnapshot` contains data read from a document in your Firestore
 * database. The data can be extracted with `.data()` or `.get(<field>)` to
 * get a specific field.
 *
 * For a `DocumentSnapshot` that points to a non-existing document, any data
 * access will return 'undefined'. You can use the `exists()` method to
 * explicitly verify a document's existence.
 */ class au {
    // Note: This class is stripped down version of the DocumentSnapshot in
    // the legacy SDK. The changes are:
    // - No support for SnapshotMetadata.
    // - No support for SnapshotOptions.
    /** @hideconstructor protected */
    constructor(t, e, n, s, i) {
        this.zf = t, this.Hf = e, this.S_ = n, this.Jf = s, this.v_ = i;
    }
    /** Property of the `DocumentSnapshot` that provides the document's ID. */    get id() {
        return this.S_.path.et();
    }
    /**
     * The `DocumentReference` for the document included in the `DocumentSnapshot`.
     */    get ref() {
        return new Hc(this.zf, this.v_, this.S_);
    }
    /**
     * Signals whether or not the document at the snapshot's location exists.
     *
     * @returns true if the document exists.
     */    exists() {
        return null !== this.Jf;
    }
    /**
     * Retrieves all fields in the document as an `Object`. Returns `undefined` if
     * the document doesn't exist.
     *
     * @returns An `Object` containing all fields in the document or `undefined`
     * if the document doesn't exist.
     */    data() {
        if (this.Jf) {
            if (this.v_) {
                // We only want to use the converter and create a new DocumentSnapshot
                // if a converter has been provided.
                const t = new uu(this.zf, this.Hf, this.S_, this.Jf, 
                /* converter= */ null);
                return this.v_.fromFirestore(t);
            }
            return this.Hf.$f(this.Jf.vt());
        }
    }
    /**
     * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
     * document or field doesn't exist.
     *
     * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
     * field.
     * @returns The data at the specified field location or undefined if no such
     * field exists in the document.
     */
    // We are using `any` here to avoid an explicit cast by our users.
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    get(t) {
        if (this.Jf) {
            const e = this.Jf.data().field(hu("DocumentSnapshot.get", t));
            if (null !== e) return this.Hf.$f(e);
        }
    }
}

/**
 * A `QueryDocumentSnapshot` contains data read from a document in your
 * Firestore database as part of a query. The document is guaranteed to exist
 * and its data can be extracted with `.data()` or `.get(<field>)` to get a
 * specific field.
 *
 * A `QueryDocumentSnapshot` offers the same API surface as a
 * `DocumentSnapshot`. Since query results contain only existing documents, the
 * `exists` property will always be true and `data()` will never return
 * 'undefined'.
 */ class uu extends au {
    /**
     * Retrieves all fields in the document as an `Object`.
     *
     * @override
     * @returns An `Object` containing all fields in the document.
     */
    data() {
        return super.data();
    }
}

/**
 * Helper that calls fromDotSeparatedString() but wraps any error thrown.
 */ function hu(t, e) {
    return "string" == typeof e ? ba(t, e) : e instanceof M ? e._.d_ : e.d_;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ function lu(t) {
    if (ae(t) && 0 === t.Nt.length) throw new F(O.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause");
}

/**
 * A `QueryConstraint` is used to narrow the set of documents returned by a
 * Firestore query. `QueryConstraint`s are created by invoking {@link where},
 * {@link orderBy}, {@link startAt}, {@link startAfter}, {@link
 * endBefore}, {@link endAt}, {@link limit} or {@link limitToLast} and
 * can then be passed to {@link query} to create a new query instance that
 * also contains this `QueryConstraint`.
 */ class _u {}

/**
 * Creates a new immutable instance of `query` that is extended to also include
 * additional query constraints.
 *
 * @param query - The query instance to use as a base for the new constraints.
 * @param queryConstraints - The list of `QueryConstraint`s to apply.
 * @throws if any of the provided query constraints cannot be combined with the
 * existing or new constraints.
 */ function fu(t, ...e) {
    for (const n of e) t = n.Yf(t);
    return t;
}

class du extends _u {
    constructor(t, e, n) {
        super(), this.Xf = t, this.Zf = e, this.td = n, this.type = "where";
    }
    Yf(t) {
        const e = ha(t.firestore), n = function(t, e, n, s, i, r, o) {
            let c;
            if (i.ht()) {
                if ("array-contains" /* ARRAY_CONTAINS */ === r || "array-contains-any" /* ARRAY_CONTAINS_ANY */ === r) throw new F(O.INVALID_ARGUMENT, `Invalid Query. You can't perform '${r}' queries on FieldPath.documentId().`);
                if ("in" /* IN */ === r || "not-in" /* NOT_IN */ === r) {
                    Ru(o, r);
                    const e = [];
                    for (const n of o) e.push(Au(s, t, n));
                    c = {
                        arrayValue: {
                            values: e
                        }
                    };
                } else c = Au(s, t, o);
            } else "in" /* IN */ !== r && "not-in" /* NOT_IN */ !== r && "array-contains-any" /* ARRAY_CONTAINS_ANY */ !== r || Ru(o, r), 
            c = Aa(n, e, o, 
            /* allowArrays= */ "in" /* IN */ === r || "not-in" /* NOT_IN */ === r);
            const a = Ut.create(i, r, c);
            return function(t, e) {
                if (e.xt()) {
                    const n = he(t);
                    if (null !== n && !n.isEqual(e.field)) throw new F(O.INVALID_ARGUMENT, `Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${n.toString()}' and '${e.field.toString()}'`);
                    const s = ue(t);
                    null !== s && Pu(t, e.field, s);
                }
                const n = function(t, e) {
                    for (const n of t.filters) if (e.indexOf(n.op) >= 0) return n.op;
                    return null;
                }(t, 
                /**
 * Given an operator, returns the set of operators that cannot be used with it.
 *
 * Operators in a query must adhere to the following set of rules:
 * 1. Only one array operator is allowed.
 * 2. Only one disjunctive operator is allowed.
 * 3. NOT_EQUAL cannot be used with another NOT_EQUAL operator.
 * 4. NOT_IN cannot be used with array, disjunctive, or NOT_EQUAL operators.
 *
 * Array operators: ARRAY_CONTAINS, ARRAY_CONTAINS_ANY
 * Disjunctive operators: IN, ARRAY_CONTAINS_ANY, NOT_IN
 */
                function(t) {
                    switch (t) {
                      case "!=" /* NOT_EQUAL */ :
                        return [ "!=" /* NOT_EQUAL */ , "not-in" /* NOT_IN */ ];

                      case "array-contains" /* ARRAY_CONTAINS */ :
                        return [ "array-contains" /* ARRAY_CONTAINS */ , "array-contains-any" /* ARRAY_CONTAINS_ANY */ , "not-in" /* NOT_IN */ ];

                      case "in" /* IN */ :
                        return [ "array-contains-any" /* ARRAY_CONTAINS_ANY */ , "in" /* IN */ , "not-in" /* NOT_IN */ ];

                      case "array-contains-any" /* ARRAY_CONTAINS_ANY */ :
                        return [ "array-contains" /* ARRAY_CONTAINS */ , "array-contains-any" /* ARRAY_CONTAINS_ANY */ , "in" /* IN */ , "not-in" /* NOT_IN */ ];

                      case "not-in" /* NOT_IN */ :
                        return [ "array-contains" /* ARRAY_CONTAINS */ , "array-contains-any" /* ARRAY_CONTAINS_ANY */ , "in" /* IN */ , "not-in" /* NOT_IN */ , "!=" /* NOT_EQUAL */ ];

                      default:
                        return [];
                    }
                }(e.op));
                if (null !== n) 
                // Special case when it's a duplicate op to give a slightly clearer error message.
                throw n === e.op ? new F(O.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new F(O.INVALID_ARGUMENT, `Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`);
            }(t, a), a;
        }(t.C_, "where", e, t.firestore.I_, this.Xf, this.Zf, this.td);
        return new Jc(t.firestore, t.v_, function(t, e) {
            const n = t.filters.concat([ e ]);
            return new ie(t.path, t.collectionGroup, t.Nt.slice(), n, t.limit, t.limitType, t.startAt, t.endAt);
        }(t.C_, n));
    }
}

/**
 * Creates a `QueryConstraint` that enforces that documents must contain the
 * specified field and that the value should satisfy the relation constraint
 * provided.
 *
 * @param fieldPath - The path to compare
 * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
 *   "&lt;=", "!=").
 * @param value - The value for comparison
 * @returns The created `Query`.
 */ class wu extends _u {
    constructor(t, e) {
        super(), this.Xf = t, this.ed = e, this.type = "orderBy";
    }
    Yf(t) {
        const e = function(t, e, n) {
            if (null !== t.startAt) throw new F(O.INVALID_ARGUMENT, "Invalid query. You must not call startAt() or startAfter() before calling orderBy().");
            if (null !== t.endAt) throw new F(O.INVALID_ARGUMENT, "Invalid query. You must not call endAt() or endBefore() before calling orderBy().");
            const s = new te(e, n);
            return function(t, e) {
                if (null === ue(t)) {
                    // This is the first order by. It must match any inequality.
                    const n = he(t);
                    null !== n && Pu(t, n, e.field);
                }
            }(t, s), s;
        }
        /**
 * Create a Bound from a query and a document.
 *
 * Note that the Bound will always include the key of the document
 * and so only the provided document will compare equal to the returned
 * position.
 *
 * Will throw if the document does not contain all fields of the order by
 * of the query or if any of the fields in the order by are an uncommitted
 * server timestamp.
 */ (t.C_, this.Xf, this.ed);
        return new Jc(t.firestore, t.v_, function(t, e) {
            // TODO(dimond): validate that orderBy does not list the same key twice.
            const n = t.Nt.concat([ e ]);
            return new ie(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
        }(t.C_, e));
    }
}

/**
 * Creates a `QueryConstraint` that sorts the query result by the
 * specified field, optionally in descending order instead of ascending.
 *
 * @param fieldPath - The field to sort by.
 * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
 * not specified, order will be ascending.
 * @returns The created `Query`.
 */ class Eu extends _u {
    constructor(t, e, n) {
        super(), this.type = t, this.nd = e, this.sd = n;
    }
    Yf(t) {
        return new Jc(t.firestore, t.v_, de(t.C_, this.nd, this.sd));
    }
}

/**
 * Creates a `QueryConstraint` that only returns the first matching documents.
 *
 * @param limit - The maximum number of items to return.
 * @returns The created `Query`.
 */ class Tu extends _u {
    constructor(t, e, n) {
        super(), this.type = t, this.rd = e, this.od = n;
    }
    Yf(t) {
        const e = mu(t, this.type, this.rd, this.od);
        return new Jc(t.firestore, t.v_, function(t, e) {
            return new ie(t.path, t.collectionGroup, t.Nt.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt);
        }(t.C_, e));
    }
}

class Iu extends _u {
    constructor(t, e, n) {
        super(), this.type = t, this.rd = e, this.od = n;
    }
    Yf(t) {
        const e = mu(t, this.type, this.rd, this.od);
        return new Jc(t.firestore, t.v_, function(t, e) {
            return new ie(t.path, t.collectionGroup, t.Nt.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e);
        }(t.C_, e));
    }
}

/** Helper function to create a bound from a document or fields */
function mu(t, e, n, s) {
    if (n[0] instanceof M && (n[0] = n[0]._), n[0] instanceof au) return function(t, e, n, s, i) {
        if (!s) throw new F(O.NOT_FOUND, "Can't use a DocumentSnapshot that doesn't exist for " + n + "().");
        const r = [];
        // Because people expect to continue/end a query at the exact document
        // provided, we need to use the implicit sort order rather than the explicit
        // sort order, because it's guaranteed to contain the document key. That way
        // the position becomes unambiguous and the query continues/ends exactly at
        // the provided document. Without the key (by using the explicit sort
        // orders), multiple documents could match the position, yielding duplicate
        // results.
                for (const n of _e(t)) if (n.field.ht()) r.push(yt(e, s.key)); else {
            const t = s.field(n.field);
            if (ht(t)) throw new F(O.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + n.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');
            if (null === t) {
                const t = n.field.ot();
                throw new F(O.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`);
            }
            r.push(t);
        }
        return new Xt(r, i);
    }
    /**
 * Converts a list of field values to a Bound for the given query.
 */ (t.C_, t.firestore.I_, e, n[0].Jf, s);
    {
        const i = ha(t.firestore);
        return function(t, e, n, s, i, r) {
            // Use explicit order by's because it has to match the query the user made
            const o = t.Nt;
            if (i.length > o.length) throw new F(O.INVALID_ARGUMENT, `Too many arguments provided to ${s}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);
            const c = [];
            for (let r = 0; r < i.length; r++) {
                const a = i[r];
                if (o[r].field.ht()) {
                    if ("string" != typeof a) throw new F(O.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${s}(), but got a ${typeof a}`);
                    if (!le(t) && -1 !== a.indexOf("/")) throw new F(O.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by FieldPath.documentId(), the value passed to ${s}() must be a plain document ID, but '${a}' contains a slash.`);
                    const n = t.path.child(X.ct(a));
                    if (!et.Et(n)) throw new F(O.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by FieldPath.documentId(), the value passed to ${s}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);
                    const i = new et(n);
                    c.push(yt(e, i));
                } else {
                    const t = Aa(n, s, a);
                    c.push(t);
                }
            }
            return new Xt(c, r);
        }
        /**
 * Parses the given documentIdValue into a ReferenceValue, throwing
 * appropriate errors if the value is anything other than a DocumentReference
 * or String, or if the string is malformed.
 */ (t.C_, t.firestore.I_, i, e, n, s);
    }
}

function Au(t, e, n) {
    if (n instanceof M && (n = n._), "string" == typeof n) {
        if ("" === n) throw new F(O.INVALID_ARGUMENT, "Invalid query. When querying with FieldPath.documentId(), you must provide a valid document ID, but it was an empty string.");
        if (!le(e) && -1 !== n.indexOf("/")) throw new F(O.INVALID_ARGUMENT, `Invalid query. When querying a collection by FieldPath.documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);
        const s = e.path.child(X.ct(n));
        if (!et.Et(s)) throw new F(O.INVALID_ARGUMENT, `Invalid query. When querying a collection group by FieldPath.documentId(), the value provided must result in a valid document path, but '${s}' is not because it has an odd number of segments (${s.length}).`);
        return yt(t, new et(s));
    }
    if (n instanceof Hc) return yt(t, n.S_);
    throw new F(O.INVALID_ARGUMENT, "Invalid query. When querying with FieldPath.documentId(), you must provide a valid string or a DocumentReference, but it was: " + Qc(n) + ".");
}

/**
 * Validates that the value passed into a disjunctive filter satisfies all
 * array requirements.
 */ function Ru(t, e) {
    if (!Array.isArray(t) || 0 === t.length) throw new F(O.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`);
    if (t.length > 10) throw new F(O.INVALID_ARGUMENT, `Invalid Query. '${e.toString()}' filters support a maximum of 10 elements in the value array.`);
}

function Pu(t, e, n) {
    if (!n.isEqual(e)) throw new F(O.INVALID_ARGUMENT, `Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${e.toString()}' and so you must also use '${e.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ function yu(t) {
    /**
 * Returns true if obj is an object and contains at least one of the specified
 * methods.
 */
    return function(t, e) {
        if ("object" != typeof t || null === t) return !1;
        const n = t;
        for (const t of e) if (t in n && "function" == typeof n[t]) return !0;
        return !1;
    }
    /**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
    /**
 * Converts custom model object of type T into DocumentData by applying the
 * converter if it exists.
 *
 * This function is used when converting user objects to DocumentData
 * because we want to provide the user with a more specific error message if
 * their set() or fails due to invalid data originating from a toFirestore()
 * call.
 */ (t, [ "next", "error", "complete" ]);
}

function gu(t, e, n) {
    let s;
    // Cast to `any` in order to satisfy the union type constraint on
    // toFirestore().
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    return s = t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e, 
    s;
}

class Vu extends cu {
    constructor(t) {
        super(), this.firestore = t;
    }
    Uf(t) {
        return new k(t);
    }
    Qf(t) {
        const e = this.Gf(t, this.firestore.I_);
        return new Hc(this.firestore, /* converter= */ null, e);
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Metadata about a snapshot, describing the state of the snapshot.
 */ class pu {
    /** @hideconstructor */
    constructor(t, e) {
        this.hasPendingWrites = t, this.fromCache = e;
    }
    /**
     * Returns true if this `SnapshotMetadata` is equal to the provided one.
     *
     * @param other - The `SnapshotMetadata` to compare against.
     * @returns true if this `SnapshotMetadata` is equal to the provided one.
     */    isEqual(t) {
        return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;
    }
}

/**
 * A `DocumentSnapshot` contains data read from a document in your Firestore
 * database. The data can be extracted with `.data()` or `.get(<field>)` to
 * get a specific field.
 *
 * For a `DocumentSnapshot` that points to a non-existing document, any data
 * access will return 'undefined'. You can use the `exists()` method to
 * explicitly verify a document's existence.
 */ class bu extends au {
    /** @hideconstructor protected */
    constructor(t, e, n, s, i, r) {
        super(t, e, n, s, r), this.zf = t, this.ad = t, this.metadata = i;
    }
    /**
     * Property of the `DocumentSnapshot` that signals whether or not the data
     * exists. True if the document exists.
     */    exists() {
        return super.exists();
    }
    /**
     * Retrieves all fields in the document as an `Object`. Returns `undefined` if
     * the document doesn't exist.
     *
     * By default, `FieldValue.serverTimestamp()` values that have not yet been
     * set to their final value will be returned as `null`. You can override
     * this by passing an options object.
     *
     * @param options - An options object to configure how data is retrieved from
     * the snapshot (for example the desired behavior for server timestamps that
     * have not yet been set to their final value).
     * @returns An `Object` containing all fields in the document or `undefined` if
     * the document doesn't exist.
     */    data(t = {}) {
        if (this.Jf) {
            if (this.v_) {
                // We only want to use the converter and create a new DocumentSnapshot
                // if a converter has been provided.
                const e = new vu(this.zf, this.Hf, this.S_, this.Jf, this.metadata, 
                /* converter= */ null);
                return this.v_.fromFirestore(e, t);
            }
            return this.Hf.$f(this.Jf.vt(), t.serverTimestamps);
        }
    }
    /**
     * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
     * document or field doesn't exist.
     *
     * By default, a `FieldValue.serverTimestamp()` that has not yet been set to
     * its final value will be returned as `null`. You can override this by
     * passing an options object.
     *
     * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
     * field.
     * @param options - An options object to configure how the field is retrieved
     * from the snapshot (for example the desired behavior for server timestamps
     * that have not yet been set to their final value).
     * @returns The data at the specified field location or undefined if no such
     * field exists in the document.
     */
    // We are using `any` here to avoid an explicit cast by our users.
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    get(t, e = {}) {
        if (this.Jf) {
            const n = this.Jf.data().field(hu("DocumentSnapshot.get", t));
            if (null !== n) return this.Hf.$f(n, e.serverTimestamps);
        }
    }
}

/**
 * A `QueryDocumentSnapshot` contains data read from a document in your
 * Firestore database as part of a query. The document is guaranteed to exist
 * and its data can be extracted with `.data()` or `.get(<field>)` to get a
 * specific field.
 *
 * A `QueryDocumentSnapshot` offers the same API surface as a
 * `DocumentSnapshot`. Since query results contain only existing documents, the
 * `exists` property will always be true and `data()` will never return
 * 'undefined'.
 */ class vu extends bu {
    /**
     * Retrieves all fields in the document as an `Object`.
     *
     * By default, `FieldValue.serverTimestamp()` values that have not yet been
     * set to their final value will be returned as `null`. You can override
     * this by passing an options object.
     *
     * @override
     * @param options - An options object to configure how data is retrieved from
     * the snapshot (for example the desired behavior for server timestamps that
     * have not yet been set to their final value).
     * @returns An `Object` containing all fields in the document.
     */
    data(t = {}) {
        return super.data(t);
    }
}

/**
 * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
 * representing the results of a query. The documents can be accessed as an
 * array via the `docs` property or enumerated using the `forEach` method. The
 * number of documents can be determined via the `empty` and `size`
 * properties.
 */ class Su {
    /** @hideconstructor */
    constructor(t, e, n, s) {
        this.zf = t, this.Hf = e, this.ud = s, this.metadata = new pu(s.hasPendingWrites, s.fromCache), 
        this.query = n;
    }
    /** An array of all the documents in the `QuerySnapshot`. */    get docs() {
        const t = [];
        return this.forEach((e => t.push(e))), t;
    }
    /** The number of documents in the `QuerySnapshot`. */    get size() {
        return this.ud.docs.size;
    }
    /** True if there are no documents in the `QuerySnapshot`. */    get empty() {
        return 0 === this.size;
    }
    /**
     * Enumerates all of the documents in the `QuerySnapshot`.
     *
     * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
     * each document in the snapshot.
     * @param thisArg - The `this` binding for the callback.
     */    forEach(t, e) {
        this.ud.docs.forEach((n => {
            t.call(e, new vu(this.zf, this.Hf, n.key, n, new pu(this.ud.Ce.has(n.key), this.ud.fromCache), this.query.v_));
        }));
    }
    /**
     * Returns an array of the documents changes since the last snapshot. If this
     * is the first snapshot, all documents will be in the list as 'added'
     * changes.
     *
     * @param options - `SnapshotListenOptions` that control whether metadata-only
     * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
     * snapshot events.
     */    docChanges(t = {}) {
        const e = !!t.includeMetadataChanges;
        if (e && this.ud.Ne) throw new F(O.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");
        return this.hd && this.ld === e || (this.hd = 
        /** Calculates the array of DocumentChanges for a given ViewSnapshot. */
        function(t, e) {
            if (t.ud.De.nt()) {
                // Special case the first snapshot because index calculation is easy and
                // fast
                let e, n = 0;
                return t.ud.docChanges.map((s => {
                    const i = new vu(t.zf, t.Hf, s.doc.key, s.doc, new pu(t.ud.Ce.has(s.doc.key), t.ud.fromCache), t.query.v_);
                    return e = s.doc, {
                        type: "added",
                        doc: i,
                        oldIndex: -1,
                        newIndex: n++
                    };
                }));
            }
            {
                // A DocumentSet that is updated incrementally as changes are applied to use
                // to lookup the index of a document.
                let n = t.ud.De;
                return t.ud.docChanges.filter((t => e || 3 /* Metadata */ !== t.type)).map((e => {
                    const s = new vu(t.zf, t.Hf, e.doc.key, e.doc, new pu(t.ud.Ce.has(e.doc.key), t.ud.fromCache), t.query.v_);
                    let i = -1, r = -1;
                    return 0 /* Added */ !== e.type && (i = n.indexOf(e.doc.key), n = n.delete(e.doc.key)), 
                    1 /* Removed */ !== e.type && (n = n.add(e.doc), r = n.indexOf(e.doc.key)), {
                        type: Du(e.type),
                        doc: s,
                        oldIndex: i,
                        newIndex: r
                    };
                }));
            }
        }(this, e), this.ld = e), this.hd;
    }
}

function Du(t) {
    switch (t) {
      case 0 /* Added */ :
        return "added";

      case 2 /* Modified */ :
      case 3 /* Metadata */ :
        return "modified";

      case 1 /* Removed */ :
        return "removed";

      default:
        return V();
    }
}

// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot
// metadata
/**
 * Returns true if the provided snapshots are equal.
 *
 * @param left - A snapshot to compare.
 * @param right - A snapshot to compare.
 * @returns true if the snapshots are equal.
 */ function Cu(t, e) {
    return t instanceof bu && e instanceof bu ? t.zf === e.zf && t.S_.isEqual(e.S_) && (null === t.Jf ? null === e.Jf : t.Jf.isEqual(e.Jf)) && t.v_ === e.v_ : t instanceof Su && e instanceof Su && (t.zf === e.zf && na(t.query, e.query) && t.metadata.isEqual(e.metadata) && t.ud.isEqual(e.ud));
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Reads the document referred to by this `DocumentReference`.
 *
 * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting
 * for data from the server, but it may return cached data or fail if you are
 * offline and the server cannot be reached. To specify this behavior, invoke
 * {@link getDocFromCache} or {@link getDocFromServer}.
 *
 * @param reference - The reference of the document to fetch.
 * @returns A Promise resolved with a `DocumentSnapshot` containing the
 * current document contents.
 */ class xu extends cu {
    constructor(t) {
        super(), this.firestore = t;
    }
    Uf(t) {
        return new k(t);
    }
    Qf(t) {
        const e = this.Gf(t, this.firestore.I_);
        return new Hc(this.firestore, /* converter= */ null, e);
    }
}

/**
 * Reads the document referred to by this `DocumentReference` from cache.
 * Returns an error if the document is not currently cached.
 *
 * @returns A Promise resolved with a `DocumentSnapshot` containing the
 * current document contents.
 */ function Nu(t, e, n, ...s) {
    t = Kc(t, Hc);
    const i = Kc(t.firestore, tu), r = ha(i);
    let o;
    // For Compat types, we have to "extract" the underlying types before
    // performing validation.
    e instanceof M && (e = e._), o = "string" == typeof e || e instanceof kc ? ma(r, "updateDoc", t.S_, e, n, s) : Ia(r, "updateDoc", t.S_, e);
    return Fu(i, [ o.O_(t.S_, Be.exists(!0)) ]);
}

/**
 * Deletes the document referred to by the specified `DocumentReference`.
 *
 * @param reference - A reference to the document to delete.
 * @returns A Promise resolved once the document has been successfully
 * deleted from the backend (note that it won't resolve while you're offline).
 */ function Ou(t, ...e) {
    var n, s, i;
    t instanceof M && (t = t._);
    let r = {
        includeMetadataChanges: !1
    }, o = 0;
    "object" != typeof e[o] || yu(e[o]) || (r = e[o], o++);
    const c = {
        includeMetadataChanges: r.includeMetadataChanges
    };
    if (yu(e[o])) {
        const t = e[o];
        e[o] = null === (n = t.next) || void 0 === n ? void 0 : n.bind(t), e[o + 1] = null === (s = t.error) || void 0 === s ? void 0 : s.bind(t), 
        e[o + 2] = null === (i = t.complete) || void 0 === i ? void 0 : i.bind(t);
    }
    let a, u, h;
    if (t instanceof Hc) u = Kc(t.firestore, tu), h = oe(t.S_.path), a = {
        next: n => {
            e[o] && e[o](ku(u, t, n));
        },
        error: e[o + 1],
        complete: e[o + 2]
    }; else {
        const n = Kc(t, Jc);
        u = Kc(n.firestore, tu), h = n.C_;
        const s = new xu(u);
        a = {
            next: t => {
                e[o] && e[o](new Su(u, s, n, t));
            },
            error: e[o + 1],
            complete: e[o + 2]
        }, lu(t.C_);
    }
    return function(t, e, n, s) {
        const i = new Oc(s), r = new Bo(e, i, n);
        return t.fs.ys((async () => Fo(await qa(t), r))), () => {
            i.r_(), t.fs.ys((async () => ko(await qa(t), r)));
        };
    }(eu(u), h, c, a);
}

/** Locally writes `mutations` on the async queue. */
function Fu(t, e) {
    return function(t, e) {
        const n = new ms;
        return t.fs.ys((async () => tc(await Ba(t), e, n))), n.promise;
    }(eu(t), e);
}

/**
 * Converts a ViewSnapshot that contains the single document specified by `ref`
 * to a DocumentSnapshot.
 */ function ku(t, e, n) {
    const s = n.docs.get(e.S_), i = new xu(t);
    return new bu(t, i, e.S_, s, new pu(n.hasPendingWrites, n.fromCache), e.v_);
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A write batch, used to perform multiple writes as a single atomic unit.
 *
 * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
 * provides methods for adding writes to the write batch. None of the writes
 * will be committed (or visible locally) until {@link WriteBatch#commit} is
 * called.
 */ class Mu {
    /** @hideconstructor */
    constructor(t, e) {
        this.zf = t, this._d = e, this.fd = [], this.dd = !1, this.wd = ha(t);
    }
    set(t, e, n) {
        this.Ed();
        const s = Lu(t, this.zf), i = gu(s.v_, e, n), r = la(this.wd, "WriteBatch.set", s.S_, i, null !== s.v_, n);
        return this.fd.push(r.O_(s.S_, Be.jt())), this;
    }
    update(t, e, n, ...s) {
        this.Ed();
        const i = Lu(t, this.zf);
        // For Compat types, we have to "extract" the underlying types before
        // performing validation.
                let r;
        return e instanceof M && (e = e._), r = "string" == typeof e || e instanceof kc ? ma(this.wd, "WriteBatch.update", i.S_, e, n, s) : Ia(this.wd, "WriteBatch.update", i.S_, e), 
        this.fd.push(r.O_(i.S_, Be.exists(!0))), this;
    }
    /**
     * Deletes the document referred to by the provided {@link DocumentReference}.
     *
     * @param documentRef - A reference to the document to be deleted.
     * @returns This `WriteBatch` instance. Used for chaining method calls.
     */    delete(t) {
        this.Ed();
        const e = Lu(t, this.zf);
        return this.fd = this.fd.concat(new tn(e.S_, Be.jt())), this;
    }
    /**
     * Commits all of the writes in this write batch as a single atomic unit.
     *
     * The result of these writes will only be reflected in document reads that
     * occur after the returned Promise resolves. If the client is offline, the
     * write fails. If you would like to see local modifications or buffer writes
     * until the client is online, use the full Firestore SDK.
     *
     * @returns A Promise resolved once all of the writes in the batch have been
     * successfully written to the backend as an atomic unit (note that it won't
     * resolve while you're offline).
     */    commit() {
        return this.Ed(), this.dd = !0, this.fd.length > 0 ? this._d(this.fd) : Promise.resolve();
    }
    Ed() {
        if (this.dd) throw new F(O.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called.");
    }
}

function Lu(t, e) {
    if (t instanceof M && (t = t._), t.firestore !== e) throw new F(O.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance.");
    return t;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the
// legacy SDK.
/**
 * A reference to a transaction.
 *
 * The `Transaction` object passed to a transaction's `updateFunction` provides
 * the methods to read and write data within the transaction context. See
 * {@link runTransaction}.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A reference to a transaction.
 *
 * The `Transaction` object passed to a transaction's `updateFunction` provides
 * the methods to read and write data within the transaction context. See
 * {@link runTransaction}.
 */
class $u extends class {
    /** @hideconstructor */
    constructor(t, e) {
        this.zf = t, this.Td = e, this.wd = ha(t);
    }
    /**
     * Reads the document referenced by the provided {@link DocumentReference}.
     *
     * @param documentRef - A reference to the document to be read.
     * @returns A `DocumentSnapshot` with the read data.
     */    get(t) {
        const e = Lu(t, this.zf), n = new Vu(this.zf);
        return this.Td.ef([ e.S_ ]).then((t => {
            if (!t || 1 !== t.length) return V();
            const s = t[0];
            if (s instanceof Ot) return new au(this.zf, n, e.S_, null, e.v_);
            if (s instanceof Nt) return new au(this.zf, n, s.key, s, e.v_);
            throw V();
        }));
    }
    set(t, e, n) {
        const s = Lu(t, this.zf), i = gu(s.v_, e, n), r = la(this.wd, "Transaction.set", s.S_, i, null !== s.v_, n);
        return this.Td.set(s.S_, r), this;
    }
    update(t, e, n, ...s) {
        const i = Lu(t, this.zf);
        // For Compat types, we have to "extract" the underlying types before
        // performing validation.
                let r;
        return e instanceof M && (e = e._), r = "string" == typeof e || e instanceof kc ? ma(this.wd, "Transaction.update", i.S_, e, n, s) : Ia(this.wd, "Transaction.update", i.S_, e), 
        this.Td.update(i.S_, r), this;
    }
    /**
     * Deletes the document referred to by the provided {@link DocumentReference}.
     *
     * @param documentRef - A reference to the document to be deleted.
     * @returns This `Transaction` instance. Used for chaining method calls.
     */    delete(t) {
        const e = Lu(t, this.zf);
        return this.Td.delete(e.S_), this;
    }
} {
    // This class implements the same logic as the Transaction API in the Lite SDK
    // but is subclassed in order to return its own DocumentSnapshot types.
    /** @hideconstructor */
    constructor(t, e) {
        super(t, e), this.zf = t;
    }
    /**
     * Reads the document referenced by the provided {@link DocumentReference}.
     *
     * @param documentRef - A reference to the document to be read.
     * @returns A `DocumentSnapshot` with the read data.
     */    get(t) {
        const e = Lu(t, this.zf), n = new xu(this.zf);
        return super.get(t).then((t => new bu(this.zf, n, e.S_, t.Jf, new pu(
        /* hasPendingWrites= */ !1, 
        /* fromCache= */ !1), e.v_)));
    }
}

/**
 * Executes the given `updateFunction` and then attempts to commit the changes
 * applied within the transaction. If any document read within the transaction
 * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
 * commit after 5 attempts, the transaction fails.
 *
 * The maximum number of writes allowed in a single transaction is 500.
 *
 * @param firestore - A reference to the Firestore database to run this
 * transaction against.
 * @param updateFunction - The function to execute within the transaction
 * context.
 * @returns If the transaction completed successfully or was explicitly aborted
 * (the `updateFunction` returned a failed promise), the promise returned by the
 * `updateFunction `is returned here. Otherwise, if the transaction failed, a
 * rejected promise with the corresponding failure error is returned.
 */
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const Bu = "You are using the memory-only build of Firestore. Persistence support is only available via the @firebase/firestore bundle or the firebase-firestore.js build.";

/**
 * The persistence provider included with the memory-only SDK. This provider
 * errors for all attempts to access persistence.
 */ class qu {
    enableIndexedDbPersistence(t, e) {
        throw new F(O.FAILED_PRECONDITION, Bu);
    }
    enableMultiTabIndexedDbPersistence(t) {
        throw new F(O.FAILED_PRECONDITION, Bu);
    }
    clearIndexedDbPersistence(t) {
        throw new F(O.FAILED_PRECONDITION, Bu);
    }
}

/**
 * The persistence provider included with the full Firestore SDK.
 */ class Uu {
    enableIndexedDbPersistence(t, e) {
        return function(t, e) {
            ou(t = Kc(t, tu));
            const n = eu(t), s = t.p_(), i = new xc;
            return su(n, i, new Dc(i, s.cacheSizeBytes, null == e ? void 0 : e.forceOwnership));
        }
        /**
 * Attempts to enable multi-tab persistent storage, if possible. If enabled
 * across all tabs, all operations share access to local persistence, including
 * shared execution of queries and latency-compensated local document updates
 * across all connected instances.
 *
 * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise
 * it returns. Note that even after this failure, the `Firestore` instance will
 * remain usable, however offline persistence will be disabled.
 *
 * There are several reasons why this can fail, which can be identified by
 * the `code` on the error.
 *
 *   * failed-precondition: The app is already open in another browser tab and
 *     multi-tab is not enabled.
 *   * unimplemented: The browser is incompatible with the offline
 *     persistence implementation.
 *
 * @param firestore - The `Firestore` instance to enable persistence for.
 * @returns A promise that represents successfully enabling persistent
 * storage.
 */ (t._, {
            forceOwnership: e
        });
    }
    enableMultiTabIndexedDbPersistence(t) {
        return function(t) {
            ou(t = Kc(t, tu));
            const e = eu(t), n = t.p_(), s = new xc;
            return su(e, s, new Cc(s, n.cacheSizeBytes));
        }(t._);
    }
    clearIndexedDbPersistence(t) {
        return iu(t._);
    }
}

/**
 * Compat class for Firestore. Exposes Firestore Legacy API, but delegates
 * to the functional API of firestore-exp.
 */ class Qu extends M {
    constructor(t, e, n) {
        super(e), this.Id = n, this.INTERNAL = {
            delete: () => this.terminate()
        }, t instanceof q || (this.md = t);
    }
    get I_() {
        return this._.I_;
    }
    settings(t) {
        t.merge && 
        // Remove the property from the settings once the merge is completed
        delete (t = Object.assign(Object.assign({}, this._.V_()), t)).merge, this._.g_(t);
    }
    useEmulator(t, e) {
        !function(t, e, n) {
            const s = (t = Kc(t, zc)).V_();
            "firestore.googleapis.com" !== s.host && s.host !== e && y("Host has been set in both settings() and useEmulator(), emulator host will be used"), 
            t.g_(Object.assign(Object.assign({}, s), {
                host: `${e}:${n}`,
                ssl: !1
            }));
        }(this._, t, e);
    }
    enableNetwork() {
        return Ua(eu(Kc(this._, tu)));
    }
    disableNetwork() {
        return Qa(eu(Kc(this._, tu)));
    }
    enablePersistence(t) {
        let e = !1, n = !1;
        return t && (e = !!t.synchronizeTabs, n = !!t.experimentalForceOwningTab, Bc("synchronizeTabs", e, "experimentalForceOwningTab", n)), 
        e ? this.Id.enableMultiTabIndexedDbPersistence(this) : this.Id.enableIndexedDbPersistence(this, n);
    }
    clearPersistence() {
        return this.Id.clearIndexedDbPersistence(this);
    }
    terminate() {
        return this.app._removeServiceInstance("firestore"), this.app._removeServiceInstance("firestore-exp"), 
        this._._delete();
    }
    waitForPendingWrites() {
        return ru(this._);
    }
    onSnapshotsInSync(t) {
        return function(t, e) {
            return za(eu(t = Kc(t, tu)), yu(e) ? e : {
                next: e
            });
        }(this._, t);
    }
    get app() {
        if (!this.md) throw new F(O.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
        return this.md;
    }
    collection(t) {
        try {
            return new sh(this, Xc(this._, t));
        } catch (t) {
            throw Hu(t, "collection()", "Firestore.collection()");
        }
    }
    doc(t) {
        try {
            return new zu(this, ta(this._, t));
        } catch (t) {
            throw Hu(t, "doc()", "Firestore.doc()");
        }
    }
    collectionGroup(t) {
        try {
            return new th(this, Zc(this._, t));
        } catch (t) {
            throw Hu(t, "collectionGroup()", "Firestore.collectionGroup()");
        }
    }
    runTransaction(t) {
        return function(t, e) {
            return Ha(eu(t), (n => e(new $u(t, n))));
        }(this._, (e => t(new Wu(this, e))));
    }
    batch() {
        return eu(this._), new Gu(new Mu(this._, (t => Fu(this._, t))));
    }
    loadBundle(t) {
        throw new F(O.FAILED_PRECONDITION, '"loadBundle()" does not exist, have you imported "firebase/firestore/bundle"?');
    }
    namedQuery(t) {
        throw new F(O.FAILED_PRECONDITION, '"namedQuery()" does not exist, have you imported "firebase/firestore/bundle"?');
    }
}

class Ku extends cu {
    constructor(t) {
        super(), this.firestore = t;
    }
    Uf(t) {
        return new $(new k(t));
    }
    Qf(t) {
        const e = this.Gf(t, this.firestore.I_);
        return zu.Ad(e, this.firestore, /* converter= */ null);
    }
}

function ju(t) {
    var e;
    e = t, m.setLogLevel(e);
}

/**
 * A reference to a transaction.
 */ class Wu extends M {
    constructor(t, e) {
        super(e), this.zf = t, this.Hf = new Ku(t);
    }
    get(t) {
        const e = ih(t);
        return this._.get(e).then((t => new Xu(this.zf, new bu(this.zf._, this.Hf, t.S_, t.Jf, t.metadata, e.v_))));
    }
    set(t, e, n) {
        const s = ih(t);
        return n ? ($c("Transaction.set", n), this._.set(s, e, n)) : this._.set(s, e), this;
    }
    update(t, e, n, ...s) {
        const i = ih(t);
        return 2 === arguments.length ? this._.update(i, e) : this._.update(i, e, n, ...s), 
        this;
    }
    delete(t) {
        const e = ih(t);
        return this._.delete(e), this;
    }
}

class Gu extends M {
    set(t, e, n) {
        const s = ih(t);
        return n ? ($c("WriteBatch.set", n), this._.set(s, e, n)) : this._.set(s, e), this;
    }
    update(t, e, n, ...s) {
        const i = ih(t);
        return 2 === arguments.length ? this._.update(i, e) : this._.update(i, e, n, ...s), 
        this;
    }
    delete(t) {
        const e = ih(t);
        return this._.delete(e), this;
    }
    commit() {
        return this._.commit();
    }
}

/**
 * A reference to a particular document in a collection in the database.
 */ class zu extends M {
    constructor(t, e) {
        super(e), this.firestore = t, this.Hf = new Ku(t);
    }
    static Rd(t, e, n) {
        if (t.length % 2 != 0) throw new F(O.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${t.ot()} has ${t.length}`);
        return new zu(e, new Hc(e._, n, new et(t)));
    }
    static Ad(t, e, n) {
        return new zu(e, new Hc(e._, n, t));
    }
    get id() {
        return this._.id;
    }
    get parent() {
        return new sh(this.firestore, this._.parent);
    }
    get path() {
        return this._.path;
    }
    collection(t) {
        try {
            return new sh(this.firestore, Xc(this._, t));
        } catch (t) {
            throw Hu(t, "collection()", "DocumentReference.collection()");
        }
    }
    isEqual(t) {
        return t instanceof M && (t = t._), t instanceof Hc && ea(this._, t);
    }
    set(t, e) {
        e = $c("DocumentReference.set", e);
        try {
            return function(t, e, n) {
                t = Kc(t, Hc);
                const s = Kc(t.firestore, tu), i = gu(t.v_, e, n);
                return Fu(s, [ la(ha(s), "setDoc", t.S_, i, null !== t.v_, n).O_(t.S_, Be.jt()) ]);
            }(this._, t, e);
        } catch (t) {
            throw Hu(t, "setDoc()", "DocumentReference.set()");
        }
    }
    update(t, e, ...n) {
        try {
            return 1 === arguments.length ? Nu(this._, t) : Nu(this._, t, e, ...n);
        } catch (t) {
            throw Hu(t, "updateDoc()", "DocumentReference.update()");
        }
    }
    delete() {
        return Fu(Kc((t = this._).firestore, tu), [ new tn(t.S_, Be.jt()) ]);
        var t;
        /**
 * Add a new document to specified `CollectionReference` with the given data,
 * assigning it a document ID automatically.
 *
 * @param reference - A reference to the collection to add this document to.
 * @param data - An Object containing the data for the new document.
 * @returns A Promise resolved with a `DocumentReference` pointing to the
 * newly created document after it has been written to the backend (Note that it
 * won't resolve while you're offline).
 */    }
    onSnapshot(...t) {
        const e = Ju(t), n = Yu(t, (t => new Xu(this.firestore, new bu(this.firestore._, this.Hf, t.S_, t.Jf, t.metadata, this._.v_))));
        return Ou(this._, e, n);
    }
    get(t) {
        let e;
        return e = "cache" === (null == t ? void 0 : t.source) ? function(t) {
            t = Kc(t, Hc);
            const e = Kc(t.firestore, tu), n = eu(e), s = new xu(e);
            return Ka(n, t.S_).then((n => new bu(e, s, t.S_, n, new pu(n instanceof Nt && n.bt, 
            /* fromCache= */ !0), t.v_)));
        }
        /**
 * Reads the document referred to by this `DocumentReference` from the server.
 * Returns an error if the network is not available.
 *
 * @returns A Promise resolved with a `DocumentSnapshot` containing the
 * current document contents.
 */ (this._) : "server" === (null == t ? void 0 : t.source) ? function(t) {
            t = Kc(t, Hc);
            const e = Kc(t.firestore, tu);
            return ja(eu(e), t.S_, {
                source: "server"
            }).then((n => ku(e, t, n)));
        }
        /**
 * Executes the query and returns the results as a `QuerySnapshot`.
 *
 * Note: `getDocs()` attempts to provide up-to-date data when possible by
 * waiting for data from the server, but it may return cached data or fail if
 * you are offline and the server cannot be reached. To specify this behavior,
 * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.
 *
 * @returns A Promise that will be resolved with the results of the query.
 */ (this._) : function(t) {
            t = Kc(t, Hc);
            const e = Kc(t.firestore, tu);
            return ja(eu(e), t.S_).then((n => ku(e, t, n)));
        }(this._), e.then((t => new Xu(this.firestore, new bu(this.firestore._, this.Hf, t.S_, t.Jf, t.metadata, this._.v_))));
    }
    withConverter(t) {
        return new zu(this.firestore, this._.withConverter(t));
    }
}

/**
 * Replaces the function name in an error thrown by the firestore-exp API
 * with the function names used in the classic API.
 */ function Hu(t, e, n) {
    return t.message = t.message.replace(e, n), t;
}

/**
 * Iterates the list of arguments from an `onSnapshot` call and returns the
 * first argument that may be an `SnapshotListenOptions` object. Returns an
 * empty object if none is found.
 */ function Ju(t) {
    for (const e of t) if ("object" == typeof e && !yu(e)) return e;
    return {};
}

/**
 * Creates an observer that can be passed to the firestore-exp SDK. The
 * observer converts all observed values into the format expected by the classic
 * SDK.
 *
 * @param args - The list of arguments from an `onSnapshot` call.
 * @param wrapper - The function that converts the firestore-exp type into the
 * type used by this shim.
 */ function Yu(t, e) {
    var n, s;
    let i;
    return i = yu(t[0]) ? t[0] : yu(t[1]) ? t[1] : "function" == typeof t[0] ? {
        next: t[0],
        error: t[1],
        complete: t[2]
    } : {
        next: t[1],
        error: t[2],
        complete: t[3]
    }, {
        next: t => {
            i.next && i.next(e(t));
        },
        error: null === (n = i.error) || void 0 === n ? void 0 : n.bind(i),
        complete: null === (s = i.complete) || void 0 === s ? void 0 : s.bind(i)
    };
}

class Xu extends M {
    constructor(t, e) {
        super(e), this.zf = t;
    }
    get ref() {
        return new zu(this.zf, this._.ref);
    }
    get id() {
        return this._.id;
    }
    get metadata() {
        return this._.metadata;
    }
    get exists() {
        return this._.exists();
    }
    data(t) {
        return this._.data(t);
    }
    get(t, e) {
        return this._.get(t, e);
    }
    isEqual(t) {
        return Cu(this._, t._);
    }
}

class Zu extends Xu {
    data(t) {
        return this._.data(t);
    }
}

class th extends M {
    constructor(t, e) {
        super(e), this.firestore = t, this.Hf = new Ku(t);
    }
    where(t, e, n) {
        try {
            // The "as string" cast is a little bit of a hack. `where` accepts the
            // FieldPath Compat type as input, but is not typed as such in order to
            // not expose this via our public typings file.
            return new th(this.firestore, fu(this._, function(t, e, n) {
                const s = e, i = hu("where", t);
                return new du(i, s, n);
            }(t, e, n)));
        } catch (t) {
            throw Hu(t, /(orderBy|where)\(\)/, "Query.$1()");
        }
    }
    orderBy(t, e) {
        try {
            // The "as string" cast is a little bit of a hack. `orderBy` accepts the
            // FieldPath Compat type as input, but is not typed as such in order to
            // not expose this via our public typings file.
            return new th(this.firestore, fu(this._, function(t, e = "asc") {
                const n = e, s = hu("orderBy", t);
                return new wu(s, n);
            }(t, e)));
        } catch (t) {
            throw Hu(t, /(orderBy|where)\(\)/, "Query.$1()");
        }
    }
    limit(t) {
        try {
            return new th(this.firestore, fu(this._, function(t) {
                return jc("limit", t), new Eu("limit", t, "F" /* First */);
            }
            /**
 * Creates a `QueryConstraint` that only returns the last matching documents.
 *
 * You must specify at least one `orderBy` clause for `limitToLast` queries,
 * otherwise an exception will be thrown during execution.
 *
 * @param limit - The maximum number of items to return.
 * @returns The created `Query`.
 */ (t)));
        } catch (t) {
            throw Hu(t, "limit()", "Query.limit()");
        }
    }
    limitToLast(t) {
        try {
            return new th(this.firestore, fu(this._, function(t) {
                return jc("limitToLast", t), new Eu("limitToLast", t, "L" /* Last */);
            }(t)));
        } catch (t) {
            throw Hu(t, "limitToLast()", "Query.limitToLast()");
        }
    }
    startAt(...t) {
        try {
            return new th(this.firestore, fu(this._, function(...t) {
                return new Tu("startAt", t, /*before=*/ !0);
            }(...t)));
        } catch (t) {
            throw Hu(t, "startAt()", "Query.startAt()");
        }
    }
    startAfter(...t) {
        try {
            return new th(this.firestore, fu(this._, function(...t) {
                return new Tu("startAfter", t, 
                /*before=*/ !1);
            }(...t)));
        } catch (t) {
            throw Hu(t, "startAfter()", "Query.startAfter()");
        }
    }
    endBefore(...t) {
        try {
            return new th(this.firestore, fu(this._, function(...t) {
                return new Iu("endBefore", t, /*before=*/ !0);
            }(...t)));
        } catch (t) {
            throw Hu(t, "endBefore()", "Query.endBefore()");
        }
    }
    endAt(...t) {
        try {
            return new th(this.firestore, fu(this._, function(...t) {
                return new Iu("endAt", t, /*before=*/ !1);
            }(...t)));
        } catch (t) {
            throw Hu(t, "endAt()", "Query.endAt()");
        }
    }
    isEqual(t) {
        return na(this._, t._);
    }
    get(t) {
        let e;
        return e = "cache" === (null == t ? void 0 : t.source) ? 
        /**
 * Executes the query and returns the results as a `QuerySnapshot` from cache.
 * Returns an error if the document is not currently cached.
 *
 * @returns A Promise that will be resolved with the results of the query.
 */
        function(t) {
            t = Kc(t, Jc);
            const e = Kc(t.firestore, tu), n = eu(e), s = new xu(e);
            return Wa(n, t.C_).then((n => new Su(e, s, t, n)));
        }
        /**
 * Executes the query and returns the results as a `QuerySnapshot` from the
 * server. Returns an error if the network is not available.
 *
 * @returns A Promise that will be resolved with the results of the query.
 */ (this._) : "server" === (null == t ? void 0 : t.source) ? function(t) {
            t = Kc(t, Jc);
            const e = Kc(t.firestore, tu), n = eu(e), s = new xu(e);
            return Ga(n, t.C_, {
                source: "server"
            }).then((n => new Su(e, s, t, n)));
        }(this._) : function(t) {
            t = Kc(t, Jc);
            const e = Kc(t.firestore, tu), n = eu(e), s = new xu(e);
            return lu(t.C_), Ga(n, t.C_).then((n => new Su(e, s, t, n)));
        }(this._), e.then((t => new nh(this.firestore, new Su(this.firestore._, this.Hf, this._, t.ud))));
    }
    onSnapshot(...t) {
        const e = Ju(t), n = Yu(t, (t => new nh(this.firestore, new Su(this.firestore._, this.Hf, this._, t.ud))));
        return Ou(this._, e, n);
    }
    withConverter(t) {
        return new th(this.firestore, this._.withConverter(t));
    }
}

class eh extends M {
    constructor(t, e) {
        super(e), this.zf = t;
    }
    get type() {
        return this._.type;
    }
    get doc() {
        return new Zu(this.zf, this._.doc);
    }
    get oldIndex() {
        return this._.oldIndex;
    }
    get newIndex() {
        return this._.newIndex;
    }
}

class nh extends M {
    constructor(t, e) {
        super(e), this.zf = t;
    }
    get query() {
        return new th(this.zf, this._.query);
    }
    get metadata() {
        return this._.metadata;
    }
    get size() {
        return this._.size;
    }
    get empty() {
        return this._.empty;
    }
    get docs() {
        return this._.docs.map((t => new Zu(this.zf, t)));
    }
    docChanges(t) {
        return this._.docChanges(t).map((t => new eh(this.zf, t)));
    }
    forEach(t, e) {
        this._.forEach((n => {
            t.call(e, new Zu(this.zf, n));
        }));
    }
    isEqual(t) {
        return Cu(this._, t._);
    }
}

class sh extends th {
    constructor(t, e) {
        super(t, e), this.firestore = t, this._ = e;
    }
    get id() {
        return this._.id;
    }
    get path() {
        return this._.path;
    }
    get parent() {
        const t = this._.parent;
        return t ? new zu(this.firestore, t) : null;
    }
    doc(t) {
        try {
            return new zu(this.firestore, void 0 === t ? ta(this._) : ta(this._, t));
        } catch (t) {
            throw Hu(t, "doc()", "CollectionReference.doc()");
        }
    }
    add(t) {
        return function(t, e) {
            const n = Kc(t.firestore, tu), s = ta(t), i = gu(t.v_, e);
            return Fu(n, [ la(ha(t.firestore), "addDoc", s.S_, i, null !== t.v_, {}).O_(s.S_, Be.exists(!1)) ]).then((() => s));
        }(this._, t).then((t => new zu(this.firestore, t)));
    }
    isEqual(t) {
        return ea(this._, t._);
    }
    withConverter(t) {
        return new sh(this.firestore, this._.withConverter(t));
    }
}

function ih(t) {
    return t instanceof M && (t = t._), Kc(t, Hc);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// The objects that are a part of this API are exposed to third-parties as
// compiled javascript so we want to flag our private members with a leading
// underscore to discourage their use.
/**
 * A `FieldPath` refers to a field in a document. The path may consist of a
 * single field name (referring to a top-level field in the document), or a list
 * of field names (referring to a nested field in the document).
 */ class rh extends M {
    /**
     * Creates a FieldPath from the provided field names. If more than one field
     * name is provided, the path will point to a nested field in a document.
     *
     * @param fieldNames - A list of field names.
     */
    constructor(...t) {
        super(new kc(...t));
    }
    static documentId() {
        /**
         * Internal Note: The backend doesn't technically support querying by
         * document ID. Instead it queries by the entire document name (full path
         * included), but in the cases we currently support documentId(), the net
         * effect is the same.
         */
        return new rh(tt.lt().ot());
    }
    isEqual(t) {
        return t instanceof M && (t = t._), t instanceof kc && this._.d_.isEqual(t.d_);
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Returns a sentinel for use with {@link updateDoc} or
 * {@link setDoc} with `{merge: true}` to mark a field for deletion.
 */
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class oh extends M {
    static serverTimestamp() {
        const t = new da("serverTimestamp");
        return t._methodName = "FieldValue.serverTimestamp", new oh(t);
    }
    static delete() {
        const t = new _a("deleteField");
        return t._methodName = "FieldValue.delete", new oh(t);
    }
    static arrayUnion(...t) {
        const e = 
        /**
 * Returns a special value that can be used with {@link setDoc} or {@link
 * updateDoc} that tells the server to union the given elements with any array
 * value that already exists on the server. Each specified element that doesn't
 * already exist in the array will be added to the end. If the field being
 * modified is not already an array it will be overwritten with an array
 * containing exactly the specified elements.
 *
 * @param elements - The elements to union into the array.
 * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
 * `updateDoc()`.
 */
        function(...t) {
            // NOTE: We don't actually parse the data until it's used in set() or
            // update() since we'd need the Firestore instance to do this.
            return new wa("arrayUnion", t);
        }
        /**
 * Returns a special value that can be used with {@link (setDoc:1)} or {@link
 * updateDoc} that tells the server to remove the given elements from any
 * array value that already exists on the server. All instances of each element
 * specified will be removed from the array. If the field being modified is not
 * already an array it will be overwritten with an empty array.
 *
 * @param elements - The elements to remove from the array.
 * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
 * `updateDoc()`
 */ (...t);
        return e._methodName = "FieldValue.arrayUnion", new oh(e);
    }
    static arrayRemove(...t) {
        const e = function(...t) {
            // NOTE: We don't actually parse the data until it's used in set() or
            // update() since we'd need the Firestore instance to do this.
            return new Ea("arrayRemove", t);
        }
        /**
 * Returns a special value that can be used with {@link setDoc} or {@link
 * updateDoc} that tells the server to increment the field's current value by
 * the given value.
 *
 * If either the operand or the current field value uses floating point
 * precision, all arithmetic follows IEEE 754 semantics. If both values are
 * integers, values outside of JavaScript's safe number range
 * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
 * precision loss. Furthermore, once processed by the Firestore backend, all
 * integer operations are capped between -2^63 and 2^63-1.
 *
 * If the current field value is not of type `number`, or if the field does not
 * yet exist, the transformation sets the field to the given value.
 *
 * @param n - The value to increment by.
 * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
 * `updateDoc()`
 */ (...t);
        return e._methodName = "FieldValue.arrayRemove", new oh(e);
    }
    static increment(t) {
        const e = function(t) {
            return new Ta("increment", t);
        }(t);
        return e._methodName = "FieldValue.increment", new oh(e);
    }
    isEqual(t) {
        return this._.isEqual(t._);
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class ch {
    constructor() {
        this.Pd = {}, this.yd = new ms, this.gd = {
            taskState: "Running",
            totalBytes: 0,
            totalDocuments: 0,
            bytesLoaded: 0,
            documentsLoaded: 0
        };
    }
    onProgress(t, e, n) {
        this.Pd = {
            next: t,
            error: e,
            complete: n
        };
    }
    catch(t) {
        return this.yd.promise.catch(t);
    }
    then(t, e) {
        return this.yd.promise.then(t, e);
    }
    /**
     * Notifies all observers that bundle loading has completed, with a provided
     * `LoadBundleTaskProgress` object.
     */    Ul(t) {
        this.Ql(t), this.Pd.complete && this.Pd.complete(), this.yd.resolve(t);
    }
    /**
     * Notifies all observers that bundle loading has failed, with a provided
     * `Error` as the reason.
     */    jl(t) {
        this.gd.taskState = "Error", this.Pd.next && this.Pd.next(this.gd), this.Pd.error && this.Pd.error(t), 
        this.yd.reject(t);
    }
    /**
     * Notifies a progress update of loading a bundle.
     * @param progress - The new progress.
     */    Ql(t) {
        this.gd = t, this.Pd.next && this.Pd.next(t);
    }
}

function ah(t, e) {
    const n = new ch;
    return Ja(eu(t._), t.I_, e, n), n;
}

function uh(t, e) {
    return Ya(eu(t._), e).then((e => e ? new th(t, new Jc(t._, null, e.query)) : null));
}

export { $ as Blob, Za as CACHE_SIZE_UNLIMITED, sh as CollectionReference, zu as DocumentReference, Xu as DocumentSnapshot, tu as ExpFirebaseFirestore, rh as FieldPath, oh as FieldValue, Qu as Firestore, sa as GeoPoint, Uu as IndexedDbPersistenceProvider, qu as MemoryPersistenceProvider, th as Query, Zu as QueryDocumentSnapshot, nh as QuerySnapshot, H as Timestamp, Wu as Transaction, Gu as WriteBatch, ah as loadBundle, uh as namedQuery, ju as setLogLevel };
//# sourceMappingURL=prebuilt.rn.js.map
