text: import t from "@firebase/app";
  
  import { Logger as e, LogLevel as s } from "@firebase/logger";
  
  import { getUA as i, isMobileCordova as n, isReactNative as r, isElectron as h, isIE as o, isUWP as a, isBrowserExtension as u } from "@firebase/util";
  
  import { Component as c } from "@firebase/component";
  
  import { XhrIo as _, EventType as l, ErrorCode as d, createWebChannelTransport as f, WebChannel as T } from "@firebase/webchannel-wrapper";
  
  /**
   * @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 semver (www.semver.org) version of the SDK. */ const E = t.SDK_VERSION;
  
  /**
   * @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 I {
      constructor(t) {
          this.uid = t;
      }
      t() {
          return null != this.uid;
      }
      /**
       * Returns a key representing this user, suitable for inclusion in a
       * dictionary.
       */    s() {
          return this.t() ? "uid:" + this.uid : "anonymous-user";
      }
      isEqual(t) {
          return t.uid === this.uid;
      }
  }
  
  /** A user with a null UID. */ I.UNAUTHENTICATED = new I(null), 
  // TODO(mikelehen): Look into getting a proper uid-equivalent for
  // non-FirebaseAuth providers.
  I.i = new I("google-credentials-uid"), I.h = new I("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.
   */
  const w = {
      // 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 class used for Firestore-generated errors. Ideally we should be
   * using FirebaseError, but integrating with it is overly arduous at the moment,
   * so we define our own compatible error class (with a `name` of 'FirebaseError'
   * and compatible `code` and `message` fields.)
   */ class R extends Error {
      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 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 m {
      constructor(t, e) {
          this.user = e, this.type = "OAuth", this.o = {}, 
          // Set the headers using Object Literal notation to avoid minification
          this.o.Authorization = `Bearer ${t}`;
      }
  }
  
  /** A CredentialsProvider that always yields an empty token. */ class A {
      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.u = null;
      }
      getToken() {
          return Promise.resolve(null);
      }
      _() {}
      l(t) {
          this.u = t, 
          // Fire with initial user.
          t(I.UNAUTHENTICATED);
      }
      T() {
          this.u = null;
      }
  }
  
  class P {
      constructor(t) {
          /**
           * The auth token listener registered with FirebaseApp, retained here so we
           * can unregister it.
           */
          this.I = null, 
          /** Tracks the current User. */
          this.currentUser = I.UNAUTHENTICATED, this.R = !1, 
          /**
           * Counter used to detect if the token changed while a getToken request was
           * outstanding.
           */
          this.m = 0, 
          /** The listener registered with setChangeListener(). */
          this.u = null, this.forceRefresh = !1, this.I = () => {
              this.m++, this.currentUser = this.A(), this.R = !0, this.u && this.u(this.currentUser);
          }, this.m = 0, this.auth = t.getImmediate({
              optional: !0
          }), this.auth ? this.auth.addAuthTokenListener(this.I) : (
          // if auth is not available, invoke tokenListener once with null token
          this.I(null), t.get().then(t => {
              this.auth = t, this.I && 
              // tokenListener can be removed by removeChangeListener()
              this.auth.addAuthTokenListener(this.I);
          }, () => {}));
      }
      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.m, 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).
              if (this.m !== t) throw new R(w.ABORTED, "getToken aborted due to token change.");
              return e ? (ve("string" == typeof e.accessToken), new m(e.accessToken, this.currentUser)) : null;
          }) : Promise.resolve(null);
      }
      _() {
          this.forceRefresh = !0;
      }
      l(t) {
          this.u = t, 
          // Fire the initial event
          this.R && t(this.currentUser);
      }
      T() {
          this.auth && this.auth.removeAuthTokenListener(this.I), this.I = null, this.u = 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.
      A() {
          const t = this.auth && this.auth.getUid();
          return ve(null === t || "string" == typeof t), new I(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 V {
      constructor(t, e) {
          this.P = t, this.V = e, this.type = "FirstParty", this.user = I.h;
      }
      get o() {
          const t = {
              "X-Goog-AuthUser": this.V
          }, e = this.P.auth.g([]);
          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.P = t, this.V = e;
      }
      getToken() {
          return Promise.resolve(new V(this.P, this.V));
      }
      l(t) {
          // Fire with initial uid.
          t(I.h);
      }
      T() {}
      _() {}
  }
  
  /**
   * Builds a CredentialsProvider depending on the type of
   * the credentials passed in.
   */ class p {
      constructor(t, e) {
          if (this.seconds = t, this.nanoseconds = e, e < 0) throw new R(w.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
          if (e >= 1e9) throw new R(w.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
          if (t < -62135596800) throw new R(w.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
          // This will break in the year 10,000.
                  if (t >= 253402300800) throw new R(w.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
      }
      static now() {
          return p.fromMillis(Date.now());
      }
      static fromDate(t) {
          return p.fromMillis(t.getTime());
      }
      static fromMillis(t) {
          const e = Math.floor(t / 1e3);
          return new p(e, 1e6 * (t - 1e3 * e));
      }
      toDate() {
          return new Date(this.toMillis());
      }
      toMillis() {
          return 1e3 * this.seconds + this.nanoseconds / 1e6;
      }
      p(t) {
          return this.seconds === t.seconds ? Ce(this.nanoseconds, t.nanoseconds) : Ce(this.seconds, t.seconds);
      }
      isEqual(t) {
          return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;
      }
      toString() {
          return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
      }
      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 y {
      constructor(t) {
          this.timestamp = t;
      }
      static v(t) {
          return new y(t);
      }
      static min() {
          return new y(new p(0, 0));
      }
      S(t) {
          return this.timestamp.p(t.timestamp);
      }
      isEqual(t) {
          return this.timestamp.isEqual(t.timestamp);
      }
      /** Returns a number representation of the version for use in spec tests. */    D() {
          // Convert to microseconds.
          return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
      }
      toString() {
          return "SnapshotVersion(" + this.timestamp.toString() + ")";
      }
      C() {
          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 b {
      constructor(t, e, s) {
          void 0 === e ? e = 0 : e > t.length && be(), void 0 === s ? s = t.length - e : s > t.length - e && be(), 
          this.segments = t, this.offset = e, this.F = s;
      }
      get length() {
          return this.F;
      }
      isEqual(t) {
          return 0 === b.N(this, t);
      }
      child(t) {
          const e = this.segments.slice(this.offset, this.limit());
          return t instanceof b ? t.forEach(t => {
              e.push(t);
          }) : e.push(t), this.$(e);
      }
      /** The index of one past the last segment of the path. */    limit() {
          return this.offset + this.length;
      }
      k(t) {
          return t = void 0 === t ? 1 : t, this.$(this.segments, this.offset + t, this.length - t);
      }
      M() {
          return this.$(this.segments, this.offset, this.length - 1);
      }
      L() {
          return this.segments[this.offset];
      }
      O() {
          return this.get(this.length - 1);
      }
      get(t) {
          return this.segments[this.offset + t];
      }
      B() {
          return 0 === this.length;
      }
      q(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;
      }
      U(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, s = this.limit(); e < s; e++) t(this.segments[e]);
      }
      W() {
          return this.segments.slice(this.offset, this.limit());
      }
      static N(t, e) {
          const s = Math.min(t.length, e.length);
          for (let i = 0; i < s; i++) {
              const s = t.get(i), n = e.get(i);
              if (s < n) return -1;
              if (s > n) 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 v extends b {
      $(t, e, s) {
          return new v(t, e, s);
      }
      j() {
          // 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.W().join("/");
      }
      toString() {
          return this.j();
      }
      /**
       * Creates a resource path from the given slash-delimited string.
       */    static K(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).
          if (t.indexOf("//") >= 0) throw new R(w.INVALID_ARGUMENT, `Invalid path (${t}). Paths must not contain // in them.`);
          // We may still have an empty segment at the beginning or end if they had a
          // leading or trailing slash (which we allow).
                  const e = t.split("/").filter(t => t.length > 0);
          return new v(e);
      }
  }
  
  v.G = new v([]);
  
  const S = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
  
  /** A dot-separated path for navigating sub-objects within a document. */ class D extends b {
      $(t, e, s) {
          return new D(t, e, s);
      }
      /**
       * Returns true if the string could be used as a segment in a field path
       * without escaping.
       */    static H(t) {
          return S.test(t);
      }
      j() {
          return this.W().map(t => (t = t.replace("\\", "\\\\").replace("`", "\\`"), D.H(t) || (t = "`" + t + "`"), 
          t)).join(".");
      }
      toString() {
          return this.j();
      }
      /**
       * Returns true if this field references the key of a document.
       */    Y() {
          return 1 === this.length && "__name__" === this.get(0);
      }
      /**
       * The field designating the key of a document.
       */    static J() {
          return new D([ "__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 X(t) {
          const e = [];
          let s = "", i = 0;
          const n = () => {
              if (0 === s.length) throw new R(w.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, begin ` + "with '.', end with '.', or contain '..'");
              e.push(s), s = "";
          };
          let r = !1;
          for (;i < t.length; ) {
              const e = t[i];
              if ("\\" === e) {
                  if (i + 1 === t.length) throw new R(w.INVALID_ARGUMENT, "Path has trailing escape character: " + t);
                  const e = t[i + 1];
                  if ("\\" !== e && "." !== e && "`" !== e) throw new R(w.INVALID_ARGUMENT, "Path has invalid escape sequence: " + t);
                  s += e, i += 2;
              } else "`" === e ? (r = !r, i++) : "." !== e || r ? (s += e, i++) : (n(), i++);
          }
          if (n(), r) throw new R(w.INVALID_ARGUMENT, "Unterminated ` in path: " + t);
          return new D(e);
      }
  }
  
  D.G = new D([]);
  
  /**
   * @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 C {
      constructor(t) {
          this.path = t;
      }
      static Z(t) {
          return new C(v.K(t).k(5));
      }
      /** Returns true if the document is in the specified collectionId. */    tt(t) {
          return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;
      }
      isEqual(t) {
          return null !== t && 0 === v.N(this.path, t.path);
      }
      toString() {
          return this.path.toString();
      }
      static N(t, e) {
          return v.N(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
       * @return A new instance of DocumentKey
       */    static st(t) {
          return new C(new v(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 F(t) {
      let e = 0;
      for (const s in t) Object.prototype.hasOwnProperty.call(t, s) && e++;
      return e;
  }
  
  function N(t, e) {
      for (const s in t) Object.prototype.hasOwnProperty.call(t, s) && e(s, t[s]);
  }
  
  function $(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.
   */
  /**
   * 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.
   */ C.EMPTY = new C(new v([]));
  
  class k {
      constructor(t) {
          this.it = t;
      }
      static fromBase64String(t) {
          const e = me.nt().atob(t);
          return new k(e);
      }
      static fromUint8Array(t) {
          const e = 
          /**
   * Helper function to convert an Uint8array to a binary string.
   */
          function(t) {
              let e = "";
              for (let s = 0; s < t.length; ++s) e += String.fromCharCode(t[s]);
              return e;
          }
          /**
   * Helper function to convert a binary string to an Uint8Array.
   */ (t);
          return new k(e);
      }
      toBase64() {
          return me.nt().btoa(this.it);
      }
      toUint8Array() {
          return function(t) {
              const e = new Uint8Array(t.length);
              for (let s = 0; s < t.length; s++) e[s] = t.charCodeAt(s);
              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.
   */
          /**
   * Returns whether a variable is either undefined or null.
   */ (this.it);
      }
      rt() {
          return 2 * this.it.length;
      }
      S(t) {
          return Ce(this.it, t.it);
      }
      isEqual(t) {
          return this.it === t.it;
      }
  }
  
  function M(t) {
      return null == t;
  }
  
  /** Returns whether the value represents -0. */ function L(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 O(t) {
      return "number" == typeof t && Number.isInteger(t) && !L(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.
   */
  /**
   * 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
   *   TransformMutation (see TransformMutation.applyTo()). 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.
   */ k.ht = new k("");
  
  function x(t) {
      var e, s;
      return "server_timestamp" === (null === (s = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === s ? void 0 : s.stringValue);
  }
  
  /**
   * Creates a new ServerTimestamp proto value (using the internal format).
   */
  /**
   * Returns the local time at which this timestamp was first set.
   */
  function B(t) {
      const e = H(t.mapValue.fields.__local_write_time__.timestampValue);
      return new p(e.seconds, e.nanos);
  }
  
  /**
   * @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 q = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
  
  /** Extracts the backend's type order for the provided value. */ function U(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 ? x(t) ? 4 /* ServerTimestampValue */ : 10 /* ObjectValue */ : be();
  }
  
  /** Tests `left` and `right` for equality based on the backend semantics. */ function Q(t, e) {
      const s = U(t);
      if (s !== U(e)) return !1;
      switch (s) {
        case 0 /* NullValue */ :
          return !0;
  
        case 1 /* BooleanValue */ :
          return t.booleanValue === e.booleanValue;
  
        case 4 /* ServerTimestampValue */ :
          return B(t).isEqual(B(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 s = H(t.timestampValue), i = H(e.timestampValue);
              return s.seconds === i.seconds && s.nanos === i.nanos;
          }(t, e);
  
        case 5 /* StringValue */ :
          return t.stringValue === e.stringValue;
  
        case 6 /* BlobValue */ :
          return function(t, e) {
              return J(t.bytesValue).isEqual(J(e.bytesValue));
          }(t, e);
  
        case 7 /* RefValue */ :
          return t.referenceValue === e.referenceValue;
  
        case 8 /* GeoPointValue */ :
          return function(t, e) {
              return Y(t.geoPointValue.latitude) === Y(e.geoPointValue.latitude) && Y(t.geoPointValue.longitude) === Y(e.geoPointValue.longitude);
          }(t, e);
  
        case 2 /* NumberValue */ :
          return function(t, e) {
              if ("integerValue" in t && "integerValue" in e) return Y(t.integerValue) === Y(e.integerValue);
              if ("doubleValue" in t && "doubleValue" in e) {
                  const s = Y(t.doubleValue), i = Y(e.doubleValue);
                  return s === i ? L(s) === L(i) : isNaN(s) && isNaN(i);
              }
              return !1;
          }(t, e);
  
        case 9 /* ArrayValue */ :
          return Fe(t.arrayValue.values || [], e.arrayValue.values || [], Q);
  
        case 10 /* ObjectValue */ :
          return function(t, e) {
              const s = t.mapValue.fields || {}, i = e.mapValue.fields || {};
              if (F(s) !== F(i)) return !1;
              for (const t in s) if (s.hasOwnProperty(t) && (void 0 === i[t] || !Q(s[t], i[t]))) return !1;
              return !0;
          }
          /** Returns true if the ArrayValue contains the specified element. */ (t, e);
  
        default:
          return be();
      }
  }
  
  function W(t, e) {
      return void 0 !== (t.values || []).find(t => Q(t, e));
  }
  
  function j(t, e) {
      const s = U(t), i = U(e);
      if (s !== i) return Ce(s, i);
      switch (s) {
        case 0 /* NullValue */ :
          return 0;
  
        case 1 /* BooleanValue */ :
          return Ce(t.booleanValue, e.booleanValue);
  
        case 2 /* NumberValue */ :
          return function(t, e) {
              const s = Y(t.integerValue || t.doubleValue), i = Y(e.integerValue || e.doubleValue);
              return s < i ? -1 : s > i ? 1 : s === i ? 0 : 
              // one or both are NaN.
              isNaN(s) ? isNaN(i) ? 0 : -1 : 1;
          }(t, e);
  
        case 3 /* TimestampValue */ :
          return K(t.timestampValue, e.timestampValue);
  
        case 4 /* ServerTimestampValue */ :
          return K(B(t), B(e));
  
        case 5 /* StringValue */ :
          return Ce(t.stringValue, e.stringValue);
  
        case 6 /* BlobValue */ :
          return function(t, e) {
              const s = J(t), i = J(e);
              return s.S(i);
          }(t.bytesValue, e.bytesValue);
  
        case 7 /* RefValue */ :
          return function(t, e) {
              const s = t.split("/"), i = e.split("/");
              for (let t = 0; t < s.length && t < i.length; t++) {
                  const e = Ce(s[t], i[t]);
                  if (0 !== e) return e;
              }
              return Ce(s.length, i.length);
          }(t.referenceValue, e.referenceValue);
  
        case 8 /* GeoPointValue */ :
          return function(t, e) {
              const s = Ce(Y(t.latitude), Y(e.latitude));
              if (0 !== s) return s;
              return Ce(Y(t.longitude), Y(e.longitude));
          }(t.geoPointValue, e.geoPointValue);
  
        case 9 /* ArrayValue */ :
          return function(t, e) {
              const s = t.values || [], i = e.values || [];
              for (let t = 0; t < s.length && t < i.length; ++t) {
                  const e = j(s[t], i[t]);
                  if (e) return e;
              }
              return Ce(s.length, i.length);
          }(t.arrayValue, e.arrayValue);
  
        case 10 /* ObjectValue */ :
          return function(t, e) {
              const s = t.fields || {}, i = Object.keys(s), n = e.fields || {}, r = Object.keys(n);
              // 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.
              i.sort(), r.sort();
              for (let t = 0; t < i.length && t < r.length; ++t) {
                  const e = Ce(i[t], r[t]);
                  if (0 !== e) return e;
                  const h = j(s[i[t]], n[r[t]]);
                  if (0 !== h) return h;
              }
              return Ce(i.length, r.length);
          }
          /**
   * Generates the canonical ID for the provided field value (as used in Target
   * serialization).
   */ (t.mapValue, e.mapValue);
  
        default:
          throw be();
      }
  }
  
  function K(t, e) {
      if ("string" == typeof t && "string" == typeof e && t.length === e.length) return Ce(t, e);
      const s = H(t), i = H(e), n = Ce(s.seconds, i.seconds);
      return 0 !== n ? n : Ce(s.nanos, i.nanos);
  }
  
  function G(t) {
      return z(t);
  }
  
  function z(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 = H(t);
          return `time(${e.seconds},${e.nanos})`;
      }(t.timestampValue) : "stringValue" in t ? t.stringValue : "bytesValue" in t ? J(t.bytesValue).toBase64() : "referenceValue" in t ? (s = t.referenceValue, 
      C.Z(s).toString()) : "geoPointValue" in t ? `geo(${(e = t.geoPointValue).latitude},${e.longitude})` : "arrayValue" in t ? function(t) {
          let e = "[", s = !0;
          for (const i of t.values || []) s ? s = !1 : e += ",", e += z(i);
          return e + "]";
      }
      /**
   * Converts the possible Proto values for a timestamp value into a "seconds and
   * nanos" representation.
   */ (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 s = "{", i = !0;
          for (const n of e) i ? i = !1 : s += ",", s += `${n}:${z(t.fields[n])}`;
          return s + "}";
      }(t.mapValue) : be();
      var e, s;
  }
  
  function H(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 (ve(!!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 s = q.exec(t);
          if (ve(!!s), s[1]) {
              // Pad the fraction out to 9 digits (nanos).
              let t = s[1];
              t = (t + "000000000").substr(0, 9), e = Number(t);
          }
          // Parse the date to get the seconds.
                  const i = new Date(t);
          return {
              seconds: Math.floor(i.getTime() / 1e3),
              nanos: e
          };
      }
      return {
          seconds: Y(t.seconds),
          nanos: Y(t.nanos)
      };
  }
  
  /**
   * Converts the possible Proto types for numbers into a JavaScript number.
   * Returns 0 if the value is not numeric.
   */ function Y(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 J(t) {
      return "string" == typeof t ? k.fromBase64String(t) : k.fromUint8Array(t);
  }
  
  /** Returns a reference value for the provided database and key. */ function X(t, e) {
      return {
          referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.j()}`
      };
  }
  
  /** Returns true if `value` is an IntegerValue . */ function Z(t) {
      return !!t && "integerValue" in t;
  }
  
  /** Returns true if `value` is a DoubleValue. */
  /** Returns true if `value` is an ArrayValue. */
  function tt(t) {
      return !!t && "arrayValue" in t;
  }
  
  /** Returns true if `value` is a NullValue. */ function et(t) {
      return !!t && "nullValue" in t;
  }
  
  /** Returns true if `value` is NaN. */ function st(t) {
      return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue));
  }
  
  /** Returns true if `value` is a MapValue. */ function it(t) {
      return !!t && "mapValue" in 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.
   */
  /** Transforms a value into a server-generated timestamp. */ class nt {
      constructor() {}
      ot(t, e) {
          return function(t, e) {
              const s = {
                  fields: {
                      __type__: {
                          stringValue: "server_timestamp"
                      },
                      __local_write_time__: {
                          timestampValue: {
                              seconds: t.seconds,
                              nanos: t.nanoseconds
                          }
                      }
                  }
              };
              return e && (s.fields.__previous_value__ = e), {
                  mapValue: s
              };
          }
          /**
   * 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.
   */ (e, t);
      }
      at(t, e) {
          return e;
      }
      ut(t) {
          return null;
   // Server timestamps are idempotent and don't require a base value.
          }
      isEqual(t) {
          return t instanceof nt;
      }
  }
  
  nt.instance = new nt;
  
  /** Transforms an array value via a union operation. */
  class rt {
      constructor(t) {
          this.elements = t;
      }
      ot(t, e) {
          return this.apply(t);
      }
      at(t, e) {
          // 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 this.apply(t);
      }
      apply(t) {
          const e = at(t);
          for (const t of this.elements) e.some(e => Q(e, t)) || e.push(t);
          return {
              arrayValue: {
                  values: e
              }
          };
      }
      ut(t) {
          return null;
   // Array transforms are idempotent and don't require a base value.
          }
      isEqual(t) {
          return t instanceof rt && Fe(this.elements, t.elements, Q);
      }
  }
  
  /** Transforms an array value via a remove operation. */ class ht {
      constructor(t) {
          this.elements = t;
      }
      ot(t, e) {
          return this.apply(t);
      }
      at(t, e) {
          // 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 this.apply(t);
      }
      apply(t) {
          let e = at(t);
          for (const t of this.elements) e = e.filter(e => !Q(e, t));
          return {
              arrayValue: {
                  values: e
              }
          };
      }
      ut(t) {
          return null;
   // Array transforms are idempotent and don't require a base value.
          }
      isEqual(t) {
          return t instanceof ht && Fe(this.elements, t.elements, Q);
      }
  }
  
  /**
   * 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 ot {
      constructor(t, e) {
          this.serializer = t, this.ct = e;
      }
      ot(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 s = this.ut(t), i = this.asNumber(s) + this.asNumber(this.ct);
          return Z(s) && Z(this.ct) ? this.serializer._t(i) : this.serializer.lt(i);
      }
      at(t, e) {
          return e;
      }
      /**
       * Inspects the provided value, returning the provided value if it is already
       * a NumberValue, otherwise returning a coerced value of 0.
       */    ut(t) {
          return Z(e = t) || function(t) {
              return !!t && "doubleValue" in t;
          }
          /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ (e) ? t : {
              integerValue: 0
          };
          var e;
      }
      isEqual(t) {
          return t instanceof ot && Q(this.ct, t.ct);
      }
      asNumber(t) {
          return Y(t.integerValue || t.doubleValue);
      }
  }
  
  function at(t) {
      return tt(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.
   */
  /**
   * 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 ut {
      constructor(t) {
          this.fields = t, 
          // TODO(dimond): validation of FieldMask
          // Sort the field mask to support `FieldMask.isEqual()` and assert below.
          t.sort(D.N);
      }
      /**
       * 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.
       */    dt(t) {
          for (const e of this.fields) if (e.q(t)) return !0;
          return !1;
      }
      isEqual(t) {
          return Fe(this.fields, t.fields, (t, e) => t.isEqual(e));
      }
  }
  
  /** A field path and the TransformOperation to perform upon it. */ class ct {
      constructor(t, e) {
          this.field = t, this.transform = e;
      }
      isEqual(t) {
          return this.field.isEqual(t.field) && this.transform.isEqual(t.transform);
      }
  }
  
  /** The result of successfully applying a mutation to the backend. */ class _t {
      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
       * TransformMutation has been committed. Contains one FieldValue for each
       * FieldTransform that was in the mutation.
       *
       * Will be null if the mutation was not a TransformMutation.
       */
      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 lt {
      constructor(t, e) {
          this.updateTime = t, this.exists = e;
      }
      /** Creates a new empty Precondition. */    static ft() {
          return new lt;
      }
      /** Creates a new Precondition with an exists flag. */    static exists(t) {
          return new lt(void 0, t);
      }
      /** Creates a new Precondition based on a version a document exists at. */    static updateTime(t) {
          return new lt(t);
      }
      /** Returns whether this Precondition is empty. */    get Tt() {
          return void 0 === this.updateTime && void 0 === this.exists;
      }
      /**
       * Returns true if the preconditions is valid for the given document
       * (or null if no document is available).
       */    Et(t) {
          return void 0 !== this.updateTime ? t instanceof Vt && t.version.isEqual(this.updateTime) : void 0 === this.exists || this.exists === t instanceof Vt;
      }
      isEqual(t) {
          return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);
      }
  }
  
  /**
   * 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, Patch, and Transform 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
   * TransformMutation  Document(v3)          Document(v3)
   * TransformMutation  NoDocument(v3)        NoDocument(v3)
   * TransformMutation  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, Patch, and Transform 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.
   *
   * Note that TransformMutations don't create Documents (in the case of being
   * applied to a NoDocument), even though they would on the backend. This is
   * because the client always combines the TransformMutation with a SetMutation
   * or PatchMutation and we only want to apply the transform if the prior
   * mutation resulted in a Document (always true for a SetMutation, but not
   * necessarily for a PatchMutation).
   *
   * ## 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 dt {
      It(t) {}
      /**
       * 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().
       */    static wt(t) {
          return t instanceof Vt ? t.version : y.min();
      }
  }
  
  /**
   * A mutation that creates or replaces the document at the given key with the
   * object value contents.
   */ class ft extends dt {
      constructor(t, e, s) {
          super(), this.key = t, this.value = e, this.Rt = s, this.type = 0 /* Set */;
      }
      at(t, e) {
          this.It(t);
          // Unlike applyToLocalView, if we're applying a mutation to a remote
          // document the server has accepted the mutation so the precondition must
          // have held.
          const s = e.version;
          return new Vt(this.key, s, this.value, {
              hasCommittedMutations: !0
          });
      }
      ot(t, e, s) {
          if (this.It(t), !this.Rt.Et(t)) return t;
          const i = dt.wt(t);
          return new Vt(this.key, i, this.value, {
              At: !0
          });
      }
      Pt(t) {
          return null;
      }
      isEqual(t) {
          return t instanceof ft && this.key.isEqual(t.key) && this.value.isEqual(t.value) && this.Rt.isEqual(t.Rt);
      }
  }
  
  /**
   * 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.
   */ class Tt extends dt {
      constructor(t, e, s, i) {
          super(), this.key = t, this.data = e, this.Vt = s, this.Rt = i, this.type = 1 /* Patch */;
      }
      at(t, e) {
          if (this.It(t), !this.Rt.Et(t)) 
          // 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 pt(this.key, e.version);
          const s = this.gt(t);
          return new Vt(this.key, e.version, s, {
              hasCommittedMutations: !0
          });
      }
      ot(t, e, s) {
          if (this.It(t), !this.Rt.Et(t)) return t;
          const i = dt.wt(t), n = this.gt(t);
          return new Vt(this.key, i, n, {
              At: !0
          });
      }
      Pt(t) {
          return null;
      }
      isEqual(t) {
          return t instanceof Tt && this.key.isEqual(t.key) && this.Vt.isEqual(t.Vt) && this.Rt.isEqual(t.Rt);
      }
      /**
       * 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.
       */    gt(t) {
          let e;
          return e = t instanceof Vt ? t.data() : Rt.empty(), this.pt(e);
      }
      pt(t) {
          const e = new mt(t);
          return this.Vt.fields.forEach(t => {
              if (!t.B()) {
                  const s = this.data.field(t);
                  null !== s ? e.set(t, s) : e.delete(t);
              }
          }), e.yt();
      }
  }
  
  /**
   * A mutation that modifies specific fields of the document with transform
   * operations. Currently the only supported transform is a server timestamp, but
   * IP Address, increment(n), etc. could be supported in the future.
   *
   * It is somewhat similar to a PatchMutation in that it patches specific fields
   * and has no effect when applied to a null or NoDocument (see comment on
   * Mutation for rationale).
   */ class Et extends dt {
      constructor(t, e) {
          super(), this.key = t, this.fieldTransforms = e, this.type = 2 /* Transform */ , 
          // NOTE: We set a precondition of exists: true as a safety-check, since we
          // always combine TransformMutations with a SetMutation or PatchMutation which
          // (if successful) should end up with an existing document.
          this.Rt = lt.exists(!0);
      }
      at(t, e) {
          if (this.It(t), ve(null != e.transformResults), !this.Rt.Et(t)) 
          // 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 pt(this.key, e.version);
          const s = this.bt(t), i = this.vt(t, e.transformResults), n = e.version, r = this.St(s.data(), i);
          return new Vt(this.key, n, r, {
              hasCommittedMutations: !0
          });
      }
      ot(t, e, s) {
          if (this.It(t), !this.Rt.Et(t)) return t;
          const i = this.bt(t), n = this.Dt(s, t, e), r = this.St(i.data(), n);
          return new Vt(this.key, i.version, r, {
              At: !0
          });
      }
      Pt(t) {
          let e = null;
          for (const s of this.fieldTransforms) {
              const i = t instanceof Vt ? t.field(s.field) : void 0, n = s.transform.ut(i || null);
              null != n && (e = null == e ? (new mt).set(s.field, n) : e.set(s.field, n));
          }
          return e ? e.yt() : null;
      }
      isEqual(t) {
          return t instanceof Et && this.key.isEqual(t.key) && Fe(this.fieldTransforms, t.fieldTransforms, (t, e) => t.isEqual(e)) && this.Rt.isEqual(t.Rt);
      }
      /**
       * Asserts that the given MaybeDocument is actually a Document and verifies
       * that it matches the key for this mutation. Since we only support
       * transformations with precondition exists this method is guaranteed to be
       * safe.
       */    bt(t) {
          return t;
      }
      /**
       * Creates a list of "transform results" (a transform result is a field value
       * representing the result of applying a transform) for use after a
       * TransformMutation has been acknowledged by the server.
       *
       * @param baseDoc The document prior to applying this mutation batch.
       * @param serverTransformResults The transform results received by the server.
       * @return The transform results list.
       */    vt(t, e) {
          const s = [];
          ve(this.fieldTransforms.length === e.length);
          for (let i = 0; i < e.length; i++) {
              const n = this.fieldTransforms[i], r = n.transform;
              let h = null;
              t instanceof Vt && (h = t.field(n.field)), s.push(r.at(h, e[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
       * TransformMutation locally.
       *
       * @param localWriteTime The local time of the transform 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.
       * @return The transform results list.
       */    Dt(t, e, s) {
          const i = [];
          for (const n of this.fieldTransforms) {
              const r = n.transform;
              let h = null;
              e instanceof Vt && (h = e.field(n.field)), null === h && s instanceof Vt && (
              // If the current document does not contain a value for the mutated
              // field, use the value that existed before applying this mutation
              // batch. This solves an edge case where a PatchMutation clears the
              // values in a nested map before the TransformMutation is applied.
              h = s.field(n.field)), i.push(r.ot(h, t));
          }
          return i;
      }
      St(t, e) {
          const s = new mt(t);
          for (let t = 0; t < this.fieldTransforms.length; t++) {
              const i = this.fieldTransforms[t].field;
              s.set(i, e[t]);
          }
          return s.yt();
      }
  }
  
  /** A mutation that deletes the document at the given key. */ class It extends dt {
      constructor(t, e) {
          super(), this.key = t, this.Rt = e, this.type = 3 /* Delete */;
      }
      at(t, e) {
          // 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 this.It(t), new gt(this.key, e.version, {
              hasCommittedMutations: !0
          });
      }
      ot(t, e, s) {
          return this.It(t), this.Rt.Et(t) ? new gt(this.key, y.min()) : t;
      }
      Pt(t) {
          return null;
      }
      isEqual(t) {
          return t instanceof It && this.key.isEqual(t.key) && this.Rt.isEqual(t.Rt);
      }
  }
  
  /**
   * 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.
   */ class wt extends dt {
      constructor(t, e) {
          super(), this.key = t, this.Rt = e, this.type = 4 /* Verify */;
      }
      at(t, e) {
          be();
      }
      ot(t, e, s) {
          be();
      }
      Pt(t) {
          be();
      }
      isEqual(t) {
          return t instanceof wt && this.key.isEqual(t.key) && this.Rt.isEqual(t.Rt);
      }
  }
  
  /**
   * @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 Rt {
      constructor(t) {
          this.proto = t;
      }
      static empty() {
          return new Rt({
              mapValue: {}
          });
      }
      /**
       * Returns the value at the given path or null.
       *
       * @param path the path to search
       * @return The value at the path or if there it doesn't exist.
       */    field(t) {
          if (t.B()) return this.proto;
          {
              let e = this.proto;
              for (let s = 0; s < t.length - 1; ++s) {
                  if (!e.mapValue.fields) return null;
                  if (e = e.mapValue.fields[t.get(s)], !it(e)) return null;
              }
              return e = (e.mapValue.fields || {})[t.O()], e || null;
          }
      }
      isEqual(t) {
          return Q(this.proto, t.proto);
      }
  }
  
  /**
   * An ObjectValueBuilder provides APIs to set and delete fields from an
   * ObjectValue.
   */ class mt {
      /**
       * @param baseObject The object to mutate.
       */
      constructor(t = Rt.empty()) {
          this.Ct = t, 
          /** A map that contains the accumulated changes in this builder. */
          this.Ft = new Map;
      }
      /**
       * Sets the field to the provided value.
       *
       * @param path The field path to set.
       * @param value The value to set.
       * @return The current Builder instance.
       */    set(t, e) {
          return this.Nt(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.
       * @return The current Builder instance.
       */    delete(t) {
          return this.Nt(t, null), this;
      }
      /**
       * Adds `value` to the overlay map at `path`. Creates nested map entries if
       * needed.
       */    Nt(t, e) {
          let s = this.Ft;
          for (let e = 0; e < t.length - 1; ++e) {
              const i = t.get(e);
              let n = s.get(i);
              n instanceof Map ? 
              // Re-use a previously created map
              s = n : n && 10 /* ObjectValue */ === U(n) ? (
              // Convert the existing Protobuf MapValue into a map
              n = new Map(Object.entries(n.mapValue.fields || {})), s.set(i, n), s = n) : (
              // Create an empty map to represent the current nesting level
              n = new Map, s.set(i, n), s = n);
          }
          s.set(t.O(), e);
      }
      /** Returns an ObjectValue with all mutations applied. */    yt() {
          const t = this.$t(D.G, this.Ft);
          return null != t ? new Rt(t) : this.Ct;
      }
      /**
       * 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.EMPTY_PATH to represent the root.
       * @param currentOverlays The overlays at the current nesting level in the
       * same format as `overlayMap`.
       * @return The merged data at `currentPath` or null if no modifications
       * were applied.
       */    $t(t, e) {
          let s = !1;
          const i = this.Ct.field(t), n = it(i) ? // If there is already data at the current path, base our
          Object.assign({}, i.mapValue.fields) : {};
          return e.forEach((e, i) => {
              if (e instanceof Map) {
                  const r = this.$t(t.child(i), e);
                  null != r && (n[i] = r, s = !0);
              } else null !== e ? (n[i] = e, s = !0) : n.hasOwnProperty(i) && (delete n[i], s = !0);
          }), s ? {
              mapValue: {
                  fields: n
              }
          } : null;
      }
  }
  
  /**
   * Returns a FieldMask built from all fields in a MapValue.
   */ function At(t) {
      const e = [];
      return N(t.fields || {}, (t, s) => {
          const i = new D([ t ]);
          if (it(s)) {
              const t = At(s.mapValue).fields;
              if (0 === t.length) 
              // Preserve the empty map by adding it to the FieldMask.
              e.push(i); else 
              // For nested and non-empty ObjectValues, add the FieldPath of the
              // leaf nodes.
              for (const s of t) e.push(i.child(s));
          } else 
          // For nested and non-empty ObjectValues, add the FieldPath of the leaf
          // nodes.
          e.push(i);
      }), new ut(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 Pt {
      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 Vt extends Pt {
      constructor(t, e, s, i) {
          super(t, e), this.kt = s, this.At = !!i.At, this.hasCommittedMutations = !!i.hasCommittedMutations;
      }
      field(t) {
          return this.kt.field(t);
      }
      data() {
          return this.kt;
      }
      Mt() {
          return this.kt.proto;
      }
      isEqual(t) {
          return t instanceof Vt && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.At === t.At && this.hasCommittedMutations === t.hasCommittedMutations && this.kt.isEqual(t.kt);
      }
      toString() {
          return `Document(${this.key}, ${this.version}, ${this.kt.toString()}, ` + `{hasLocalMutations: ${this.At}}), ` + `{hasCommittedMutations: ${this.hasCommittedMutations}})`;
      }
      get hasPendingWrites() {
          return this.At || 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 gt extends Pt {
      constructor(t, e, s) {
          super(t, e), this.hasCommittedMutations = !(!s || !s.hasCommittedMutations);
      }
      toString() {
          return `NoDocument(${this.key}, ${this.version})`;
      }
      get hasPendingWrites() {
          return this.hasCommittedMutations;
      }
      isEqual(t) {
          return t instanceof gt && 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 pt extends Pt {
      toString() {
          return `UnknownDocument(${this.key}, ${this.version})`;
      }
      get hasPendingWrites() {
          return !0;
      }
      isEqual(t) {
          return t instanceof pt && 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.
   */
  /**
   * A Target represents the WatchTarget representation of a Query, which is used
   * by the LocalStore and the RemoteStore to keep track of and to execute
   * backend queries. While a Query can represent multiple Targets, each Targets
   * maps to a single WatchTarget in RemoteStore and a single TargetData entry
   * in persistence.
   */ class yt {
      /**
       * 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 constructor, because `Query` provides an implicit `orderBy`
       * property.
       */
      constructor(t, e = null, s = [], i = [], n = null, r = null, h = null) {
          this.path = t, this.collectionGroup = e, this.orderBy = s, this.filters = i, this.limit = n, 
          this.startAt = r, this.endAt = h, this.Lt = null;
      }
      canonicalId() {
          if (null === this.Lt) {
              let t = this.path.j();
              null !== this.collectionGroup && (t += "|cg:" + this.collectionGroup), t += "|f:", 
              t += this.filters.map(t => t.canonicalId()).join(","), t += "|ob:", t += this.orderBy.map(t => t.canonicalId()).join(","), 
              M(this.limit) || (t += "|l:", t += this.limit), this.startAt && (t += "|lb:", t += this.startAt.canonicalId()), 
              this.endAt && (t += "|ub:", t += this.endAt.canonicalId()), this.Lt = t;
          }
          return this.Lt;
      }
      toString() {
          let t = this.path.j();
          return null !== this.collectionGroup && (t += " collectionGroup=" + this.collectionGroup), 
          this.filters.length > 0 && (t += `, filters: [${this.filters.join(", ")}]`), M(this.limit) || (t += ", limit: " + this.limit), 
          this.orderBy.length > 0 && (t += `, orderBy: [${this.orderBy.join(", ")}]`), this.startAt && (t += ", startAt: " + this.startAt.canonicalId()), 
          this.endAt && (t += ", endAt: " + this.endAt.canonicalId()), `Target(${t})`;
      }
      isEqual(t) {
          if (this.limit !== t.limit) return !1;
          if (this.orderBy.length !== t.orderBy.length) return !1;
          for (let e = 0; e < this.orderBy.length; e++) if (!this.orderBy[e].isEqual(t.orderBy[e])) return !1;
          if (this.filters.length !== t.filters.length) return !1;
          for (let e = 0; e < this.filters.length; e++) if (!this.filters[e].isEqual(t.filters[e])) return !1;
          return this.collectionGroup === t.collectionGroup && (!!this.path.isEqual(t.path) && (!!(null !== this.startAt ? this.startAt.isEqual(t.startAt) : null === t.startAt) && (null !== this.endAt ? this.endAt.isEqual(t.endAt) : null === t.endAt)));
      }
      Ot() {
          return C.et(this.path) && null === this.collectionGroup && 0 === this.filters.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.
   */
  /**
   * 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.
   */ class bt {
      /**
       * 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, s = [], i = [], n = null, r = "F" /* First */ , h = null, o = null) {
          this.path = t, this.collectionGroup = e, this.xt = s, this.filters = i, this.limit = n, 
          this.Bt = r, this.startAt = h, this.endAt = o, this.qt = null, 
          // The corresponding `Target` of this `Query` instance.
          this.Ut = null, this.startAt && this.Qt(this.startAt), this.endAt && this.Qt(this.endAt);
      }
      static Wt(t) {
          return new bt(t);
      }
      get orderBy() {
          if (null === this.qt) {
              this.qt = [];
              const t = this.jt(), e = this.Kt();
              if (null !== t && null === e) 
              // 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.Y() || this.qt.push(new kt(t)), this.qt.push(new kt(D.J(), "asc" /* ASCENDING */)); else {
                  let t = !1;
                  for (const e of this.xt) this.qt.push(e), e.field.Y() && (t = !0);
                  if (!t) {
                      // The order of the implicit key ordering always matches the last
                      // explicit order by
                      const t = this.xt.length > 0 ? this.xt[this.xt.length - 1].dir : "asc" /* ASCENDING */;
                      this.qt.push(new kt(D.J(), t));
                  }
              }
          }
          return this.qt;
      }
      Gt(t) {
          const e = this.filters.concat([ t ]);
          return new bt(this.path, this.collectionGroup, this.xt.slice(), e, this.limit, this.Bt, this.startAt, this.endAt);
      }
      zt(t) {
          // TODO(dimond): validate that orderBy does not list the same key twice.
          const e = this.xt.concat([ t ]);
          return new bt(this.path, this.collectionGroup, e, this.filters.slice(), this.limit, this.Bt, this.startAt, this.endAt);
      }
      Ht(t) {
          return new bt(this.path, this.collectionGroup, this.xt.slice(), this.filters.slice(), t, "F" /* First */ , this.startAt, this.endAt);
      }
      Yt(t) {
          return new bt(this.path, this.collectionGroup, this.xt.slice(), this.filters.slice(), t, "L" /* Last */ , this.startAt, this.endAt);
      }
      Jt(t) {
          return new bt(this.path, this.collectionGroup, this.xt.slice(), this.filters.slice(), this.limit, this.Bt, t, this.endAt);
      }
      Xt(t) {
          return new bt(this.path, this.collectionGroup, this.xt.slice(), this.filters.slice(), this.limit, this.Bt, this.startAt, 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.
       */    Zt(t) {
          return new bt(t, 
          /*collectionGroup=*/ null, this.xt.slice(), this.filters.slice(), this.limit, this.Bt, this.startAt, this.endAt);
      }
      /**
       * Returns true if this query does not specify any query constraints that
       * could remove results.
       */    te() {
          return 0 === this.filters.length && null === this.limit && null == this.startAt && null == this.endAt && (0 === this.xt.length || 1 === this.xt.length && this.xt[0].field.Y());
      }
      // 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.
      canonicalId() {
          return `${this.ee().canonicalId()}|lt:${this.Bt}`;
      }
      toString() {
          return `Query(target=${this.ee().toString()}; limitType=${this.Bt})`;
      }
      isEqual(t) {
          return this.ee().isEqual(t.ee()) && this.Bt === t.Bt;
      }
      se(t, e) {
          let s = !1;
          for (const i of this.orderBy) {
              const n = i.compare(t, e);
              if (0 !== n) return n;
              s = s || i.field.Y();
          }
          return 0;
      }
      matches(t) {
          return this.ie(t) && this.ne(t) && this.re(t) && this.he(t);
      }
      oe() {
          return !M(this.limit) && "F" /* First */ === this.Bt;
      }
      ae() {
          return !M(this.limit) && "L" /* Last */ === this.Bt;
      }
      Kt() {
          return this.xt.length > 0 ? this.xt[0].field : null;
      }
      jt() {
          for (const t of this.filters) if (t instanceof vt && t.ue()) return t.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.
      ce(t) {
          for (const e of this.filters) if (e instanceof vt && t.indexOf(e.op) >= 0) return e.op;
          return null;
      }
      Ot() {
          return this.ee().Ot();
      }
      _e() {
          return null !== this.collectionGroup;
      }
      /**
       * Converts this `Query` instance to it's corresponding `Target`
       * representation.
       */    ee() {
          if (!this.Ut) if ("F" /* First */ === this.Bt) this.Ut = new yt(this.path, this.collectionGroup, this.orderBy, this.filters, this.limit, this.startAt, this.endAt); else {
              // Flip the orderBy directions since we want the last results
              const t = [];
              for (const e of this.orderBy) {
                  const s = "desc" /* DESCENDING */ === e.dir ? "asc" /* ASCENDING */ : "desc" /* DESCENDING */;
                  t.push(new kt(e.field, s));
              }
              // We need to swap the cursors to match the now-flipped query ordering.
                          const e = this.endAt ? new $t(this.endAt.position, !this.endAt.before) : null, s = this.startAt ? new $t(this.startAt.position, !this.startAt.before) : null;
              // Now return as a LimitType.First query.
              this.Ut = new yt(this.path, this.collectionGroup, t, this.filters, this.limit, e, s);
          }
          return this.Ut;
      }
      ie(t) {
          const e = t.key.path;
          return null !== this.collectionGroup ? t.key.tt(this.collectionGroup) && this.path.q(e) : C.et(this.path) ? this.path.isEqual(e) : this.path.U(e);
      }
      /**
       * A document must have a value for every ordering clause in order to show up
       * in the results.
       */    ne(t) {
          for (const e of this.xt) 
          // order by key always matches
          if (!e.field.Y() && null === t.field(e.field)) return !1;
          return !0;
      }
      re(t) {
          for (const e of this.filters) if (!e.matches(t)) return !1;
          return !0;
      }
      /**
       * Makes sure a document is within the bounds, if provided.
       */    he(t) {
          return !(this.startAt && !this.startAt.le(this.orderBy, t)) && (!this.endAt || !this.endAt.le(this.orderBy, t));
      }
      Qt(t) {}
  }
  
  class vt extends class {} {
      constructor(t, e, s) {
          super(), this.field = t, this.op = e, this.value = s;
      }
      /**
       * Creates a filter based on the provided arguments.
       */    static create(t, e, s) {
          if (t.Y()) return "in" /* IN */ === e ? new Dt(t, s) : new St(t, e, s);
          if (et(s)) {
              if ("==" /* EQUAL */ !== e) throw new R(w.INVALID_ARGUMENT, "Invalid query. Null supports only equality comparisons.");
              return new vt(t, e, s);
          }
          if (st(s)) {
              if ("==" /* EQUAL */ !== e) throw new R(w.INVALID_ARGUMENT, "Invalid query. NaN supports only equality comparisons.");
              return new vt(t, e, s);
          }
          return "array-contains" /* ARRAY_CONTAINS */ === e ? new Ct(t, s) : "in" /* IN */ === e ? new Ft(t, s) : "array-contains-any" /* ARRAY_CONTAINS_ANY */ === e ? new Nt(t, s) : new vt(t, e, s);
      }
      matches(t) {
          const e = t.field(this.field);
          // Only compare types with matching backend order (such as double and int).
                  return null !== e && U(this.value) === U(e) && this.de(j(e, this.value));
      }
      de(t) {
          switch (this.op) {
            case "<" /* LESS_THAN */ :
              return t < 0;
  
            case "<=" /* LESS_THAN_OR_EQUAL */ :
              return t <= 0;
  
            case "==" /* EQUAL */ :
              return 0 === t;
  
            case ">" /* GREATER_THAN */ :
              return t > 0;
  
            case ">=" /* GREATER_THAN_OR_EQUAL */ :
              return t >= 0;
  
            default:
              return be();
          }
      }
      ue() {
          return [ "<" /* LESS_THAN */ , "<=" /* LESS_THAN_OR_EQUAL */ , ">" /* GREATER_THAN */ , ">=" /* GREATER_THAN_OR_EQUAL */ ].indexOf(this.op) >= 0;
      }
      canonicalId() {
          // 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 this.field.j() + this.op.toString() + G(this.value);
      }
      isEqual(t) {
          return t instanceof vt && (this.op === t.op && this.field.isEqual(t.field) && Q(this.value, t.value));
      }
      toString() {
          return `${this.field.j()} ${this.op} ${G(this.value)}`;
      }
  }
  
  /** Filter that matches on key fields (i.e. '__name__'). */ class St extends vt {
      constructor(t, e, s) {
          super(t, e, s), this.key = C.Z(s.referenceValue);
      }
      matches(t) {
          const e = C.N(t.key, this.key);
          return this.de(e);
      }
  }
  
  /** Filter that matches on key fields within an array. */ class Dt extends vt {
      constructor(t, e) {
          super(t, "in" /* IN */ , e), this.keys = (e.arrayValue.values || []).map(t => C.Z(t.referenceValue));
      }
      matches(t) {
          return this.keys.some(e => e.isEqual(t.key));
      }
  }
  
  /** A Filter that implements the array-contains operator. */ class Ct extends vt {
      constructor(t, e) {
          super(t, "array-contains" /* ARRAY_CONTAINS */ , e);
      }
      matches(t) {
          const e = t.field(this.field);
          return tt(e) && W(e.arrayValue, this.value);
      }
  }
  
  /** A Filter that implements the IN operator. */ class Ft extends vt {
      constructor(t, e) {
          super(t, "in" /* IN */ , e);
      }
      matches(t) {
          const e = t.field(this.field);
          return null !== e && W(this.value.arrayValue, e);
      }
  }
  
  /** A Filter that implements the array-contains-any operator. */ class Nt extends vt {
      constructor(t, e) {
          super(t, "array-contains-any" /* ARRAY_CONTAINS_ANY */ , e);
      }
      matches(t) {
          const e = t.field(this.field);
          return !(!tt(e) || !e.arrayValue.values) && e.arrayValue.values.some(t => W(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 $t {
      constructor(t, e) {
          this.position = t, this.before = e;
      }
      canonicalId() {
          // TODO(b/29183165): Make this collision robust.
          return `${this.before ? "b" : "a"}:${this.position.map(t => G(t)).join(",")}`;
      }
      /**
       * Returns true if a document sorts before a bound using the provided sort
       * order.
       */    le(t, e) {
          let s = 0;
          for (let i = 0; i < this.position.length; i++) {
              const n = t[i], r = this.position[i];
              if (n.field.Y()) s = C.N(C.Z(r.referenceValue), e.key); else {
                  s = j(r, e.field(n.field));
              }
              if ("desc" /* DESCENDING */ === n.dir && (s *= -1), 0 !== s) break;
          }
          return this.before ? s <= 0 : s < 0;
      }
      isEqual(t) {
          if (null === t) return !1;
          if (this.before !== t.before || this.position.length !== t.position.length) return !1;
          for (let e = 0; e < this.position.length; e++) {
              if (!Q(this.position[e], t.position[e])) return !1;
          }
          return !0;
      }
  }
  
  /**
   * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
   */ class kt {
      constructor(t, e) {
          this.field = t, void 0 === e && (e = "asc" /* ASCENDING */), this.dir = e, this.fe = t.Y();
      }
      compare(t, e) {
          const s = this.fe ? C.N(t.key, e.key) : function(t, e, s) {
              const i = e.field(t), n = s.field(t);
              return null !== i && null !== n ? j(i, n) : be();
          }(this.field, t, e);
          switch (this.dir) {
            case "asc" /* ASCENDING */ :
              return s;
  
            case "desc" /* DESCENDING */ :
              return -1 * s;
  
            default:
              return be();
          }
      }
      canonicalId() {
          // TODO(b/29183165): Make this collision robust.
          return this.field.j() + this.dir.toString();
      }
      toString() {
          return `${this.field.j()} (${this.dir})`;
      }
      isEqual(t) {
          return this.dir === t.dir && this.field.isEqual(t.field);
      }
  }
  
  /**
   * @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 Mt {
      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. */
      s, 
      /**
       * The sequence number of the last transaction during which this target data
       * was modified.
       */
      i, 
      /** The latest snapshot version seen for this target. */
      n = y.min()
      /**
       * The maximum snapshot version at which the associated view
       * contained no limbo documents.
       */ , r = y.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.
       */ , h = k.ht) {
          this.target = t, this.targetId = e, this.Te = s, this.sequenceNumber = i, this.Ee = n, 
          this.lastLimboFreeSnapshotVersion = r, this.resumeToken = h;
      }
      /** Creates a new target data instance with an updated sequence number. */    Ie(t) {
          return new Mt(this.target, this.targetId, this.Te, t, this.Ee, this.lastLimboFreeSnapshotVersion, this.resumeToken);
      }
      /**
       * Creates a new target data instance with an updated resume token and
       * snapshot version.
       */    we(t, e) {
          return new Mt(this.target, this.targetId, this.Te, this.sequenceNumber, e, this.lastLimboFreeSnapshotVersion, t);
      }
      /**
       * Creates a new target data instance with an updated last limbo free
       * snapshot version number.
       */    Re(t) {
          return new Mt(this.target, this.targetId, this.Te, this.sequenceNumber, this.Ee, t, this.resumeToken);
      }
  }
  
  /**
   * @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 Lt {
      // 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 Ot, xt;
  
  /**
   * 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 Bt(t) {
      switch (t) {
        case w.OK:
          return be();
  
        case w.CANCELLED:
        case w.UNKNOWN:
        case w.DEADLINE_EXCEEDED:
        case w.RESOURCE_EXHAUSTED:
        case w.INTERNAL:
        case w.UNAVAILABLE:
   // Unauthenticated means something went wrong with our token and we need
          // to retry with new credentials which will happen automatically.
                case w.UNAUTHENTICATED:
          return !1;
  
        case w.INVALID_ARGUMENT:
        case w.NOT_FOUND:
        case w.ALREADY_EXISTS:
        case w.PERMISSION_DENIED:
        case w.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 w.ABORTED:
        case w.OUT_OF_RANGE:
        case w.UNIMPLEMENTED:
        case w.DATA_LOSS:
          return !0;
  
        default:
          return be();
      }
  }
  
  /**
   * 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 qt(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 pe("GRPC error has no .code"), w.UNKNOWN;
      switch (t) {
        case Ot.OK:
          return w.OK;
  
        case Ot.CANCELLED:
          return w.CANCELLED;
  
        case Ot.UNKNOWN:
          return w.UNKNOWN;
  
        case Ot.DEADLINE_EXCEEDED:
          return w.DEADLINE_EXCEEDED;
  
        case Ot.RESOURCE_EXHAUSTED:
          return w.RESOURCE_EXHAUSTED;
  
        case Ot.INTERNAL:
          return w.INTERNAL;
  
        case Ot.UNAVAILABLE:
          return w.UNAVAILABLE;
  
        case Ot.UNAUTHENTICATED:
          return w.UNAUTHENTICATED;
  
        case Ot.INVALID_ARGUMENT:
          return w.INVALID_ARGUMENT;
  
        case Ot.NOT_FOUND:
          return w.NOT_FOUND;
  
        case Ot.ALREADY_EXISTS:
          return w.ALREADY_EXISTS;
  
        case Ot.PERMISSION_DENIED:
          return w.PERMISSION_DENIED;
  
        case Ot.FAILED_PRECONDITION:
          return w.FAILED_PRECONDITION;
  
        case Ot.ABORTED:
          return w.ABORTED;
  
        case Ot.OUT_OF_RANGE:
          return w.OUT_OF_RANGE;
  
        case Ot.UNIMPLEMENTED:
          return w.UNIMPLEMENTED;
  
        case Ot.DATA_LOSS:
          return w.DATA_LOSS;
  
        default:
          return be();
      }
  }
  
  /**
   * 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.
   */ (xt = Ot || (Ot = {}))[xt.OK = 0] = "OK", xt[xt.CANCELLED = 1] = "CANCELLED", 
  xt[xt.UNKNOWN = 2] = "UNKNOWN", xt[xt.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", 
  xt[xt.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", xt[xt.NOT_FOUND = 5] = "NOT_FOUND", 
  xt[xt.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", xt[xt.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", 
  xt[xt.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", xt[xt.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", 
  xt[xt.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", xt[xt.ABORTED = 10] = "ABORTED", 
  xt[xt.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", xt[xt.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", 
  xt[xt.INTERNAL = 13] = "INTERNAL", xt[xt.UNAVAILABLE = 14] = "UNAVAILABLE", xt[xt.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 Ut {
      constructor(t, e) {
          this.N = t, this.root = e || Wt.EMPTY;
      }
      // Returns a copy of the map, with the specified key/value added or replaced.
      me(t, e) {
          return new Ut(this.N, this.root.me(t, e, this.N).Ae(null, null, Wt.Pe, null, null));
      }
      // Returns a copy of the map, with the specified key removed.
      remove(t) {
          return new Ut(this.N, this.root.remove(t, this.N).Ae(null, null, Wt.Pe, null, null));
      }
      // Returns the value of the node with the given key, or null.
      get(t) {
          let e = this.root;
          for (;!e.B(); ) {
              const s = this.N(t, e.key);
              if (0 === s) return e.value;
              s < 0 ? e = e.left : s > 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, s = this.root;
          for (;!s.B(); ) {
              const i = this.N(t, s.key);
              if (0 === i) return e + s.left.size;
              i < 0 ? s = s.left : (
              // Count all nodes left of the node plus the node itself
              e += s.left.size + 1, s = s.right);
          }
          // Node not found
                  return -1;
      }
      B() {
          return this.root.B();
      }
      // Returns the total number of nodes in the map.
      get size() {
          return this.root.size;
      }
      // Returns the minimum key in the map.
      Ve() {
          return this.root.Ve();
      }
      // Returns the maximum key in the map.
      ge() {
          return this.root.ge();
      }
      // 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.
      pe(t) {
          return this.root.pe(t);
      }
      forEach(t) {
          this.pe((e, s) => (t(e, s), !1));
      }
      toString() {
          const t = [];
          return this.pe((e, s) => (t.push(`${e}:${s}`), !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.
      ye(t) {
          return this.root.ye(t);
      }
      // Returns an iterator over the SortedMap.
      be() {
          return new Qt(this.root, null, this.N, !1);
      }
      ve(t) {
          return new Qt(this.root, t, this.N, !1);
      }
      Se() {
          return new Qt(this.root, null, this.N, !0);
      }
      De(t) {
          return new Qt(this.root, t, this.N, !0);
      }
  }
  
   // end SortedMap
  // An iterator over an LLRBNode.
  class Qt {
      constructor(t, e, s, i) {
          this.Ce = i, this.Fe = [];
          let n = 1;
          for (;!t.B(); ) if (n = e ? s(t.key, e) : 1, 
          // flip the comparison if we're going in reverse
          i && (n *= -1), n < 0) 
          // This node is less than our start key. ignore it
          t = this.Ce ? t.left : t.right; else {
              if (0 === n) {
                  // This node is exactly equal to our start key. Push it on the stack,
                  // but stop iterating;
                  this.Fe.push(t);
                  break;
              }
              // This node is greater than our start key, add it to the stack and move
              // to the next one
              this.Fe.push(t), t = this.Ce ? t.right : t.left;
          }
      }
      Ne() {
          let t = this.Fe.pop();
          const e = {
              key: t.key,
              value: t.value
          };
          if (this.Ce) for (t = t.left; !t.B(); ) this.Fe.push(t), t = t.right; else for (t = t.right; !t.B(); ) this.Fe.push(t), 
          t = t.left;
          return e;
      }
      $e() {
          return this.Fe.length > 0;
      }
      ke() {
          if (0 === this.Fe.length) return null;
          const t = this.Fe[this.Fe.length - 1];
          return {
              key: t.key,
              value: t.value
          };
      }
  }
  
   // end SortedMapIterator
  // Represents a node in a Left-leaning Red-Black tree.
  class Wt {
      constructor(t, e, s, i, n) {
          this.key = t, this.value = e, this.color = null != s ? s : Wt.RED, this.left = null != i ? i : Wt.EMPTY, 
          this.right = null != n ? n : Wt.EMPTY, this.size = this.left.size + 1 + this.right.size;
      }
      // Returns a copy of the current node, optionally replacing pieces of it.
      Ae(t, e, s, i, n) {
          return new Wt(null != t ? t : this.key, null != e ? e : this.value, null != s ? s : this.color, null != i ? i : this.left, null != n ? n : this.right);
      }
      B() {
          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.
      pe(t) {
          return this.left.pe(t) || t(this.key, this.value) || this.right.pe(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.
      ye(t) {
          return this.right.ye(t) || t(this.key, this.value) || this.left.ye(t);
      }
      // Returns the minimum node in the tree.
      min() {
          return this.left.B() ? this : this.left.min();
      }
      // Returns the maximum key in the tree.
      Ve() {
          return this.min().key;
      }
      // Returns the maximum key in the tree.
      ge() {
          return this.right.B() ? this.key : this.right.ge();
      }
      // Returns new tree, with the key/value added.
      me(t, e, s) {
          let i = this;
          const n = s(t, i.key);
          return i = n < 0 ? i.Ae(null, null, null, i.left.me(t, e, s), null) : 0 === n ? i.Ae(null, e, null, null, null) : i.Ae(null, null, null, null, i.right.me(t, e, s)), 
          i.Me();
      }
      Le() {
          if (this.left.B()) return Wt.EMPTY;
          let t = this;
          return t.left.Oe() || t.left.left.Oe() || (t = t.xe()), t = t.Ae(null, null, null, t.left.Le(), null), 
          t.Me();
      }
      // Returns new tree, with the specified item removed.
      remove(t, e) {
          let s, i = this;
          if (e(t, i.key) < 0) i.left.B() || i.left.Oe() || i.left.left.Oe() || (i = i.xe()), 
          i = i.Ae(null, null, null, i.left.remove(t, e), null); else {
              if (i.left.Oe() && (i = i.Be()), i.right.B() || i.right.Oe() || i.right.left.Oe() || (i = i.qe()), 
              0 === e(t, i.key)) {
                  if (i.right.B()) return Wt.EMPTY;
                  s = i.right.min(), i = i.Ae(s.key, s.value, null, null, i.right.Le());
              }
              i = i.Ae(null, null, null, null, i.right.remove(t, e));
          }
          return i.Me();
      }
      Oe() {
          return this.color;
      }
      // Returns new tree after performing any needed rotations.
      Me() {
          let t = this;
          return t.right.Oe() && !t.left.Oe() && (t = t.Ue()), t.left.Oe() && t.left.left.Oe() && (t = t.Be()), 
          t.left.Oe() && t.right.Oe() && (t = t.Qe()), t;
      }
      xe() {
          let t = this.Qe();
          return t.right.left.Oe() && (t = t.Ae(null, null, null, null, t.right.Be()), t = t.Ue(), 
          t = t.Qe()), t;
      }
      qe() {
          let t = this.Qe();
          return t.left.left.Oe() && (t = t.Be(), t = t.Qe()), t;
      }
      Ue() {
          const t = this.Ae(null, null, Wt.RED, null, this.right.left);
          return this.right.Ae(null, null, this.color, t, null);
      }
      Be() {
          const t = this.Ae(null, null, Wt.RED, this.left.right, null);
          return this.left.Ae(null, null, this.color, null, t);
      }
      Qe() {
          const t = this.left.Ae(null, null, !this.left.color, null, null), e = this.right.Ae(null, null, !this.right.color, null, null);
          return this.Ae(null, null, !this.color, t, e);
      }
      // For testing.
      We() {
          const t = this.je();
          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.
      je() {
          if (this.Oe() && this.left.Oe()) throw be();
          if (this.right.Oe()) throw be();
          const t = this.left.je();
          if (t !== this.right.je()) throw be();
          return t + (this.Oe() ? 0 : 1);
      }
  }
  
   // end LLRBNode
  // Empty node is shared between all LLRB trees.
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  Wt.EMPTY = null, Wt.RED = !0, Wt.Pe = !1;
  
  // end LLRBEmptyNode
  Wt.EMPTY = new 
  // Represents an empty node (a leaf node in the Red-Black Tree).
  class {
      constructor() {
          this.size = 0;
      }
      get key() {
          throw be();
      }
      get value() {
          throw be();
      }
      get color() {
          throw be();
      }
      get left() {
          throw be();
      }
      get right() {
          throw be();
      }
      // Returns a copy of the current node.
      Ae(t, e, s, i, n) {
          return this;
      }
      // Returns a copy of the tree, with the specified key/value added.
      me(t, e, s) {
          return new Wt(t, e);
      }
      // Returns a copy of the tree, with the specified key removed.
      remove(t, e) {
          return this;
      }
      B() {
          return !0;
      }
      pe(t) {
          return !1;
      }
      ye(t) {
          return !1;
      }
      Ve() {
          return null;
      }
      ge() {
          return null;
      }
      Oe() {
          return !1;
      }
      // For testing.
      We() {
          return !0;
      }
      je() {
          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 jt {
      constructor(t) {
          this.N = t, this.data = new Ut(this.N);
      }
      has(t) {
          return null !== this.data.get(t);
      }
      first() {
          return this.data.Ve();
      }
      last() {
          return this.data.ge();
      }
      get size() {
          return this.data.size;
      }
      indexOf(t) {
          return this.data.indexOf(t);
      }
      /** Iterates elements in order defined by "comparator" */    forEach(t) {
          this.data.pe((e, s) => (t(e), !1));
      }
      /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */    Ke(t, e) {
          const s = this.data.ve(t[0]);
          for (;s.$e(); ) {
              const i = s.Ne();
              if (this.N(i.key, t[1]) >= 0) return;
              e(i.key);
          }
      }
      /**
       * Iterates over `elem`s such that: start <= elem until false is returned.
       */    Ge(t, e) {
          let s;
          for (s = void 0 !== e ? this.data.ve(e) : this.data.be(); s.$e(); ) {
              if (!t(s.Ne().key)) return;
          }
      }
      /** Finds the least element greater than or equal to `elem`. */    ze(t) {
          const e = this.data.ve(t);
          return e.$e() ? e.Ne().key : null;
      }
      be() {
          return new Kt(this.data.be());
      }
      ve(t) {
          return new Kt(this.data.ve(t));
      }
      /** Inserts or updates an element */    add(t) {
          return this.Ae(this.data.remove(t).me(t, !0));
      }
      /** Deletes an element */    delete(t) {
          return this.has(t) ? this.Ae(this.data.remove(t)) : this;
      }
      B() {
          return this.data.B();
      }
      He(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 jt)) return !1;
          if (this.size !== t.size) return !1;
          const e = this.data.be(), s = t.data.be();
          for (;e.$e(); ) {
              const t = e.Ne().key, i = s.Ne().key;
              if (0 !== this.N(t, i)) return !1;
          }
          return !0;
      }
      W() {
          const t = [];
          return this.forEach(e => {
              t.push(e);
          }), t;
      }
      toString() {
          const t = [];
          return this.forEach(e => t.push(e)), "SortedSet(" + t.toString() + ")";
      }
      Ae(t) {
          const e = new jt(this.N);
          return e.data = t, e;
      }
  }
  
  class Kt {
      constructor(t) {
          this.Ye = t;
      }
      Ne() {
          return this.Ye.Ne().key;
      }
      $e() {
          return this.Ye.$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.
   */ const Gt = new Ut(C.N);
  
  function zt() {
      return Gt;
  }
  
  function Ht() {
      return zt();
  }
  
  const Yt = new Ut(C.N);
  
  function Jt() {
      return Yt;
  }
  
  const Xt = new Ut(C.N);
  
  function Zt() {
      return Xt;
  }
  
  const te = new jt(C.N);
  
  function ee(...t) {
      let e = te;
      for (const s of t) e = e.add(s);
      return e;
  }
  
  const se = new jt(Ce);
  
  function ie() {
      return se;
  }
  
  /**
   * @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 ne {
      /** 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.N = t ? (e, s) => t(e, s) || C.N(e.key, s.key) : (t, e) => C.N(t.key, e.key), 
          this.Je = Jt(), this.Xe = new Ut(this.N);
      }
      /**
       * Returns an empty copy of the existing DocumentSet, using the same
       * comparator.
       */    static Ze(t) {
          return new ne(t.N);
      }
      has(t) {
          return null != this.Je.get(t);
      }
      get(t) {
          return this.Je.get(t);
      }
      first() {
          return this.Xe.Ve();
      }
      last() {
          return this.Xe.ge();
      }
      B() {
          return this.Xe.B();
      }
      /**
       * 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.Je.get(t);
          return e ? this.Xe.indexOf(e) : -1;
      }
      get size() {
          return this.Xe.size;
      }
      /** Iterates documents in order defined by "comparator" */    forEach(t) {
          this.Xe.pe((e, s) => (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.Ae(e.Je.me(t.key, t), e.Xe.me(t, null));
      }
      /** Deletes a document with a given key */    delete(t) {
          const e = this.get(t);
          return e ? this.Ae(this.Je.remove(t), this.Xe.remove(e)) : this;
      }
      isEqual(t) {
          if (!(t instanceof ne)) return !1;
          if (this.size !== t.size) return !1;
          const e = this.Xe.be(), s = t.Xe.be();
          for (;e.$e(); ) {
              const t = e.Ne().key, i = s.Ne().key;
              if (!t.isEqual(i)) 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)";
      }
      Ae(t, e) {
          const s = new ne;
          return s.N = this.N, s.Je = t, s.Xe = e, 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.
   */
  /**
   * DocumentChangeSet keeps track of a set of changes to docs in a query, merging
   * duplicate events for the same doc.
   */ class re {
      constructor() {
          this.ts = new Ut(C.N);
      }
      track(t) {
          const e = t.doc.key, s = this.ts.get(e);
          s ? 
          // Merge the new change with the existing change.
          0 /* Added */ !== t.type && 3 /* Metadata */ === s.type ? this.ts = this.ts.me(e, t) : 3 /* Metadata */ === t.type && 1 /* Removed */ !== s.type ? this.ts = this.ts.me(e, {
              type: s.type,
              doc: t.doc
          }) : 2 /* Modified */ === t.type && 2 /* Modified */ === s.type ? this.ts = this.ts.me(e, {
              type: 2 /* Modified */ ,
              doc: t.doc
          }) : 2 /* Modified */ === t.type && 0 /* Added */ === s.type ? this.ts = this.ts.me(e, {
              type: 0 /* Added */ ,
              doc: t.doc
          }) : 1 /* Removed */ === t.type && 0 /* Added */ === s.type ? this.ts = this.ts.remove(e) : 1 /* Removed */ === t.type && 2 /* Modified */ === s.type ? this.ts = this.ts.me(e, {
              type: 1 /* Removed */ ,
              doc: s.doc
          }) : 0 /* Added */ === t.type && 1 /* Removed */ === s.type ? this.ts = this.ts.me(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
          be() : this.ts = this.ts.me(e, t);
      }
      es() {
          const t = [];
          return this.ts.pe((e, s) => {
              t.push(s);
          }), t;
      }
  }
  
  class he {
      constructor(t, e, s, i, n, r, h, o) {
          this.query = t, this.docs = e, this.ss = s, this.docChanges = i, this.ns = n, this.fromCache = r, 
          this.rs = h, this.hs = o;
      }
      /** Returns a view snapshot as if all documents in the snapshot were added. */    static os(t, e, s, i) {
          const n = [];
          return e.forEach(t => {
              n.push({
                  type: 0 /* Added */ ,
                  doc: t
              });
          }), new he(t, e, ne.Ze(e), n, s, i, 
          /* syncStateChanged= */ !0, 
          /* excludesMetadataChanges= */ !1);
      }
      get hasPendingWrites() {
          return !this.ns.B();
      }
      isEqual(t) {
          if (!(this.fromCache === t.fromCache && this.rs === t.rs && this.ns.isEqual(t.ns) && this.query.isEqual(t.query) && this.docs.isEqual(t.docs) && this.ss.isEqual(t.ss))) return !1;
          const e = this.docChanges, s = t.docChanges;
          if (e.length !== s.length) return !1;
          for (let t = 0; t < e.length; t++) if (e[t].type !== s[t].type || !e[t].doc.isEqual(s[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 oe {
      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.
       */
      s, 
      /**
       * A set of which documents have changed or been deleted, along with the
       * doc's new values (if not deleted).
       */
      i, 
      /**
       * A set of which document updates are due only to limbo resolution targets.
       */
      n) {
          this.Ee = t, this.as = e, this.us = s, this.cs = i, this._s = n;
      }
      /**
       * 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 ls(t, e) {
          const s = new Map;
          return s.set(t, ae.ds(t, e)), new oe(y.min(), s, ie(), zt(), ee());
      }
  }
  
  /**
   * 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 ae {
      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.
       */
      s, 
      /**
       * The set of documents that were already assigned to this target but received
       * an update during this remote event.
       */
      i, 
      /**
       * The set of documents that were removed from this target as part of this
       * remote event.
       */
      n) {
          this.resumeToken = t, this.fs = e, this.Ts = s, this.Es = i, this.Is = n;
      }
      /**
       * 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 ds(t, e) {
          return new ae(k.ht, e, ee(), ee(), ee());
      }
  }
  
  /**
   * @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 ue {
      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. */
      s, 
      /**
       * 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.
       */
      i) {
          this.ws = t, this.removedTargetIds = e, this.key = s, this.Rs = i;
      }
  }
  
  class ce {
      constructor(t, e) {
          this.targetId = t, this.ms = e;
      }
  }
  
  class _e {
      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.
       */
      s = k.ht
      /** An RPC error indicating why the watch failed. */ , i = null) {
          this.state = t, this.targetIds = e, this.resumeToken = s, this.cause = i;
      }
  }
  
  /** Tracks the internal state of a Watch target. */ class le {
      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.As = 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.Ps = Te(), 
          /** See public getters for explanations of these fields. */
          this.Vs = k.ht, this.gs = !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.ps = !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 fs() {
          return this.gs;
      }
      /** The last resume token sent to us for this target. */    get resumeToken() {
          return this.Vs;
      }
      /** Whether this target has pending target adds or target removes. */    get ys() {
          return 0 !== this.As;
      }
      /** Whether we have modified any state that should trigger a snapshot. */    get bs() {
          return this.ps;
      }
      /**
       * Applies the resume token to the TargetChange, but only when it has a new
       * value. Empty resumeTokens are discarded.
       */    vs(t) {
          t.rt() > 0 && (this.ps = !0, this.Vs = t);
      }
      /**
       * Creates a target change from the current set of changes.
       *
       * To reset the document changes after raising this snapshot, call
       * `clearPendingChanges()`.
       */    Ss() {
          let t = ee(), e = ee(), s = ee();
          return this.Ps.forEach((i, n) => {
              switch (n) {
                case 0 /* Added */ :
                  t = t.add(i);
                  break;
  
                case 2 /* Modified */ :
                  e = e.add(i);
                  break;
  
                case 1 /* Removed */ :
                  s = s.add(i);
                  break;
  
                default:
                  be();
              }
          }), new ae(this.Vs, this.gs, t, e, s);
      }
      /**
       * Resets the document changes and sets `hasPendingChanges` to false.
       */    Ds() {
          this.ps = !1, this.Ps = Te();
      }
      Cs(t, e) {
          this.ps = !0, this.Ps = this.Ps.me(t, e);
      }
      Fs(t) {
          this.ps = !0, this.Ps = this.Ps.remove(t);
      }
      Ns() {
          this.As += 1;
      }
      $s() {
          this.As -= 1;
      }
      ks() {
          this.ps = !0, this.gs = !0;
      }
  }
  
  /**
   * A helper class to accumulate watch changes into a RemoteEvent.
   */
  class de {
      constructor(t) {
          this.Ms = t, 
          /** The internal state of all tracked targets. */
          this.Ls = new Map, 
          /** Keeps track of the documents to update since the last raised snapshot. */
          this.Os = zt(), 
          /** A mapping of document keys to their set of target IDs. */
          this.xs = fe(), 
          /**
           * 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.Bs = new jt(Ce);
      }
      /**
       * Processes and adds the DocumentWatchChange to the current set of changes.
       */    qs(t) {
          for (const e of t.ws) t.Rs instanceof Vt ? this.Us(e, t.Rs) : t.Rs instanceof gt && this.Qs(e, t.key, t.Rs);
          for (const e of t.removedTargetIds) this.Qs(e, t.key, t.Rs);
      }
      /** Processes and adds the WatchTargetChange to the current set of changes. */    Ws(t) {
          this.js(t, e => {
              const s = this.Ks(e);
              switch (t.state) {
                case 0 /* NoChange */ :
                  this.Gs(e) && s.vs(t.resumeToken);
                  break;
  
                case 1 /* Added */ :
                  // We need to decrement the number of pending acks needed from watch
                  // for this targetId.
                  s.$s(), s.ys || 
                  // 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.
                  s.Ds(), s.vs(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.
                  s.$s(), s.ys || this.removeTarget(e);
                  break;
  
                case 3 /* Current */ :
                  this.Gs(e) && (s.ks(), s.vs(t.resumeToken));
                  break;
  
                case 4 /* Reset */ :
                  this.Gs(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.zs(e), s.vs(t.resumeToken));
                  break;
  
                default:
                  be();
              }
          });
      }
      /**
       * 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.
       */    js(t, e) {
          t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.Ls.forEach((t, s) => {
              this.Gs(s) && e(s);
          });
      }
      /**
       * Handles existence filters and synthesizes deletes for filter mismatches.
       * Targets that are invalidated by filter mismatches are added to
       * `pendingTargetResets`.
       */    Hs(t) {
          const e = t.targetId, s = t.ms.count, i = this.Ys(e);
          if (i) {
              const t = i.target;
              if (t.Ot()) if (0 === s) {
                  // 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 s = new C(t.path);
                  this.Qs(e, s, new gt(s, y.min()));
              } else ve(1 === s); else {
                  this.Js(e) !== s && (
                  // Existence filter mismatch: We reset the mapping and raise a new
                  // snapshot with `isFromCache:true`.
                  this.zs(e), this.Bs = this.Bs.add(e));
              }
          }
      }
      /**
       * Converts the currently accumulated state into a remote event at the
       * provided snapshot version. Resets the accumulated changes before returning.
       */    Xs(t) {
          const e = new Map;
          this.Ls.forEach((s, i) => {
              const n = this.Ys(i);
              if (n) {
                  if (s.fs && n.target.Ot()) {
                      // 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 C(n.target.path);
                      null !== this.Os.get(e) || this.Zs(i, e) || this.Qs(i, e, new gt(e, t));
                  }
                  s.bs && (e.set(i, s.Ss()), s.Ds());
              }
          });
          let s = ee();
          // 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.xs.forEach((t, e) => {
              let i = !0;
              e.Ge(t => {
                  const e = this.Ys(t);
                  return !e || 2 /* LimboResolution */ === e.Te || (i = !1, !1);
              }), i && (s = s.add(t));
          });
          const i = new oe(t, e, this.Bs, this.Os, s);
          return this.Os = zt(), this.xs = fe(), this.Bs = new jt(Ce), i;
      }
      /**
       * Adds the provided document to the internal list of document updates and
       * its document key to the given target's mapping.
       */
      // Visible for testing.
      Us(t, e) {
          if (!this.Gs(t)) return;
          const s = this.Zs(t, e.key) ? 2 /* Modified */ : 0 /* Added */;
          this.Ks(t).Cs(e.key, s), this.Os = this.Os.me(e.key, e), this.xs = this.xs.me(e.key, this.ti(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.
      Qs(t, e, s) {
          if (!this.Gs(t)) return;
          const i = this.Ks(t);
          this.Zs(t, e) ? i.Cs(e, 1 /* Removed */) : 
          // The document may have entered and left the target before we raised a
          // snapshot, so we can just ignore the change.
          i.Fs(e), this.xs = this.xs.me(e, this.ti(e).delete(t)), s && (this.Os = this.Os.me(e, s));
      }
      removeTarget(t) {
          this.Ls.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.
       */    Js(t) {
          const e = this.Ks(t).Ss();
          return this.Ms.ei(t).size + e.Ts.size - e.Is.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.
       */    Ns(t) {
          this.Ks(t).Ns();
      }
      Ks(t) {
          let e = this.Ls.get(t);
          return e || (e = new le, this.Ls.set(t, e)), e;
      }
      ti(t) {
          let e = this.xs.get(t);
          return e || (e = new jt(Ce), this.xs = this.xs.me(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.
       */    Gs(t) {
          const e = null !== this.Ys(t);
          return e || ge("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).
       */    Ys(t) {
          const e = this.Ls.get(t);
          return e && e.ys ? null : this.Ms.si(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).
       */    zs(t) {
          this.Ls.set(t, new le), this.Ms.ei(t).forEach(e => {
              this.Qs(t, e, /*updatedDocument=*/ null);
          });
      }
      /**
       * Returns whether the LocalStore considers the document to be part of the
       * specified target.
       */    Zs(t, e) {
          return this.Ms.ei(t).has(e);
      }
  }
  
  function fe() {
      return new Ut(C.N);
  }
  
  function Te() {
      return new Ut(C.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 Ee = (() => {
      const t = {
          asc: "ASCENDING",
          desc: "DESCENDING"
      };
      return t;
  })(), Ie = (() => {
      const t = {
          "<": "LESS_THAN",
          "<=": "LESS_THAN_OR_EQUAL",
          ">": "GREATER_THAN",
          ">=": "GREATER_THAN_OR_EQUAL",
          "==": "EQUAL",
          "array-contains": "ARRAY_CONTAINS",
          in: "IN",
          "array-contains-any": "ARRAY_CONTAINS_ANY"
      };
      return t;
  })();
  
  /**
   * Generates JsonObject values for the Datastore API suitable for sending to
   * either GRPC stub methods or via the JSON/HTTP REST API.
   * TODO(klimt): We can remove the databaseId argument if we keep the full
   * resource name in documents.
   */
  class we {
      constructor(t, e) {
          this.ii = t, this.options = e;
      }
      ni(t) {
          const e = void 0 === t.code ? w.UNKNOWN : qt(t.code);
          return new R(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.
       */    ri(t) {
          return this.options.hi || M(t) ? t : {
              value: t
          };
      }
      /**
       * Returns a number (or null) from a google.protobuf.Int32Value proto.
       */    oi(t) {
          let e;
          return e = "object" == typeof t ? t.value : t, M(e) ? null : e;
      }
      /**
       * Returns an IntegerValue for `value`.
       */    _t(t) {
          return {
              integerValue: "" + t
          };
      }
      /**
       * Returns an DoubleValue for `value` that is encoded based the serializer's
       * `useProto3Json` setting.
       */    lt(t) {
          if (this.options.hi) {
              if (isNaN(t)) return {
                  doubleValue: "NaN"
              };
              if (t === 1 / 0) return {
                  doubleValue: "Infinity"
              };
              if (t === -1 / 0) return {
                  doubleValue: "-Infinity"
              };
          }
          return {
              doubleValue: L(t) ? "-0" : 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.
       */    ai(t) {
          return O(t) ? this._t(t) : this.lt(t);
      }
      /**
       * Returns a value for a Date that's appropriate to put into a proto.
       */    C(t) {
          if (this.options.hi) {
              return `${new Date(1e3 * t.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + t.nanoseconds).slice(-9)}Z`;
          }
          return {
              seconds: "" + t.seconds,
              nanos: t.nanoseconds
          };
      }
      v(t) {
          const e = H(t);
          return new p(e.seconds, e.nanos);
      }
      /**
       * Returns a value for bytes that's appropriate to put in a proto.
       *
       * Visible for testing.
       */    ui(t) {
          return this.options.hi ? t.toBase64() : t.toUint8Array();
      }
      /**
       * Returns a ByteString based on the proto string value.
       */    ci(t) {
          return this.options.hi ? (ve(void 0 === t || "string" == typeof t), k.fromBase64String(t || "")) : (ve(void 0 === t || t instanceof Uint8Array), 
          k.fromUint8Array(t || new Uint8Array));
      }
      toVersion(t) {
          return this.C(t.C());
      }
      fromVersion(t) {
          return ve(!!t), y.v(this.v(t));
      }
      _i(t, e) {
          return this.li(e || this.ii).child("documents").child(t).j();
      }
      di(t) {
          const e = v.K(t);
          return ve(Re(e)), e;
      }
      fi(t) {
          return this._i(t.path);
      }
      Z(t) {
          const e = this.di(t);
          return ve(e.get(1) === this.ii.projectId), ve(!e.get(3) && !this.ii.database || e.get(3) === this.ii.database), 
          new C(this.Ti(e));
      }
      Ei(t) {
          return this._i(t);
      }
      Ii(t) {
          const e = this.di(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 ? v.G : this.Ti(e);
      }
      get wi() {
          return new v([ "projects", this.ii.projectId, "databases", this.ii.database ]).j();
      }
      li(t) {
          return new v([ "projects", t.projectId, "databases", t.database ]);
      }
      Ti(t) {
          return ve(t.length > 4 && "documents" === t.get(4)), t.k(5);
      }
      /** Creates an api.Document from key and fields (but no create/update time) */    Ri(t, e) {
          return {
              name: this.fi(t),
              fields: e.proto.mapValue.fields
          };
      }
      mi(t) {
          return {
              name: this.fi(t.key),
              fields: t.Mt().mapValue.fields,
              updateTime: this.C(t.version.C())
          };
      }
      Ai(t, e) {
          const s = this.Z(t.name), i = this.fromVersion(t.updateTime), n = new Rt({
              mapValue: {
                  fields: t.fields
              }
          });
          return new Vt(s, i, n, {
              hasCommittedMutations: !!e
          });
      }
      Pi(t) {
          ve(!!t.found), t.found.name, t.found.updateTime;
          const e = this.Z(t.found.name), s = this.fromVersion(t.found.updateTime), i = new Rt({
              mapValue: {
                  fields: t.found.fields
              }
          });
          return new Vt(e, s, i, {});
      }
      Vi(t) {
          ve(!!t.missing), ve(!!t.readTime);
          const e = this.Z(t.missing), s = this.fromVersion(t.readTime);
          return new gt(e, s);
      }
      gi(t) {
          return "found" in t ? this.Pi(t) : "missing" in t ? this.Vi(t) : be();
      }
      pi(t) {
          let e;
          if ("targetChange" in t) {
              t.targetChange;
              // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'
              // if unset
              const s = this.yi(t.targetChange.targetChangeType || "NO_CHANGE"), i = t.targetChange.targetIds || [], n = this.ci(t.targetChange.resumeToken), r = t.targetChange.cause, h = r && this.ni(r);
              e = new _e(s, i, n, h || null);
          } else if ("documentChange" in t) {
              t.documentChange;
              const s = t.documentChange;
              s.document, s.document.name, s.document.updateTime;
              const i = this.Z(s.document.name), n = this.fromVersion(s.document.updateTime), r = new Rt({
                  mapValue: {
                      fields: s.document.fields
                  }
              }), h = new Vt(i, n, r, {}), o = s.targetIds || [], a = s.removedTargetIds || [];
              e = new ue(o, a, h.key, h);
          } else if ("documentDelete" in t) {
              t.documentDelete;
              const s = t.documentDelete;
              s.document;
              const i = this.Z(s.document), n = s.readTime ? this.fromVersion(s.readTime) : y.min(), r = new gt(i, n), h = s.removedTargetIds || [];
              e = new ue([], h, r.key, r);
          } else if ("documentRemove" in t) {
              t.documentRemove;
              const s = t.documentRemove;
              s.document;
              const i = this.Z(s.document), n = s.removedTargetIds || [];
              e = new ue([], n, i, null);
          } else {
              if (!("filter" in t)) return be();
              {
                  t.filter;
                  const s = t.filter;
                  s.targetId;
                  const i = s.count || 0, n = new Lt(i), r = s.targetId;
                  e = new ce(r, n);
              }
          }
          return e;
      }
      yi(t) {
          return "NO_CHANGE" === t ? 0 /* NoChange */ : "ADD" === t ? 1 /* Added */ : "REMOVE" === t ? 2 /* Removed */ : "CURRENT" === t ? 3 /* Current */ : "RESET" === t ? 4 /* Reset */ : be();
      }
      bi(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 y.min();
          const e = t.targetChange;
          return e.targetIds && e.targetIds.length ? y.min() : e.readTime ? this.fromVersion(e.readTime) : y.min();
      }
      vi(t) {
          let e;
          if (t instanceof ft) e = {
              update: this.Ri(t.key, t.value)
          }; else if (t instanceof It) e = {
              delete: this.fi(t.key)
          }; else if (t instanceof Tt) e = {
              update: this.Ri(t.key, t.data),
              updateMask: this.Si(t.Vt)
          }; else if (t instanceof Et) e = {
              transform: {
                  document: this.fi(t.key),
                  fieldTransforms: t.fieldTransforms.map(t => this.Di(t))
              }
          }; else {
              if (!(t instanceof wt)) return be();
              e = {
                  verify: this.fi(t.key)
              };
          }
          return t.Rt.Tt || (e.currentDocument = this.Ci(t.Rt)), e;
      }
      Fi(t) {
          const e = t.currentDocument ? this.Ni(t.currentDocument) : lt.ft();
          if (t.update) {
              t.update.name;
              const s = this.Z(t.update.name), i = new Rt({
                  mapValue: {
                      fields: t.update.fields
                  }
              });
              if (t.updateMask) {
                  const n = this.$i(t.updateMask);
                  return new Tt(s, i, n, e);
              }
              return new ft(s, i, e);
          }
          if (t.delete) {
              const s = this.Z(t.delete);
              return new It(s, e);
          }
          if (t.transform) {
              const s = this.Z(t.transform.document), i = t.transform.fieldTransforms.map(t => this.ki(t));
              return ve(!0 === e.exists), new Et(s, i);
          }
          if (t.verify) {
              const s = this.Z(t.verify);
              return new wt(s, e);
          }
          return be();
      }
      Ci(t) {
          return void 0 !== t.updateTime ? {
              updateTime: this.toVersion(t.updateTime)
          } : void 0 !== t.exists ? {
              exists: t.exists
          } : be();
      }
      Ni(t) {
          return void 0 !== t.updateTime ? lt.updateTime(this.fromVersion(t.updateTime)) : void 0 !== t.exists ? lt.exists(t.exists) : lt.ft();
      }
      Mi(t, e) {
          // NOTE: Deletes don't have an updateTime.
          let s = t.updateTime ? this.fromVersion(t.updateTime) : this.fromVersion(e);
          s.isEqual(y.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
          s = this.fromVersion(e));
          let i = null;
          return t.transformResults && t.transformResults.length > 0 && (i = t.transformResults), 
          new _t(s, i);
      }
      Li(t, e) {
          return t && t.length > 0 ? (ve(void 0 !== e), t.map(t => this.Mi(t, e))) : [];
      }
      Di(t) {
          const e = t.transform;
          if (e instanceof nt) return {
              fieldPath: t.field.j(),
              setToServerValue: "REQUEST_TIME"
          };
          if (e instanceof rt) return {
              fieldPath: t.field.j(),
              appendMissingElements: {
                  values: e.elements
              }
          };
          if (e instanceof ht) return {
              fieldPath: t.field.j(),
              removeAllFromArray: {
                  values: e.elements
              }
          };
          if (e instanceof ot) return {
              fieldPath: t.field.j(),
              increment: e.ct
          };
          throw be();
      }
      ki(t) {
          let e = null;
          if ("setToServerValue" in t) ve("REQUEST_TIME" === t.setToServerValue), e = nt.instance; else if ("appendMissingElements" in t) {
              const s = t.appendMissingElements.values || [];
              e = new rt(s);
          } else if ("removeAllFromArray" in t) {
              const s = t.removeAllFromArray.values || [];
              e = new ht(s);
          } else "increment" in t ? e = new ot(this, t.increment) : be();
          const s = D.X(t.fieldPath);
          return new ct(s, e);
      }
      Oi(t) {
          return {
              documents: [ this.Ei(t.path) ]
          };
      }
      xi(t) {
          ve(1 === t.documents.length);
          const e = t.documents[0];
          return bt.Wt(this.Ii(e)).ee();
      }
      Bi(t) {
          // Dissect the path into parent, collectionId, and optional key filter.
          const e = {
              structuredQuery: {}
          }, s = t.path;
          null !== t.collectionGroup ? (e.parent = this.Ei(s), e.structuredQuery.from = [ {
              collectionId: t.collectionGroup,
              allDescendants: !0
          } ]) : (e.parent = this.Ei(s.M()), e.structuredQuery.from = [ {
              collectionId: s.O()
          } ]);
          const i = this.qi(t.filters);
          i && (e.structuredQuery.where = i);
          const n = this.Ui(t.orderBy);
          n && (e.structuredQuery.orderBy = n);
          const r = this.ri(t.limit);
          return null !== r && (e.structuredQuery.limit = r), t.startAt && (e.structuredQuery.startAt = this.Qi(t.startAt)), 
          t.endAt && (e.structuredQuery.endAt = this.Qi(t.endAt)), e;
      }
      Wi(t) {
          let e = this.Ii(t.parent);
          const s = t.structuredQuery, i = s.from ? s.from.length : 0;
          let n = null;
          if (i > 0) {
              ve(1 === i);
              const t = s.from[0];
              t.allDescendants ? n = t.collectionId : e = e.child(t.collectionId);
          }
          let r = [];
          s.where && (r = this.ji(s.where));
          let h = [];
          s.orderBy && (h = this.Ki(s.orderBy));
          let o = null;
          s.limit && (o = this.oi(s.limit));
          let a = null;
          s.startAt && (a = this.Gi(s.startAt));
          let u = null;
          return s.endAt && (u = this.Gi(s.endAt)), new bt(e, n, h, r, o, "F" /* First */ , a, u).ee();
      }
      zi(t) {
          const e = this.Hi(t.Te);
          return null == e ? null : {
              "goog-listen-tags": e
          };
      }
      Hi(t) {
          switch (t) {
            case 0 /* Listen */ :
              return null;
  
            case 1 /* ExistenceFilterMismatch */ :
              return "existence-filter-mismatch";
  
            case 2 /* LimboResolution */ :
              return "limbo-document";
  
            default:
              return be();
          }
      }
      ee(t) {
          let e;
          const s = t.target;
          return e = s.Ot() ? {
              documents: this.Oi(s)
          } : {
              query: this.Bi(s)
          }, e.targetId = t.targetId, t.resumeToken.rt() > 0 && (e.resumeToken = this.ui(t.resumeToken)), 
          e;
      }
      qi(t) {
          if (0 === t.length) return;
          const e = t.map(t => t instanceof vt ? this.Yi(t) : be());
          return 1 === e.length ? e[0] : {
              compositeFilter: {
                  op: "AND",
                  filters: e
              }
          };
      }
      ji(t) {
          return t ? void 0 !== t.unaryFilter ? [ this.Ji(t) ] : void 0 !== t.fieldFilter ? [ this.Xi(t) ] : void 0 !== t.compositeFilter ? t.compositeFilter.filters.map(t => this.ji(t)).reduce((t, e) => t.concat(e)) : be() : [];
      }
      Ui(t) {
          if (0 !== t.length) return t.map(t => this.Zi(t));
      }
      Ki(t) {
          return t.map(t => this.tn(t));
      }
      Qi(t) {
          return {
              before: t.before,
              values: t.position
          };
      }
      Gi(t) {
          const e = !!t.before, s = t.values || [];
          return new $t(s, e);
      }
      // visible for testing
      en(t) {
          return Ee[t];
      }
      // visible for testing
      sn(t) {
          switch (t) {
            case "ASCENDING":
              return "asc" /* ASCENDING */;
  
            case "DESCENDING":
              return "desc" /* DESCENDING */;
  
            default:
              return;
          }
      }
      // visible for testing
      nn(t) {
          return Ie[t];
      }
      rn(t) {
          switch (t) {
            case "EQUAL":
              return "==" /* 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 "ARRAY_CONTAINS_ANY":
              return "array-contains-any" /* ARRAY_CONTAINS_ANY */;
  
            case "OPERATOR_UNSPECIFIED":
            default:
              return be();
          }
      }
      hn(t) {
          return {
              fieldPath: t.j()
          };
      }
      on(t) {
          return D.X(t.fieldPath);
      }
      // visible for testing
      Zi(t) {
          return {
              field: this.hn(t.field),
              direction: this.en(t.dir)
          };
      }
      tn(t) {
          return new kt(this.on(t.field), this.sn(t.direction));
      }
      Xi(t) {
          return vt.create(this.on(t.fieldFilter.field), this.rn(t.fieldFilter.op), t.fieldFilter.value);
      }
      // visible for testing
      Yi(t) {
          if ("==" /* EQUAL */ === t.op) {
              if (st(t.value)) return {
                  unaryFilter: {
                      field: this.hn(t.field),
                      op: "IS_NAN"
                  }
              };
              if (et(t.value)) return {
                  unaryFilter: {
                      field: this.hn(t.field),
                      op: "IS_NULL"
                  }
              };
          }
          return {
              fieldFilter: {
                  field: this.hn(t.field),
                  op: this.nn(t.op),
                  value: t.value
              }
          };
      }
      Ji(t) {
          switch (t.unaryFilter.op) {
            case "IS_NAN":
              const e = this.on(t.unaryFilter.field);
              return vt.create(e, "==" /* EQUAL */ , {
                  doubleValue: NaN
              });
  
            case "IS_NULL":
              const s = this.on(t.unaryFilter.field);
              return vt.create(s, "==" /* EQUAL */ , {
                  nullValue: "NULL_VALUE"
              });
  
            case "OPERATOR_UNSPECIFIED":
            default:
              return be();
          }
      }
      Si(t) {
          const e = [];
          return t.fields.forEach(t => e.push(t.j())), {
              fieldPaths: e
          };
      }
      $i(t) {
          const e = t.fieldPaths || [];
          return new ut(e.map(t => D.X(t)));
      }
  }
  
  function Re(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.
   */
  /**
   * Provides singleton helpers where setup code can inject a platform at runtime.
   * setPlatform needs to be set before Firestore is used and must be set exactly
   * once.
   */ class me {
      static an(t) {
          me.platform && be(), me.platform = t;
      }
      static nt() {
          return me.platform || be(), me.platform;
      }
  }
  
  /**
   * @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 Ae = new e("@firebase/firestore");
  
  // Helper methods are needed because variables can't be exported as read/write
  function Pe() {
      return Ae.logLevel;
  }
  
  function Ve(t) {
      Ae.logLevel = t;
  }
  
  function ge(t, ...e) {
      if (Ae.logLevel <= s.DEBUG) {
          const s = e.map(ye);
          Ae.debug(`Firestore (${E}): ${t}`, ...s);
      }
  }
  
  function pe(t, ...e) {
      if (Ae.logLevel <= s.ERROR) {
          const s = e.map(ye);
          Ae.error(`Firestore (${E}): ${t}`, ...s);
      }
  }
  
  /**
   * Converts an additional log parameter to a string representation.
   */ function ye(t) {
      if ("string" == typeof t) return t;
      {
          const e = me.nt();
          try {
              return e.un(t);
          } catch (e) {
              // Converting to JSON failed, just log the object directly
              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.
   */
  /**
   * 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 be(t = "Unexpected state") {
      // Log the failure in addition to throw an exception, just in case the
      // exception is swallowed.
      const e = `FIRESTORE (${E}) 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 pe(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 ve(t, e) {
      t || be();
  }
  
  /**
   * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
   * instance of `T` before casting.
   */ function Se(t, 
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  e) {
      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.
   */ class De {
      static cn() {
          // 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 s = "";
          for (;s.length < 20; ) {
              const i = me.nt()._n(40);
              for (let n = 0; n < i.length; ++n) 
              // Only accept values that are [0, maxMultiple), this ensures they can
              // be evenly mapped to indices of `chars` via a modulo operation.
              s.length < 20 && i[n] < e && (s += t.charAt(i[n] % t.length));
          }
          return s;
      }
  }
  
  function Ce(t, e) {
      return t < e ? -1 : t > e ? 1 : 0;
  }
  
  /** Helper to compare arrays using isEqual(). */ function Fe(t, e, s) {
      return t.length === e.length && t.every((t, i) => s(t, e[i]));
  }
  
  /**
   * Returns the immediate lexicographically-following string. This is useful to
   * construct an inclusive range for indexeddb iterators.
   */ function Ne(t) {
      // Return the input string, with an additional NUL byte appended.
      return t + "\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.
   */ class $e {
      /**
       * 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.
       */
      constructor(t, e, s, i, n) {
          this.ii = t, this.persistenceKey = e, this.host = s, this.ssl = i, this.forceLongPolling = n;
      }
  }
  
  /** The default database name for a project. */
  /** Represents the database ID a Firestore client is associated with. */
  class ke {
      constructor(t, e) {
          this.projectId = t, this.database = e || "(default)";
      }
      get ln() {
          return "(default)" === this.database;
      }
      isEqual(t) {
          return t instanceof ke && t.projectId === this.projectId && t.database === this.database;
      }
      S(t) {
          return Ce(this.projectId, t.projectId) || Ce(this.database, t.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.
   */
  /**
   * A map implementation that uses objects as keys. Objects must implement the
   * Equatable interface 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.
   */ class Me {
      constructor(t) {
          this.dn = t, 
          /**
           * 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.fn = {};
      }
      /** Get a value for this key, or undefined if it does not exist. */    get(t) {
          const e = this.dn(t), s = this.fn[e];
          if (void 0 !== s) for (const [e, i] of s) if (e.isEqual(t)) return i;
      }
      has(t) {
          return void 0 !== this.get(t);
      }
      /** Put this key and value in the map. */    set(t, e) {
          const s = this.dn(t), i = this.fn[s];
          if (void 0 !== i) {
              for (let s = 0; s < i.length; s++) if (i[s][0].isEqual(t)) return void (i[s] = [ t, e ]);
              i.push([ t, e ]);
          } else this.fn[s] = [ [ t, e ] ];
      }
      /**
       * Remove this key from the map. Returns a boolean if anything was deleted.
       */    delete(t) {
          const e = this.dn(t), s = this.fn[e];
          if (void 0 === s) return !1;
          for (let i = 0; i < s.length; i++) if (s[i][0].isEqual(t)) return 1 === s.length ? delete this.fn[e] : s.splice(i, 1), 
          !0;
          return !1;
      }
      forEach(t) {
          N(this.fn, (e, s) => {
              for (const [e, i] of s) t(e, i);
          });
      }
      B() {
          return $(this.fn);
      }
  }
  
  /**
   * @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 Le {
      /**
       * @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, s, i) {
          this.batchId = t, this.Tn = e, this.baseMutations = s, this.mutations = i;
      }
      /**
       * 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.
       */    at(t, e, s) {
          const i = s.En;
          for (let s = 0; s < this.mutations.length; s++) {
              const n = this.mutations[s];
              if (n.key.isEqual(t)) {
                  const t = i[s];
                  e = n.at(e, t);
              }
          }
          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.
       */    ot(t, e) {
          // First, apply the base state. This allows us to apply non-idempotent
          // transform against a consistent set of values.
          for (const s of this.baseMutations) s.key.isEqual(t) && (e = s.ot(e, e, this.Tn));
          const s = e;
          // Second, apply all user-provided mutations.
                  for (const i of this.mutations) i.key.isEqual(t) && (e = i.ot(e, s, this.Tn));
          return e;
      }
      /**
       * Computes the local view for all provided documents given the mutations in
       * this batch.
       */    In(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(s => {
              const i = this.ot(s.key, t.get(s.key));
              i && (e = e.me(s.key, i));
          }), e;
      }
      keys() {
          return this.mutations.reduce((t, e) => t.add(e.key), ee());
      }
      isEqual(t) {
          return this.batchId === t.batchId && Fe(this.mutations, t.mutations, (t, e) => t.isEqual(e)) && Fe(this.baseMutations, t.baseMutations, (t, e) => t.isEqual(e));
      }
  }
  
  /** The result of applying a mutation batch to the backend. */ class Oe {
      constructor(t, e, s, i, 
      /**
       * A pre-computed mapping from each mutated document to the resulting
       * version.
       */
      n) {
          this.batch = t, this.wn = e, this.En = s, this.streamToken = i, this.Rn = n;
      }
      /**
       * 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=>version mapping (docVersions).
       */    static from(t, e, s, i) {
          ve(t.mutations.length === s.length);
          let n = Zt();
          const r = t.mutations;
          for (let t = 0; t < r.length; t++) n = n.me(r[t].key, s[t].version);
          return new Oe(t, e, s, i, 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.
   */
  /**
   * 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 xe {
      constructor(t) {
          // NOTE: next/catchCallback will always point to our own wrapper functions,
          // not the user's raw next() or catch() callbacks.
          this.mn = null, this.An = null, 
          // When the operation resolves, we'll set result or error and mark isDone.
          this.result = void 0, this.error = void 0, this.Pn = !1, 
          // Set to true when .then() or .catch() are called and prevents additional
          // chaining.
          this.Vn = !1, t(t => {
              this.Pn = !0, this.result = t, this.mn && 
              // value should be defined unless T is Void, but we can't express
              // that in the type system.
              this.mn(t);
          }, t => {
              this.Pn = !0, this.error = t, this.An && this.An(t);
          });
      }
      catch(t) {
          return this.next(void 0, t);
      }
      next(t, e) {
          return this.Vn && be(), this.Vn = !0, this.Pn ? this.error ? this.gn(e, this.error) : this.pn(t, this.result) : new xe((s, i) => {
              this.mn = e => {
                  this.pn(t, e).next(s, i);
              }, this.An = t => {
                  this.gn(e, t).next(s, i);
              };
          });
      }
      yn() {
          return new Promise((t, e) => {
              this.next(t, e);
          });
      }
      bn(t) {
          try {
              const e = t();
              return e instanceof xe ? e : xe.resolve(e);
          } catch (t) {
              return xe.reject(t);
          }
      }
      pn(t, e) {
          return t ? this.bn(() => t(e)) : xe.resolve(e);
      }
      gn(t, e) {
          return t ? this.bn(() => t(e)) : xe.reject(e);
      }
      static resolve(t) {
          return new xe((e, s) => {
              e(t);
          });
      }
      static reject(t) {
          return new xe((e, s) => {
              s(t);
          });
      }
      static vn(
      // Accept all Promise types in waitFor().
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      t) {
          return new xe((e, s) => {
              let i = 0, n = 0, r = !1;
              t.forEach(t => {
                  ++i, t.next(() => {
                      ++n, r && n === i && e();
                  }, t => s(t));
              }), r = !0, n === i && 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 Sn(t) {
          let e = xe.resolve(!1);
          for (const s of t) e = e.next(t => t ? xe.resolve(t) : s());
          return e;
      }
      static forEach(t, e) {
          const s = [];
          return t.forEach((t, i) => {
              s.push(e.call(this, t, i));
          }), this.vn(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.
   */
  /**
   * 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 Be {
      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.Dn = new Me(t => t.toString()), this.Cn = !1;
      }
      set readTime(t) {
          this.Fn = t;
      }
      get readTime() {
          return this.Fn;
      }
      /**
       * Buffers a `RemoteDocumentCache.addEntry()` call.
       *
       * You can only modify documents that have already been retrieved via
       * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
       */    Nn(t, e) {
          this.$n(), this.readTime = e, this.Dn.set(t.key, t);
      }
      /**
       * Buffers a `RemoteDocumentCache.removeEntry()` call.
       *
       * You can only remove documents that have already been retrieved via
       * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
       */    kn(t, e) {
          this.$n(), e && (this.readTime = e), this.Dn.set(t, null);
      }
      /**
       * 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.
       * @return The cached Document or NoDocument entry, or null if we have nothing
       * cached.
       */    Mn(t, e) {
          this.$n();
          const s = this.Dn.get(e);
          return void 0 !== s ? xe.resolve(s) : this.Ln(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.
       * @return 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.On(t, e);
      }
      /**
       * Applies buffered changes to the underlying RemoteDocumentCache, using
       * the provided transaction.
       */    apply(t) {
          return this.$n(), this.Cn = !0, this.xn(t);
      }
      /** Helper to assert this.changes is not null  */    $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 qe = "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 Ue {
      constructor() {
          this.Bn = [];
      }
      qn(t) {
          this.Bn.push(t);
      }
      Un() {
          this.Bn.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.
   */
  /**
   * 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 Qe {
      constructor(t, e, s) {
          this.Qn = t, this.Wn = e, this.jn = s;
      }
      /**
       * Get the local view of the document identified by `key`.
       *
       * @return Local view of the document or null if we don't have any cached
       * state for it.
       */    Kn(t, e) {
          return this.Wn.Gn(t, e).next(s => this.zn(t, e, s));
      }
      /** Internal version of `getDocument` that allows reusing batches. */    zn(t, e, s) {
          return this.Qn.Mn(t, e).next(t => {
              for (const i of s) t = i.ot(e, t);
              return t;
          });
      }
      // Returns the view of the given `docs` as they would appear after applying
      // all mutations in the given `batches`.
      Hn(t, e, s) {
          let i = Ht();
          return e.forEach((t, e) => {
              for (const i of s) e = i.ot(t, e);
              i = i.me(t, e);
          }), i;
      }
      /**
       * 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.
       */    Yn(t, e) {
          return this.Qn.getEntries(t, e).next(e => this.Jn(t, e));
      }
      /**
       * Similar to `getDocuments`, but creates the local view from the given
       * `baseDocs` without retrieving documents from the local store.
       */    Jn(t, e) {
          return this.Wn.Xn(t, e).next(s => {
              const i = this.Hn(t, e, s);
              let n = zt();
              return i.forEach((t, e) => {
                  // TODO(http://b/32275378): Don't conflate missing / deleted.
                  e || (e = new gt(t, y.min())), n = n.me(t, e);
              }), n;
          });
      }
      /**
       * 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).
       */    Zn(t, e, s) {
          return e.Ot() ? this.tr(t, e.path) : e._e() ? this.er(t, e, s) : this.sr(t, e, s);
      }
      tr(t, e) {
          // Just do a simple document lookup.
          return this.Kn(t, new C(e)).next(t => {
              let e = Jt();
              return t instanceof Vt && (e = e.me(t.key, t)), e;
          });
      }
      er(t, e, s) {
          const i = e.collectionGroup;
          let n = Jt();
          return this.jn.ir(t, i).next(r => xe.forEach(r, r => {
              const h = e.Zt(r.child(i));
              return this.sr(t, h, s).next(t => {
                  t.forEach((t, e) => {
                      n = n.me(t, e);
                  });
              });
          }).next(() => n));
      }
      sr(t, e, s) {
          // Query the remote documents and overlay mutations.
          let i, n;
          return this.Qn.Zn(t, e, s).next(s => (i = s, this.Wn.nr(t, e))).next(e => (n = e, 
          this.rr(t, n, i).next(t => {
              i = t;
              for (const t of n) for (const e of t.mutations) {
                  const s = e.key, n = i.get(s), r = e.ot(n, n, t.Tn);
                  i = r instanceof Vt ? i.me(s, r) : i.remove(s);
              }
          }))).next(() => (
          // Finally, filter out any documents that don't actually match
          // the query.
          i.forEach((t, s) => {
              e.matches(s) || (i = i.remove(t));
          }), i));
      }
      rr(t, e, s) {
          let i = ee();
          for (const t of e) for (const e of t.mutations) e instanceof Tt && null === s.get(e.key) && (i = i.add(e.key));
          let n = s;
          return this.Qn.getEntries(t, i).next(t => (t.forEach((t, e) => {
              null !== e && e instanceof Vt && (n = n.me(t, 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.
   */
  /**
   * 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 We {
      constructor(t, e, s, i) {
          this.targetId = t, this.fromCache = e, this.hr = s, this.or = i;
      }
      static ar(t, e) {
          let s = ee(), i = ee();
          for (const t of e.docChanges) switch (t.type) {
            case 0 /* Added */ :
              s = s.add(t.doc.key);
              break;
  
            case 1 /* Removed */ :
              i = i.add(t.doc.key);
   // do nothing
                  }
          return new We(t, e.fromCache, s, i);
      }
  }
  
  /**
   * @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 je {
      constructor(t, e) {
          this.previousValue = t, e && (e.ur = t => this.cr(t), this._r = t => e.lr(t));
      }
      cr(t) {
          return this.previousValue = Math.max(t, this.previousValue), this.previousValue;
      }
      next() {
          const t = ++this.previousValue;
          return this._r && this._r(t), t;
      }
  }
  
  je.dr = -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 Ke {
      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.
   */
  /**
   * 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 Ge {
      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.
       */
      s = 1e3
      /**
       * The multiplier to use to determine the extended base delay after each
       * attempt.
       */ , i = 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.
       */ , n = 6e4) {
          this.Tr = t, this.Er = e, this.Ir = s, this.wr = i, this.Rr = n, this.mr = 0, this.Ar = null, 
          /** The last backoff attempt, as epoch milliseconds. */
          this.Pr = 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.mr = 0;
      }
      /**
       * Resets the backoff delay to the maximum delay (e.g. for use after a
       * RESOURCE_EXHAUSTED error).
       */    Vr() {
          this.mr = this.Rr;
      }
      /**
       * 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.
       */    gr(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.mr + this.pr()), s = Math.max(0, Date.now() - this.Pr), i = Math.max(0, e - s);
          // Guard against lastAttemptTime being in the future due to a clock change.
                  i > 0 && ge("ExponentialBackoff", `Backing off for ${i} ms ` + `(base delay: ${this.mr} ms, ` + `delay with jitter: ${e} ms, ` + `last attempt: ${s} ms ago)`), 
          this.Ar = this.Tr.yr(this.Er, i, () => (this.Pr = Date.now(), t())), 
          // Apply backoff factor to determine next delay and ensure it is within
          // bounds.
          this.mr *= this.wr, this.mr < this.Ir && (this.mr = this.Ir), this.mr > this.Rr && (this.mr = this.Rr);
      }
      cancel() {
          null !== this.Ar && (this.Ar.cancel(), this.Ar = null);
      }
      /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */    pr() {
          return (Math.random() - .5) * this.mr;
      }
  }
  
  /**
   * @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 ze(t) {
      let e = "";
      for (let s = 0; s < t.length; s++) e.length > 0 && (e = Ye(e)), e = He(t.get(s), e);
      return Ye(e);
  }
  
  /** Encodes a single segment of a resource path into the given result */ function He(t, e) {
      let s = e;
      const i = t.length;
      for (let e = 0; e < i; e++) {
          const i = t.charAt(e);
          switch (i) {
            case "\0":
              s += "";
              break;
  
            case "":
              s += "";
              break;
  
            default:
              s += i;
          }
      }
      return s;
  }
  
  /** Encodes a path separator into the given result */ function Ye(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 Je(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 (ve(e >= 2), 2 === e) return ve("" === t.charAt(0) && "" === t.charAt(1)), 
      v.G;
      // Escape characters cannot exist past the second-to-last position in the
      // source value.
          const s = e - 2, i = [];
      let n = "";
      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);
          switch ((e < 0 || e > s) && be(), t.charAt(e + 1)) {
            case "":
              const s = t.substring(r, e);
              let h;
              0 === n.length ? 
              // Avoid copying for the common case of a segment that excludes \0
              // and \001
              h = s : (n += s, h = n, n = ""), i.push(h);
              break;
  
            case "":
              n += t.substring(r, e), n += "\0";
              break;
  
            case "":
              // The escape character can be used in the output to encode itself.
              n += t.substring(r, e + 1);
              break;
  
            default:
              be();
          }
          r = e + 2;
      }
      return new v(i);
  }
  
  /**
   * @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 Xe {
      constructor() {
          this.br = new Ze;
      }
      vr(t, e) {
          return this.br.add(e), xe.resolve();
      }
      ir(t, e) {
          return xe.resolve(this.br.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 Ze {
      constructor() {
          this.index = {};
      }
      // Returns false if the entry already existed.
      add(t) {
          const e = t.O(), s = t.M(), i = this.index[e] || new jt(v.N), n = !i.has(s);
          return this.index[e] = i.add(s), n;
      }
      has(t) {
          const e = t.O(), s = t.M(), i = this.index[e];
          return i && i.has(s);
      }
      getEntries(t) {
          return (this.index[t] || new jt(v.N)).W();
      }
  }
  
  /**
   * @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 ts {
      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.Sr = new Ze;
      }
      /**
       * 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.
       */    vr(t, e) {
          if (!this.Sr.has(e)) {
              const s = e.O(), i = e.M();
              t.qn(() => {
                  // Add the collection to the in memory cache only if the transaction was
                  // successfully committed.
                  this.Sr.add(e);
              });
              const n = {
                  collectionId: s,
                  parent: ze(i)
              };
              return es(t).put(n);
          }
          return xe.resolve();
      }
      ir(t, e) {
          const s = [], i = IDBKeyRange.bound([ e, "" ], [ Ne(e), "" ], 
          /*lowerOpen=*/ !1, 
          /*upperOpen=*/ !0);
          return es(t).Dr(i).next(t => {
              for (const i 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 (i.collectionId !== e) break;
                  s.push(Je(i.parent));
              }
              return s;
          });
      }
  }
  
  /**
   * Helper to get a typed SimpleDbStore for the collectionParents
   * document store.
   */ function es(t) {
      return Es.Cr(t, qs.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.
   */ class ss {
      /**
       * @param {LocalSerializer} serializer The document serializer.
       * @param {IndexManager} indexManager The query indexes that need to be maintained.
       */
      constructor(t, e) {
          this.serializer = t, this.jn = 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.
       */    Nn(t, e, s) {
          return ns(t).put(rs(e), s);
      }
      /**
       * 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.
       */    kn(t, e) {
          const s = ns(t), i = rs(e);
          return s.delete(i);
      }
      /**
       * 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(s => (s.byteSize += e, this.Fr(t, s)));
      }
      Mn(t, e) {
          return ns(t).get(rs(e)).next(t => this.Nr(t));
      }
      /**
       * Looks up an entry in the cache.
       *
       * @param documentKey The key of the entry to look up.
       * @return The cached MaybeDocument entry and its size, or null if we have nothing cached.
       */    $r(t, e) {
          return ns(t).get(rs(e)).next(t => {
              const e = this.Nr(t);
              return e ? {
                  kr: e,
                  size: hs(t)
              } : null;
          });
      }
      getEntries(t, e) {
          let s = Ht();
          return this.Mr(t, e, (t, e) => {
              const i = this.Nr(e);
              s = s.me(t, i);
          }).next(() => s);
      }
      /**
       * Looks up several entries in the cache.
       *
       * @param documentKeys The set of keys entries to look up.
       * @return 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).
       */    Lr(t, e) {
          let s = Ht(), i = new Ut(C.N);
          return this.Mr(t, e, (t, e) => {
              const n = this.Nr(e);
              n ? (s = s.me(t, n), i = i.me(t, hs(e))) : (s = s.me(t, null), i = i.me(t, 0));
          }).next(() => ({
              Or: s,
              xr: i
          }));
      }
      Mr(t, e, s) {
          if (e.B()) return xe.resolve();
          const i = IDBKeyRange.bound(e.first().path.W(), e.last().path.W()), n = e.be();
          let r = n.Ne();
          return ns(t).Br({
              range: i
          }, (t, e, i) => {
              const h = C.st(t);
              // Go through keys not found in cache.
                          for (;r && C.N(r, h) < 0; ) s(r, null), r = n.Ne();
              r && r.isEqual(h) && (
              // Key found in cache.
              s(r, e), r = n.$e() ? n.Ne() : null), 
              // Skip to the next key (if there is one).
              r ? i.qr(r.path.W()) : i.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; ) s(r, null), r = n.$e() ? n.Ne() : null;
          });
      }
      Zn(t, e, s) {
          let i = Jt();
          const n = e.path.length + 1, r = {};
          if (s.isEqual(y.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.W();
              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.W(), i = this.serializer.Ur(s);
              r.range = IDBKeyRange.lowerBound([ t, i ], 
              /* open= */ !0), r.index = Ms.collectionReadTimeIndex;
          }
          return ns(t).Br(r, (t, s, 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 !== n) return;
              const h = this.serializer.Qr(s);
              e.path.q(h.key.path) ? h instanceof Vt && e.matches(h) && (i = i.me(h.key, h)) : r.done();
          }).next(() => i);
      }
      /**
       * Returns the set of documents that have changed since the specified read
       * time.
       */
      // PORTING NOTE: This is only used for multi-tab synchronization.
      Wr(t, e) {
          let s = zt(), i = this.serializer.Ur(e);
          const n = ns(t), r = IDBKeyRange.lowerBound(i, !0);
          return n.Br({
              index: Ms.readTimeIndex,
              range: r
          }, (t, e) => {
              // Unlike `getEntry()` and others, `getNewDocumentChanges()` parses
              // the documents directly since we want to keep sentinel deletes.
              const n = this.serializer.Qr(e);
              s = s.me(n.key, n), i = e.readTime;
          }).next(() => ({
              jr: s,
              readTime: this.serializer.Kr(i)
          }));
      }
      /**
       * 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.
      Gr(t) {
          const e = ns(t);
          // If there are no existing entries, we return SnapshotVersion.min().
                  let s = y.min();
          return e.Br({
              index: Ms.readTimeIndex,
              reverse: !0
          }, (t, e, i) => {
              e.readTime && (s = this.serializer.Kr(e.readTime)), i.done();
          }).next(() => s);
      }
      zr(t) {
          return new ss.Hr(this, !!t && t.Yr);
      }
      Jr(t) {
          return this.getMetadata(t).next(t => t.byteSize);
      }
      getMetadata(t) {
          return is(t).get(Ls.key).next(t => (ve(!!t), t));
      }
      Fr(t, e) {
          return is(t).put(Ls.key, e);
      }
      /**
       * Decodes `remoteDoc` and returns the document (or null, if the document
       * corresponds to the format used for sentinel deletes).
       */    Nr(t) {
          if (t) {
              const e = this.serializer.Qr(t);
              return e instanceof gt && e.version.isEqual(y.min()) ? null : e;
          }
          return null;
      }
  }
  
  /**
   * 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.
   */ function is(t) {
      return Es.Cr(t, Ls.store);
  }
  
  /**
   * Helper to get a typed SimpleDbStore for the remoteDocuments object store.
   */ function ns(t) {
      return Es.Cr(t, Ms.store);
  }
  
  function rs(t) {
      return t.path.W();
  }
  
  /**
   * Retrusn an approximate size for the given document.
   */ function hs(t) {
      let e;
      if (t.document) e = t.document; else if (t.unknownDocument) e = t.unknownDocument; else {
          if (!t.noDocument) throw be();
          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.
   */
  /** Offset to ensure non-overlapping target ids. */ ss.Hr = class extends Be {
      /**
       * @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.Xr = t, this.Yr = e, 
          // A map of document sizes prior to applying the changes in this buffer.
          this.Zr = new Me(t => t.toString());
      }
      xn(t) {
          const e = [];
          let s = 0, i = new jt((t, e) => Ce(t.j(), e.j()));
          return this.Dn.forEach((n, r) => {
              const h = this.Zr.get(n);
              if (r) {
                  const o = this.Xr.serializer.th(r, this.readTime);
                  i = i.add(n.path.M());
                  const a = hs(o);
                  s += a - h, e.push(this.Xr.Nn(t, n, o));
              } else if (s -= h, this.Yr) {
                  // 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 s = this.Xr.serializer.th(new gt(n, y.min()), this.readTime);
                  e.push(this.Xr.Nn(t, n, s));
              } else e.push(this.Xr.kn(t, n));
          }), i.forEach(s => {
              e.push(this.Xr.jn.vr(t, s));
          }), e.push(this.Xr.updateMetadata(t, s)), xe.vn(e);
      }
      Ln(t, e) {
          // Record the size of everything we load from the cache so we can compute a delta later.
          return this.Xr.$r(t, e).next(t => null === t ? (this.Zr.set(e, 0), null) : (this.Zr.set(e, t.size), 
          t.kr));
      }
      On(t, e) {
          // Record the size of everything we load from the cache so we can compute
          // a delta later.
          return this.Xr.Lr(t, e).next(({Or: t, xr: 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));
      }
  };
  
  /**
   * 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 os {
      constructor(t) {
          this.eh = t;
      }
      next() {
          return this.eh += 2, this.eh;
      }
      static sh() {
          // 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 os(0);
      }
      static ih() {
          // Sync engine assigns target IDs for limbo document detection.
          return new os(-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 as {
      constructor(t, e) {
          this.nh = t, this.serializer = 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.
      rh(t) {
          return this.hh(t).next(e => {
              const s = new os(e.highestTargetId);
              return e.highestTargetId = s.next(), this.oh(t, e).next(() => e.highestTargetId);
          });
      }
      ah(t) {
          return this.hh(t).next(t => y.v(new p(t.lastRemoteSnapshotVersion.seconds, t.lastRemoteSnapshotVersion.nanoseconds)));
      }
      uh(t) {
          return _s(t._h);
      }
      lh(t, e, s) {
          return this.hh(t).next(i => (i.highestListenSequenceNumber = e, s && (i.lastRemoteSnapshotVersion = s.C()), 
          e > i.highestListenSequenceNumber && (i.highestListenSequenceNumber = e), this.oh(t, i)));
      }
      dh(t, e) {
          return this.fh(t, e).next(() => this.hh(t).next(s => (s.targetCount += 1, this.Th(e, s), 
          this.oh(t, s))));
      }
      Eh(t, e) {
          return this.fh(t, e);
      }
      Ih(t, e) {
          return this.wh(t, e.targetId).next(() => us(t).delete(e.targetId)).next(() => this.hh(t)).next(e => (ve(e.targetCount > 0), 
          e.targetCount -= 1, this.oh(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.
       */    Rh(t, e, s) {
          let i = 0;
          const n = [];
          return us(t).Br((r, h) => {
              const o = this.serializer.mh(h);
              o.sequenceNumber <= e && null === s.get(o.targetId) && (i++, n.push(this.Ih(t, o)));
          }).next(() => xe.vn(n)).next(() => i);
      }
      /**
       * Call provided function with each `TargetData` that we have cached.
       */    js(t, e) {
          return us(t).Br((t, s) => {
              const i = this.serializer.mh(s);
              e(i);
          });
      }
      hh(t) {
          return cs(t._h);
      }
      oh(t, e) {
          return (s = t, Es.Cr(s, Bs.store)).put(Bs.key, e);
          /**
   * Helper to get a typed SimpleDbStore for the target globals object store.
   */
          var s;
      }
      fh(t, e) {
          return us(t).put(this.serializer.Ah(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.
       */    Th(t, e) {
          let s = !1;
          return t.targetId > e.highestTargetId && (e.highestTargetId = t.targetId, s = !0), 
          t.sequenceNumber > e.highestListenSequenceNumber && (e.highestListenSequenceNumber = t.sequenceNumber, 
          s = !0), s;
      }
      Ph(t) {
          return this.hh(t).next(t => t.targetCount);
      }
      Vh(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 s = e.canonicalId(), i = IDBKeyRange.bound([ s, Number.NEGATIVE_INFINITY ], [ s, Number.POSITIVE_INFINITY ]);
          let n = null;
          return us(t).Br({
              range: i,
              index: Os.queryTargetsIndexName
          }, (t, s, i) => {
              const r = this.serializer.mh(s);
              // After finding a potential match, check that the target is
              // actually equal to the requested target.
                          e.isEqual(r.target) && (n = r, i.done());
          }).next(() => n);
      }
      gh(t, e, s) {
          // PORTING NOTE: The reverse index (documentsTargets) is maintained by
          // IndexedDb.
          const i = [], n = ls(t);
          return e.forEach(e => {
              const r = ze(e.path);
              i.push(n.put(new xs(s, r))), i.push(this.nh.ph(t, s, e));
          }), xe.vn(i);
      }
      yh(t, e, s) {
          // PORTING NOTE: The reverse index (documentsTargets) is maintained by
          // IndexedDb.
          const i = ls(t);
          return xe.forEach(e, e => {
              const n = ze(e.path);
              return xe.vn([ i.delete([ s, n ]), this.nh.bh(t, s, e) ]);
          });
      }
      wh(t, e) {
          const s = ls(t), i = IDBKeyRange.bound([ e ], [ e + 1 ], 
          /*lowerOpen=*/ !1, 
          /*upperOpen=*/ !0);
          return s.delete(i);
      }
      vh(t, e) {
          const s = IDBKeyRange.bound([ e ], [ e + 1 ], 
          /*lowerOpen=*/ !1, 
          /*upperOpen=*/ !0), i = ls(t);
          let n = ee();
          return i.Br({
              range: s,
              Sh: !0
          }, (t, e, s) => {
              const i = Je(t[1]), r = new C(i);
              n = n.add(r);
          }).next(() => n);
      }
      Dh(t, e) {
          const s = ze(e.path), i = IDBKeyRange.bound([ s ], [ Ne(s) ], 
          /*lowerOpen=*/ !1, 
          /*upperOpen=*/ !0);
          let n = 0;
          return ls(t).Br({
              index: xs.documentTargetsIndex,
              Sh: !0,
              range: i
          }, ([t, e], s, i) => {
              // 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 && (n++, i.done());
          }).next(() => n > 0);
      }
      /**
       * Looks up a TargetData entry by target ID.
       *
       * @param targetId The target ID of the TargetData entry to look up.
       * @return The cached TargetData entry, or null if the cache has no entry for
       * the target.
       */
      // PORTING NOTE: Multi-tab only.
      si(t, e) {
          return us(t).get(e).next(t => t ? this.serializer.mh(t) : null);
      }
  }
  
  /**
   * Helper to get a typed SimpleDbStore for the queries object store.
   */ function us(t) {
      return Es.Cr(t, Os.store);
  }
  
  function cs(t) {
      return js.Cr(t, Bs.store).get(Bs.key).next(t => (ve(null !== t), t));
  }
  
  function _s(t) {
      return cs(t).next(t => t.highestListenSequenceNumber);
  }
  
  /**
   * Helper to get a typed SimpleDbStore for the document target object store.
   */ function ls(t) {
      return Es.Cr(t, xs.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.
   */
  /** Serializer for values stored in the LocalStore. */ class ds {
      constructor(t) {
          this.Ch = t;
      }
      /** Decodes a remote document from storage locally to a Document. */    Qr(t) {
          if (t.document) return this.Ch.Ai(t.document, !!t.hasCommittedMutations);
          if (t.noDocument) {
              const e = C.st(t.noDocument.path), s = this.Fh(t.noDocument.readTime);
              return new gt(e, s, {
                  hasCommittedMutations: !!t.hasCommittedMutations
              });
          }
          if (t.unknownDocument) {
              const e = C.st(t.unknownDocument.path), s = this.Fh(t.unknownDocument.version);
              return new pt(e, s);
          }
          return be();
      }
      /** Encodes a document for storage locally. */    th(t, e) {
          const s = this.Ur(e), i = t.key.path.M().W();
          if (t instanceof Vt) {
              const e = this.Ch.mi(t), n = t.hasCommittedMutations;
              return new Ms(
              /* unknownDocument= */ null, 
              /* noDocument= */ null, e, n, s, i);
          }
          if (t instanceof gt) {
              const e = t.key.path.W(), n = this.Nh(t.version), r = t.hasCommittedMutations;
              return new Ms(
              /* unknownDocument= */ null, new $s(e, n), 
              /* document= */ null, r, s, i);
          }
          if (t instanceof pt) {
              const e = t.key.path.W(), n = this.Nh(t.version);
              return new Ms(new ks(e, n), 
              /* noDocument= */ null, 
              /* document= */ null, 
              /* hasCommittedMutations= */ !0, s, i);
          }
          return be();
      }
      Ur(t) {
          const e = t.C();
          return [ e.seconds, e.nanoseconds ];
      }
      Kr(t) {
          const e = new p(t[0], t[1]);
          return y.v(e);
      }
      Nh(t) {
          const e = t.C();
          return new Ss(e.seconds, e.nanoseconds);
      }
      Fh(t) {
          const e = new p(t.seconds, t.nanoseconds);
          return y.v(e);
      }
      /** Encodes a batch of mutations into a DbMutationBatch for local storage. */    $h(t, e) {
          const s = e.baseMutations.map(t => this.Ch.vi(t)), i = e.mutations.map(t => this.Ch.vi(t));
          return new Fs(t, e.batchId, e.Tn.toMillis(), s, i);
      }
      /** Decodes a DbMutationBatch into a MutationBatch */    kh(t) {
          const e = (t.baseMutations || []).map(t => this.Ch.Fi(t)), s = t.mutations.map(t => this.Ch.Fi(t)), i = p.fromMillis(t.localWriteTimeMs);
          return new Le(t.batchId, i, e, s);
      }
      /** Decodes a DbTarget into TargetData */    mh(t) {
          const e = this.Fh(t.readTime), s = void 0 !== t.lastLimboFreeSnapshotVersion ? this.Fh(t.lastLimboFreeSnapshotVersion) : y.min();
          let i;
          return i = void 0 !== t.query.documents ? this.Ch.xi(t.query) : this.Ch.Wi(t.query), 
          new Mt(i, t.targetId, 0 /* Listen */ , t.lastListenSequenceNumber, e, s, k.fromBase64String(t.resumeToken));
      }
      /** Encodes TargetData into a DbTarget for storage locally. */    Ah(t) {
          const e = this.Nh(t.Ee), s = this.Nh(t.lastLimboFreeSnapshotVersion);
          let i;
          i = t.target.Ot() ? this.Ch.Oi(t.target) : this.Ch.Bi(t.target);
          // We can't store the resumeToken as a ByteString in IndexedDb, so we
          // convert it to a base64 string for storage.
                  const n = t.resumeToken.toBase64();
          // lastListenSequenceNumber is always 0 until we do real GC.
                  return new Os(t.targetId, t.target.canonicalId(), e, n, t.sequenceNumber, s, i);
      }
  }
  
  /**
   * A helper function for figuring out what kind of query has been stored.
   */
  /**
   * @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 fs = "Failed to obtain exclusive access to the persistence layer. To allow shared access, make sure to invoke `enablePersistence()` with `synchronizeTabs:true` in all tabs.";
  
  /**
   * Oldest acceptable age in milliseconds for client metadata before the client
   * is considered inactive and its associated data is garbage collected.
   */ class Ts extends Ue {
      constructor(t, e) {
          super(), this._h = t, this.Mh = e;
      }
  }
  
  /**
   * 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 Es {
      constructor(t, e, s, i, n, r, h, o) {
          if (this.allowTabSynchronization = t, this.persistenceKey = e, this.clientId = s, 
          this.Tr = r, this.Lh = o, this.Oh = null, this.xh = !1, this.isPrimary = !1, this.networkEnabled = !0, 
          /** Our window.unload handler, if registered. */
          this.Bh = null, this.inForeground = !1, 
          /** Our 'visibilitychange' listener if registered. */
          this.qh = null, 
          /** The client metadata refresh task. */
          this.Uh = null, 
          /** The last time we garbage collected the client metadata object store. */
          this.Qh = Number.NEGATIVE_INFINITY, 
          /** A listener to notify on primary state changes. */
          this.Wh = t => Promise.resolve(), !Es.jh()) throw new R(w.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");
          if (this.nh = new Rs(this, n), this.Kh = e + Es.Gh, this.serializer = new ds(h), 
          this.document = i.document, this.zh = new as(this.nh, this.serializer), this.jn = new ts, 
          this.Qn = new ss(this.serializer, this.jn), !i.window || !i.window.localStorage) throw new R(w.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
          this.window = i.window, this.Hh = this.window.localStorage;
      }
      static Cr(t, e) {
          if (t instanceof Ts) return js.Cr(t._h, e);
          throw be();
      }
      /**
       * Attempt to start IndexedDb persistence.
       *
       * @return {Promise<void>} Whether persistence was enabled.
       */    start() {
          return js.Yh(this.Kh, bs, new vs(this.serializer)).then(t => (this.Jh = t, this.Xh())).then(() => {
              if (!this.isPrimary && !this.allowTabSynchronization) 
              // Fail `start()` if `synchronizeTabs` is disabled and we cannot
              // obtain the primary lease.
              throw new R(w.FAILED_PRECONDITION, fs);
              return this.Zh(), this.to(), this.eo(), this.Jh.runTransaction("readonly", [ Bs.store ], t => _s(t));
          }).then(t => {
              this.Oh = new je(t, this.Lh);
          }).then(() => {
              this.xh = !0;
          }).catch(t => (this.Jh && this.Jh.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.
       */    so(t) {
          return this.Wh = async e => {
              if (this.io) 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.
       */    no(t) {
          this.Jh.ro(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.
       */    ho(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.Tr.oo(async () => {
              this.io && await this.Xh();
          }));
      }
      /**
       * 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.
       */    Xh() {
          return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", t => ws(t).put(new Qs(this.clientId, Date.now(), this.networkEnabled, this.inForeground)).next(() => {
              if (this.isPrimary) return this.ao(t).next(t => {
                  t || (this.isPrimary = !1, this.Tr.oo(() => this.Wh(!1)));
              });
          }).next(() => this.uo(t)).next(e => this.isPrimary && !e ? this.co(t).next(() => !1) : !!e && this._o(t).next(() => !0))).catch(t => {
              if (!this.allowTabSynchronization) {
                  if (zs(t)) 
                  // Proceed with the existing state. Any subsequent access to
                  // IndexedDB will verify the lease.
                  return ge("IndexedDbPersistence", "Failed to extend owner lease: ", t), this.isPrimary;
                  throw t;
              }
              return ge("IndexedDbPersistence", "Releasing owner lease after error during lease refresh", t), 
              /* isPrimary= */ !1;
          }).then(t => {
              this.isPrimary !== t && this.Tr.oo(() => this.Wh(t)), this.isPrimary = t;
          });
      }
      ao(t) {
          return Is(t).get(Ds.key).next(t => xe.resolve(this.lo(t)));
      }
      do(t) {
          return ws(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 fo() {
          if (this.isPrimary && !this.To(this.Qh, 18e5)) {
              this.Qh = Date.now(), 
              // 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.
              (await this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", t => {
                  const e = Es.Cr(t, Qs.store);
                  return e.Dr().next(t => {
                      const s = this.Eo(t, 18e5), i = t.filter(t => -1 === s.indexOf(t));
                      // Delete metadata for clients that are no longer considered active.
                      return xe.forEach(i, t => e.delete(t.clientId)).next(() => i);
                  });
              }).catch(() => [])).forEach(t => {
                  this.window.localStorage.removeItem(this.Io(t.clientId));
              });
          }
      }
      /**
       * Schedules a recurring timer to update the client metadata and to either
       * extend or acquire the primary lease if the client is eligible.
       */    eo() {
          this.Uh = this.Tr.yr("client_metadata_refresh" /* ClientMetadataRefresh */ , 4e3, () => this.Xh().then(() => this.fo()).then(() => this.eo()));
      }
      /** Checks whether `client` is the local client. */    lo(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.
       */    uo(t) {
          return Is(t).get(Ds.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.
              if (null !== e && this.To(e.leaseTimestampMs, 5e3) && !this.wo(e.ownerId)) {
                  if (this.lo(e) && this.networkEnabled) return !0;
                  if (!this.lo(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 R(w.FAILED_PRECONDITION, fs);
                      return !1;
                  }
              }
              return !(!this.networkEnabled || !this.inForeground) || ws(t).Dr().next(t => void 0 === this.Eo(t, 5e3).find(t => {
                  if (this.clientId !== t.clientId) {
                      const e = !this.networkEnabled && t.networkEnabled, s = !this.inForeground && t.inForeground, i = this.networkEnabled === t.networkEnabled;
                      if (e || s && i) return !0;
                  }
                  return !1;
              }));
          }).next(t => (this.isPrimary !== t && ge("IndexedDbPersistence", `Client ${t ? "is" : "is not"} eligible for a primary lease.`), 
          t));
      }
      async Ro() {
          // The shutdown() operations are idempotent and can be called even when
          // start() aborted (e.g. because it couldn't acquire the persistence lease).
          this.xh = !1, this.mo(), this.Uh && (this.Uh.cancel(), this.Uh = null), this.Ao(), 
          this.Po(), await this.runTransaction("shutdown", "readwrite", t => this.co(t).next(() => this.do(t))).catch(t => {
              ge("IndexedDbPersistence", "Proceeding with shutdown despite failure: ", t);
          }), this.Jh.close(), 
          // Remove the entry marking the client as zombied from LocalStorage since
          // we successfully deleted its metadata from IndexedDb.
          this.Vo();
      }
      /**
       * Returns clients that are not zombied and have an updateTime within the
       * provided threshold.
       */    Eo(t, e) {
          return t.filter(t => this.To(t.updateTimeMs, e) && !this.wo(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.
       */    po() {
          return this.runTransaction("getActiveClients", "readonly", t => ws(t).Dr().next(t => this.Eo(t, 18e5).map(t => t.clientId)));
      }
      static async clearPersistence(t) {
          if (!Es.jh()) return Promise.resolve();
          const e = t + Es.Gh;
          await js.delete(e);
      }
      get io() {
          return this.xh;
      }
      yo(t) {
          return As.bo(t, this.serializer, this.jn, this.nh);
      }
      vo() {
          return this.zh;
      }
      So() {
          return this.Qn;
      }
      Do() {
          return this.jn;
      }
      runTransaction(t, e, s) {
          ge("IndexedDbPersistence", "Starting transaction:", t);
          const i = "readonly" === e ? "readonly" : "readwrite";
          let n;
          // Do all transactions as readwrite against all object stores, since we
          // are the only reader/writer.
                  return this.Jh.runTransaction(i, Ws, i => (n = new Ts(i, this.Oh ? this.Oh.next() : je.dr), 
          "readwrite-primary" === e ? this.ao(n).next(t => !!t || this.uo(n)).next(e => {
              if (!e) throw pe(`Failed to obtain primary lease for action '${t}'.`), this.isPrimary = !1, 
              this.Tr.oo(() => this.Wh(!1)), new R(w.FAILED_PRECONDITION, qe);
              return s(n);
          }).next(t => this._o(n).next(() => t)) : this.Co(n).next(() => s(n)))).then(t => (n.Un(), 
          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.
      Co(t) {
          return Is(t).get(Ds.key).next(t => {
              if (null !== t && this.To(t.leaseTimestampMs, 5e3) && !this.wo(t.ownerId) && !this.lo(t) && (!this.allowTabSynchronization || !t.allowTabSynchronization)) throw new R(w.FAILED_PRECONDITION, fs);
          });
      }
      /**
       * Obtains or extends the new primary lease for the local client. This
       * method does not verify that the client is eligible for this lease.
       */    _o(t) {
          const e = new Ds(this.clientId, this.allowTabSynchronization, Date.now());
          return Is(t).put(Ds.key, e);
      }
      static jh() {
          return js.jh();
      }
      /**
       * Generates a string used as a prefix when storing data in IndexedDB and
       * LocalStorage.
       */    static Fo(t) {
          // 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 e = t.ii.projectId;
          return t.ii.ln || (e += "." + t.ii.database), "firestore/" + t.persistenceKey + "/" + e + "/";
      }
      /** Checks the primary lease and removes it if we are the current primary. */    co(t) {
          const e = Is(t);
          return e.get(Ds.key).next(t => this.lo(t) ? (ge("IndexedDbPersistence", "Releasing primary lease."), 
          e.delete(Ds.key)) : xe.resolve());
      }
      /** Verifies that `updateTimeMs` is within `maxAgeMs`. */    To(t, e) {
          const s = Date.now();
          return !(t < s - e) && (!(t > s) || (pe(`Detected an update time that is in the future: ${t} > ${s}`), 
          !1));
      }
      Zh() {
          null !== this.document && "function" == typeof this.document.addEventListener && (this.qh = () => {
              this.Tr.oo(() => (this.inForeground = "visible" === this.document.visibilityState, 
              this.Xh()));
          }, this.document.addEventListener("visibilitychange", this.qh), this.inForeground = "visible" === this.document.visibilityState);
      }
      Ao() {
          this.qh && (this.document.removeEventListener("visibilitychange", this.qh), this.qh = 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.
       */    to() {
          "function" == typeof this.window.addEventListener && (this.Bh = () => {
              // 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.mo(), this.Tr.oo(() => this.Ro());
          }, this.window.addEventListener("unload", this.Bh));
      }
      Po() {
          this.Bh && (this.window.removeEventListener("unload", this.Bh), this.Bh = 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()`.
       */    wo(t) {
          try {
              const e = null !== this.Hh.getItem(this.Io(t));
              return ge("IndexedDbPersistence", `Client '${t}' ${e ? "is" : "is not"} zombied in LocalStorage`), 
              e;
          } catch (t) {
              // Gracefully handle if LocalStorage isn't working.
              return pe("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.
       */    mo() {
          try {
              this.Hh.setItem(this.Io(this.clientId), String(Date.now()));
          } catch (t) {
              // Gracefully handle if LocalStorage isn't available / working.
              pe("Failed to set zombie client id.", t);
          }
      }
      /** Removes the zombied client entry if it exists. */    Vo() {
          try {
              this.Hh.removeItem(this.Io(this.clientId));
          } catch (t) {
              // Ignore
          }
      }
      Io(t) {
          return `firestore_zombie_${this.persistenceKey}_${t}`;
      }
  }
  
  /**
   * The name of the main (and currently only) IndexedDB database. this name is
   * appended to the prefix provided to the IndexedDbPersistence constructor.
   */
  /**
   * Helper to get a typed SimpleDbStore for the primary client object store.
   */
  function Is(t) {
      return Es.Cr(t, Ds.store);
  }
  
  /**
   * Helper to get a typed SimpleDbStore for the client metadata object store.
   */ function ws(t) {
      return Es.Cr(t, Qs.store);
  }
  
  /** Provides LRU functionality for IndexedDB persistence. */ Es.Gh = "main";
  
  class Rs {
      constructor(t, e) {
          this.db = t, this.No = new ai(this, e);
      }
      $o(t) {
          const e = this.ko(t);
          return this.db.vo().Ph(t).next(t => e.next(e => t + e));
      }
      ko(t) {
          let e = 0;
          return this.Mo(t, t => {
              e++;
          }).next(() => e);
      }
      js(t, e) {
          return this.db.vo().js(t, e);
      }
      Mo(t, e) {
          return this.Lo(t, (t, s) => e(s));
      }
      ph(t, e, s) {
          return ms(t, s);
      }
      bh(t, e, s) {
          return ms(t, s);
      }
      Rh(t, e, s) {
          return this.db.vo().Rh(t, e, s);
      }
      Oo(t, e) {
          return ms(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.
       */    xo(t, e) {
          /** Returns true if any mutation queue contains the given document. */
          return function(t, e) {
              let s = !1;
              return ys(t).Bo(i => Ps(t, i, e).next(t => (t && (s = !0), xe.resolve(!t)))).next(() => s);
          }
          /**
   * Delete a mutation batch and the associated document mutations.
   * @return A PersistencePromise of the document mutations that were removed.
   */ (t, e);
      }
      qo(t, e) {
          const s = this.db.So().zr(), i = [];
          let n = 0;
          return this.Lo(t, (r, h) => {
              if (h <= e) {
                  const e = this.xo(t, r).next(e => {
                      if (!e) 
                      // Our size accounting requires us to read all documents before
                      // removing them.
                      return n++, s.Mn(t, r).next(() => (s.kn(r), ls(t).delete([ 0, ze(r.path) ])));
                  });
                  i.push(e);
              }
          }).next(() => xe.vn(i)).next(() => s.apply(t)).next(() => n);
      }
      removeTarget(t, e) {
          const s = e.Ie(t.Mh);
          return this.db.vo().Eh(t, s);
      }
      Uo(t, e) {
          return ms(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.
       */    Lo(t, e) {
          const s = ls(t);
          let i, n = je.dr;
          return s.Br({
              index: xs.documentTargetsIndex
          }, ([t, s], {path: r, sequenceNumber: h}) => {
              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.
              n !== je.dr && e(new C(Je(i)), n), 
              // 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.
              n = h, i = r) : 
              // set nextToReport to be invalid, we know we don't need to report
              // this one since we found a target for it.
              n = je.dr;
          }).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.
              n !== je.dr && e(new C(Je(i)), n);
          });
      }
      Qo(t) {
          return this.db.So().Jr(t);
      }
  }
  
  function ms(t, e) {
      return ls(t).put(
      /**
   * @return A value suitable for writing a sentinel row in the target-document
   * store.
   */
      function(t, e) {
          return new xs(0, ze(t.path), e);
      }(e, t.Mh));
  }
  
  /**
   * @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 As {
      constructor(
      /**
       * The normalized userId (e.g. null UID => "" userId) used to store /
       * retrieve mutations.
       */
      t, e, s, i) {
          this.userId = t, this.serializer = e, this.jn = s, this.nh = i, 
          /**
           * 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.Wo = {};
      }
      /**
       * 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 bo(t, e, s, i) {
          // 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.
          ve("" !== t.uid);
          const n = t.t() ? t.uid : "";
          return new As(n, e, s, i);
      }
      jo(t) {
          let e = !0;
          const s = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);
          return gs(t).Br({
              index: Fs.userMutationsIndex,
              range: s
          }, (t, s, i) => {
              e = !1, i.done();
          }).next(() => e);
      }
      Ko(t, e, s) {
          return this.Go(t).next(e => (
          // We can't store the resumeToken as a ByteString in IndexedDB, so we
          // convert it to a Base64 string for storage.
          e.lastStreamToken = s.toBase64(), ys(t).put(e)));
      }
      zo(t) {
          return this.Go(t).next(t => k.fromBase64String(t.lastStreamToken));
      }
      Ho(t, e) {
          return this.Go(t).next(s => (
          // We can't store the resumeToken as a ByteString in IndexedDB, so we
          // convert it to a Base64 string for storage.
          s.lastStreamToken = e.toBase64(), ys(t).put(s)));
      }
      Yo(t, e, s, i) {
          const n = ps(t), r = gs(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(h => {
              ve("number" == typeof h);
              const o = new Le(h, e, s, i), a = this.serializer.$h(this.userId, o), u = [];
              let c = new jt((t, e) => Ce(t.j(), e.j()));
              for (const t of i) {
                  const e = Ns.key(this.userId, t.key.path, h);
                  c = c.add(t.key.path.M()), u.push(r.put(a)), u.push(n.put(e, Ns.PLACEHOLDER));
              }
              return c.forEach(e => {
                  u.push(this.jn.vr(t, e));
              }), t.qn(() => {
                  this.Wo[h] = o.keys();
              }), xe.vn(u).next(() => o);
          });
      }
      Jo(t, e) {
          return gs(t).get(e).next(t => t ? (ve(t.userId === this.userId), this.serializer.kh(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.
      Xo(t, e) {
          return this.Wo[e] ? xe.resolve(this.Wo[e]) : this.Jo(t, e).next(t => {
              if (t) {
                  const s = t.keys();
                  return this.Wo[e] = s, s;
              }
              return null;
          });
      }
      Zo(t, e) {
          const s = e + 1, i = IDBKeyRange.lowerBound([ this.userId, s ]);
          let n = null;
          return gs(t).Br({
              index: Fs.userMutationsIndex,
              range: i
          }, (t, e, i) => {
              e.userId === this.userId && (ve(e.batchId >= s), n = this.serializer.kh(e)), i.done();
          }).next(() => n);
      }
      ta(t) {
          const e = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);
          let s = -1;
          return gs(t).Br({
              index: Fs.userMutationsIndex,
              range: e,
              reverse: !0
          }, (t, e, i) => {
              s = e.batchId, i.done();
          }).next(() => s);
      }
      ea(t) {
          const e = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);
          return gs(t).Dr(Fs.userMutationsIndex, e).next(t => t.map(t => this.serializer.kh(t)));
      }
      Gn(t, e) {
          // Scan the document-mutation index starting with a prefix starting with
          // the given documentKey.
          const s = Ns.prefixForPath(this.userId, e.path), i = IDBKeyRange.lowerBound(s), n = [];
          return ps(t).Br({
              range: i
          }, (s, i, r) => {
              const [h, o, a] = s, u = Je(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.
                          if (h === this.userId && e.path.isEqual(u)) 
              // Look up the mutation batch in the store.
              return gs(t).get(a).next(t => {
                  if (!t) throw be();
                  ve(t.userId === this.userId), n.push(this.serializer.kh(t));
              });
              r.done();
          }).next(() => n);
      }
      Xn(t, e) {
          let s = new jt(Ce);
          const i = [];
          return e.forEach(e => {
              const n = Ns.prefixForPath(this.userId, e.path), r = IDBKeyRange.lowerBound(n), h = ps(t).Br({
                  range: r
              }, (t, i, n) => {
                  const [r, h, o] = t, a = Je(h);
                  // 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) ? s = s.add(o) : n.done();
              });
              i.push(h);
          }), xe.vn(i).next(() => this.sa(t, s));
      }
      nr(t, e) {
          const s = e.path, i = s.length + 1, n = Ns.prefixForPath(this.userId, s), r = IDBKeyRange.lowerBound(n);
          // 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 h = new jt(Ce);
          return ps(t).Br({
              range: r
          }, (t, e, n) => {
              const [r, o, a] = t, u = Je(o);
              r === this.userId && s.q(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 === i && (h = h.add(a)) : n.done();
          }).next(() => this.sa(t, h));
      }
      sa(t, e) {
          const s = [], i = [];
          // TODO(rockwood): Implement this using iterate.
          return e.forEach(e => {
              i.push(gs(t).get(e).next(t => {
                  if (null === t) throw be();
                  ve(t.userId === this.userId), s.push(this.serializer.kh(t));
              }));
          }), xe.vn(i).next(() => s);
      }
      ia(t, e) {
          return Vs(t._h, this.userId, e).next(s => (t.qn(() => {
              this.na(e.batchId);
          }), xe.forEach(s, e => this.nh.Oo(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
      na(t) {
          delete this.Wo[t];
      }
      ra(t) {
          return this.jo(t).next(e => {
              if (!e) return xe.resolve();
              // Verify that there are no entries in the documentMutations index if
              // the queue is empty.
                          const s = IDBKeyRange.lowerBound(Ns.prefixForUser(this.userId)), i = [];
              return ps(t).Br({
                  range: s
              }, (t, e, s) => {
                  if (t[0] === this.userId) {
                      const e = Je(t[1]);
                      i.push(e);
                  } else s.done();
              }).next(() => {
                  ve(0 === i.length);
              });
          });
      }
      Dh(t, e) {
          return Ps(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. */
      Go(t) {
          return ys(t).get(this.userId).next(t => t || new Cs(this.userId, -1, 
          /*lastStreamToken=*/ ""));
      }
  }
  
  /**
   * @return true if the mutation queue for the given user contains a pending
   *         mutation for the given key.
   */ function Ps(t, e, s) {
      const i = Ns.prefixForPath(e, s.path), n = i[1], r = IDBKeyRange.lowerBound(i);
      let h = !1;
      return ps(t).Br({
          range: r,
          Sh: !0
      }, (t, s, i) => {
          const [r, o, /*batchID*/ a] = t;
          r === e && o === n && (h = !0), i.done();
      }).next(() => h);
  }
  
  function Vs(t, e, s) {
      const i = t.store(Fs.store), n = t.store(Ns.store), r = [], h = IDBKeyRange.only(s.batchId);
      let o = 0;
      const a = i.Br({
          range: h
      }, (t, e, s) => (o++, s.delete()));
      r.push(a.next(() => {
          ve(1 === o);
      }));
      const u = [];
      for (const t of s.mutations) {
          const i = Ns.key(e, t.key.path, s.batchId);
          r.push(n.delete(i)), u.push(t.key);
      }
      return xe.vn(r).next(() => u);
  }
  
  /**
   * Helper to get a typed SimpleDbStore for the mutations object store.
   */ function gs(t) {
      return Es.Cr(t, Fs.store);
  }
  
  /**
   * Helper to get a typed SimpleDbStore for the mutationQueues object store.
   */ function ps(t) {
      return Es.Cr(t, Ns.store);
  }
  
  /**
   * Helper to get a typed SimpleDbStore for the mutationQueues object store.
   */ function ys(t) {
      return Es.Cr(t, Cs.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.
   */
  /**
   * 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.
   */ const bs = 10;
  
  /** Performs database creation and schema upgrades. */ class vs {
      constructor(t) {
          this.serializer = 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.
       */    createOrUpgrade(t, e, s, i) {
          ve(s < i && s >= 0 && i <= bs);
          const n = new Hs(e);
          s < 1 && i >= 1 && (function(t) {
              t.createObjectStore(Ds.store);
          }
          /**
   * 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.
   */ (t), function(t) {
              t.createObjectStore(Cs.store, {
                  keyPath: Cs.keyPath
              }), t.createObjectStore(Fs.store, {
                  keyPath: Fs.keyPath,
                  autoIncrement: !0
              }).createIndex(Fs.userMutationsIndex, Fs.userMutationsKeyPath, {
                  unique: !0
              }), t.createObjectStore(Ns.store);
          }
          /**
   * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads
   * and rewrites all data.
   */ (t), Us(t), function(t) {
              t.createObjectStore(Ms.store);
          }
          /**
   * Represents the known absence of a document at a particular version.
   * Stored in IndexedDb as part of a DbRemoteDocument object.
   */ (t));
          // Migration 2 to populate the targetGlobal object no longer needed since
          // migration 3 unconditionally clears it.
                  let r = xe.resolve();
          return s < 3 && i >= 3 && (
          // Brand new clients don't need to drop and recreate--only clients that
          // potentially have corrupt data.
          0 !== s && (!function(t) {
              t.deleteObjectStore(xs.store), t.deleteObjectStore(Os.store), t.deleteObjectStore(Bs.store);
          }(t), Us(t)), r = r.next(() => 
          /**
   * Creates the target global singleton row.
   *
   * @param {IDBTransaction} txn The version upgrade transaction for indexeddb
   */
          function(t) {
              const e = t.store(Bs.store), s = new Bs(
              /*highestTargetId=*/ 0, 
              /*lastListenSequenceNumber=*/ 0, y.min().C(), 
              /*targetCount=*/ 0);
              return e.put(Bs.key, s);
          }
          /**
   * Creates indices on the RemoteDocuments store used for both multi-tab
   * and Index-Free queries.
   */ (n))), s < 4 && i >= 4 && (0 !== s && (
          // 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(Fs.store).Dr().next(s => {
                  t.deleteObjectStore(Fs.store), t.createObjectStore(Fs.store, {
                      keyPath: Fs.keyPath,
                      autoIncrement: !0
                  }).createIndex(Fs.userMutationsIndex, Fs.userMutationsKeyPath, {
                      unique: !0
                  });
                  const i = e.store(Fs.store), n = s.map(t => i.put(t));
                  return xe.vn(n);
              });
          }
          /**
   * 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.
   */ (t, n))), r = r.next(() => {
              !function(t) {
                  t.createObjectStore(Qs.store, {
                      keyPath: Qs.keyPath
                  });
              }
              // Visible for testing
              (t);
          })), s < 5 && i >= 5 && (r = r.next(() => this.removeAcknowledgedMutations(n))), 
          s < 6 && i >= 6 && (r = r.next(() => (function(t) {
              t.createObjectStore(Ls.store);
          }
          /**
   * 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.
   */ (t), this.addDocumentGlobal(n)))), s < 7 && i >= 7 && (r = r.next(() => this.ensureSequenceNumbers(n))), 
          s < 8 && i >= 8 && (r = r.next(() => this.createCollectionParentIndex(t, n))), s < 9 && i >= 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(Ms.store);
                  e.createIndex(Ms.readTimeIndex, Ms.readTimeIndexPath, {
                      unique: !1
                  }), e.createIndex(Ms.collectionReadTimeIndex, Ms.collectionReadTimeIndexPath, {
                      unique: !1
                  });
              }
              /**
   * 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.
   */ (e);
          })), s < 10 && i >= 10 && (r = r.next(() => this.rewriteCanonicalIds(n))), r;
      }
      addDocumentGlobal(t) {
          let e = 0;
          return t.store(Ms.store).Br((t, s) => {
              e += hs(s);
          }).next(() => {
              const s = new Ls(e);
              return t.store(Ls.store).put(Ls.key, s);
          });
      }
      removeAcknowledgedMutations(t) {
          const e = t.store(Cs.store), s = t.store(Fs.store);
          return e.Dr().next(e => xe.forEach(e, e => {
              const i = IDBKeyRange.bound([ e.userId, -1 ], [ e.userId, e.lastAcknowledgedBatchId ]);
              return s.Dr(Fs.userMutationsIndex, i).next(s => xe.forEach(s, s => {
                  ve(s.userId === e.userId);
                  const i = this.serializer.kh(s);
                  return Vs(t, e.userId, i).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.
       */    ensureSequenceNumbers(t) {
          const e = t.store(xs.store), s = t.store(Ms.store);
          return _s(t).next(t => {
              const i = [];
              return s.Br((s, n) => {
                  const r = new v(s), h = function(t) {
                      return [ 0, ze(t) ];
                  }
                  /**
   * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.
   */ (r);
                  i.push(e.get(h).next(s => s ? xe.resolve() : (s => e.put(new xs(0, ze(s), t)))(r)));
              }).next(() => xe.vn(i));
          });
      }
      createCollectionParentIndex(t, e) {
          // Create the index.
          t.createObjectStore(qs.store, {
              keyPath: qs.keyPath
          });
          const s = e.store(qs.store), i = new Ze, n = t => {
              if (i.add(t)) {
                  const e = t.O(), i = t.M();
                  return s.put({
                      collectionId: e,
                      parent: ze(i)
                  });
              }
          };
          // Helper to add an index entry iff we haven't already written it.
                  // Index existing remote documents.
          return e.store(Ms.store).Br({
              Sh: !0
          }, (t, e) => {
              const s = new v(t);
              return n(s.M());
          }).next(() => e.store(Ns.store).Br({
              Sh: !0
          }, ([t, e, s], i) => {
              const r = Je(e);
              return n(r.M());
          }));
      }
      rewriteCanonicalIds(t) {
          const e = t.store(Os.store);
          return e.Br((t, s) => {
              const i = this.serializer.mh(s), n = this.serializer.Ah(i);
              return e.put(n);
          });
      }
  }
  
  class Ss {
      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 Ds {
      constructor(t, 
      /** Whether to allow shared access from multiple tabs. */
      e, s) {
          this.ownerId = t, this.allowTabSynchronization = e, this.leaseTimestampMs = s;
      }
  }
  
  /**
   * 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.
   */ Ds.store = "owner", 
  /**
   * The key string used for the single object that exists in the
   * DbPrimaryClient store.
   */
  Ds.key = "owner";
  
  class Cs {
      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.
       */
      s) {
          this.userId = t, this.lastAcknowledgedBatchId = e, this.lastStreamToken = s;
      }
  }
  
  /** Name of the IndexedDb object store.  */ Cs.store = "mutationQueues", 
  /** Keys are automatically assigned via the userId property. */
  Cs.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 Fs {
      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.
       */
      s, 
      /**
       * 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.
       */
      i, 
      /**
       * A list of mutations to apply. All mutations will be applied atomically.
       *
       * Mutations are serialized via JsonProtoSerializer.toMutation().
       */
      n) {
          this.userId = t, this.batchId = e, this.localWriteTimeMs = s, this.baseMutations = i, 
          this.mutations = n;
      }
  }
  
  /** Name of the IndexedDb object store.  */ Fs.store = "mutations", 
  /** Keys are automatically assigned via the userId, batchId properties. */
  Fs.keyPath = "batchId", 
  /** The index name for lookup of mutations by user. */
  Fs.userMutationsIndex = "userMutationsIndex", 
  /** The user mutations index is keyed by [userId, batchId] pairs. */
  Fs.userMutationsKeyPath = [ "userId", "batchId" ];
  
  class Ns {
      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, ze(e) ];
      }
      /**
       * Creates a full index key of [userId, encodedPath, batchId] for inserting
       * and deleting into the DbDocumentMutations index.
       */    static key(t, e, s) {
          return [ t, ze(e), s ];
      }
  }
  
  Ns.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.
   */
  Ns.PLACEHOLDER = new Ns;
  
  class $s {
      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 Ms {
      // 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.
       */
      s, 
      /**
       * 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.
       */
      i, 
      /**
       * When the document was read from the backend. Undefined for data written
       * prior to schema version 9.
       */
      n, 
      /**
       * 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 = s, this.hasCommittedMutations = i, 
          this.readTime = n, this.parentPath = r;
      }
  }
  
  Ms.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.
   */
  Ms.readTimeIndex = "readTimeIndex", Ms.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.
   */
  Ms.collectionReadTimeIndex = "collectionReadTimeIndex", Ms.collectionReadTimeIndexPath = [ "parentPath", "readTime" ];
  
  /**
   * Contains a single entry that has metadata about the remote document cache.
   */
  class Ls {
      /**
       * @param byteSize Approximately the total size in bytes of all the documents in the document
       * cache.
       */
      constructor(t) {
          this.byteSize = t;
      }
  }
  
  Ls.store = "remoteDocumentGlobal", Ls.key = "remoteDocumentGlobalKey";
  
  class Os {
      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.
       */
      s, 
      /**
       * 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.
       */
      i, 
      /**
       * 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.
       */
      n, 
      /**
       * 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.
       */
      h) {
          this.targetId = t, this.canonicalId = e, this.readTime = s, this.resumeToken = i, 
          this.lastListenSequenceNumber = n, this.lastLimboFreeSnapshotVersion = r, this.query = h;
      }
  }
  
  Os.store = "targets", 
  /** Keys are automatically assigned via the targetId property. */
  Os.keyPath = "targetId", 
  /** The name of the queryTargets index. */
  Os.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.
   */
  Os.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 xs {
      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`.
       */
      s) {
          this.targetId = t, this.path = e, this.sequenceNumber = s;
      }
  }
  
  /** Name of the IndexedDb object store.  */ xs.store = "targetDocuments", 
  /** Keys are automatically assigned via the targetId, path properties. */
  xs.keyPath = [ "targetId", "path" ], 
  /** The index name for the reverse index. */
  xs.documentTargetsIndex = "documentTargetsIndex", 
  /** We also need to create the reverse index for these properties. */
  xs.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 Bs {
      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.
       */
      s, 
      /**
       * The number of targets persisted.
       */
      i) {
          this.highestTargetId = t, this.highestListenSequenceNumber = e, this.lastRemoteSnapshotVersion = s, 
          this.targetCount = i;
      }
  }
  
  /**
   * The key string used for the single object that exists in the
   * DbTargetGlobal store.
   */ Bs.key = "targetGlobalKey", Bs.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 qs {
      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. */ function Us(t) {
      t.createObjectStore(xs.store, {
          keyPath: xs.keyPath
      }).createIndex(xs.documentTargetsIndex, xs.documentTargetsKeyPath, {
          unique: !0
      }), 
      // NOTE: This is unique only because the TargetId is the suffix.
      t.createObjectStore(Os.store, {
          keyPath: Os.keyPath
      }).createIndex(Os.queryTargetsIndexName, Os.queryTargetsKeyPath, {
          unique: !0
      }), t.createObjectStore(Bs.store);
  }
  
  qs.store = "collectionParents", 
  /** Keys are automatically assigned via the collectionId, parent properties. */
  qs.keyPath = [ "collectionId", "parent" ];
  
  class Qs {
      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. */
      s, 
      /** Whether this client is running in a foreground tab. */
      i) {
          this.clientId = t, this.updateTimeMs = e, this.networkEnabled = s, this.inForeground = i;
      }
  }
  
  /** Name of the IndexedDb object store. */ Qs.store = "clientMetadata", 
  /** Keys are automatically assigned via the clientId properties. */
  Qs.keyPath = "clientId";
  
  const Ws = [ ...[ ...[ ...[ Cs.store, Fs.store, Ns.store, Ms.store, Os.store, Ds.store, Bs.store, xs.store ], Qs.store ], Ls.store ], qs.store ];
  
  // V2 is no longer usable (see comment at top of file)
  // Visible for testing
  /**
   * 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 js {
      constructor(t) {
          this.db = t, 
          // 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 === js.ha(i()) && pe("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.");
      }
      /**
       * Opens the specified database, creating or upgrading it if necessary.
       *
       * 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.
       */    static Yh(t, e, s) {
          return ge("SimpleDb", "Opening database:", t), new xe((i, 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 r = window.indexedDB.open(t, e);
              r.onsuccess = t => {
                  const e = t.target.result;
                  i(new js(e));
              }, r.onblocked = () => {
                  n(new R(w.FAILED_PRECONDITION, "Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."));
              }, r.onerror = t => {
                  const e = t.target.error;
                  "VersionError" === e.name ? n(new R(w.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(e);
              }, r.onupgradeneeded = e => {
                  ge("SimpleDb", 'Database "' + t + '" requires upgrade from version:', e.oldVersion);
                  const i = e.target.result;
                  s.createOrUpgrade(i, r.transaction, e.oldVersion, bs).next(() => {
                      ge("SimpleDb", "Database upgrade to version " + bs + " complete");
                  });
              };
          }).yn();
      }
      /** Deletes the specified database. */    static delete(t) {
          return ge("SimpleDb", "Removing database:", t), Js(window.indexedDB.deleteDatabase(t)).yn();
      }
      /** Returns true if IndexedDB is available in the current environment. */    static jh() {
          if ("undefined" == typeof window || null == window.indexedDB) return !1;
          if (js.oa()) return !0;
          // In some Node environments, `window` is defined, but `window.navigator` is
          // not. We don't support IndexedDB persistence in Node if the
          // isMockPersistence() check above returns false.
                  if (void 0 === window.navigator) return !1;
          // 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 = i(), e = js.ha(t), s = 0 < e && e < 10, n = js.aa(t), r = 0 < n && n < 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 oa() {
          var t;
          return "undefined" != typeof __PRIVATE_process && "YES" === (null === (t = __PRIVATE_process.__PRIVATE_env) || void 0 === t ? void 0 : t.ua);
      }
      /** Helper to get a typed SimpleDbStore from a transaction. */    static Cr(t, e) {
          return t.store(e);
      }
      // visible for testing
      /** Parse User Agent to determine iOS version. Returns -1 if not found. */
      static ha(t) {
          const e = t.match(/i(?:phone|pad|pod) os ([\d_]+)/i), s = e ? e[1].split("_").slice(0, 2).join(".") : "-1";
          return Number(s);
      }
      // visible for testing
      /** Parse User Agent to determine Android version. Returns -1 if not found. */
      static aa(t) {
          const e = t.match(/Android ([\d.]+)/i), s = e ? e[1].split(".").slice(0, 2).join(".") : "-1";
          return Number(s);
      }
      ro(t) {
          this.db.onversionchange = e => t(e);
      }
      async runTransaction(t, e, s) {
          const i = "readonly" === t;
          let n = 0;
          for (;;) {
              ++n;
              const t = Hs.open(this.db, i ? "readonly" : "readwrite", e);
              try {
                  const e = s(t).catch(e => (
                  // Abort the transaction if there was an error.
                  t.abort(e), xe.reject(e))).yn();
                  // 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 e.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 t.ca, e;
              } 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 && n < 3;
                  if (ge("SimpleDb", "Transaction failed with error: %s. Retrying: %s.", t.message, e), 
                  !e) return Promise.reject(t);
              }
          }
      }
      close() {
          this.db.close();
      }
  }
  
  /**
   * 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 Ks {
      constructor(t) {
          this._a = t, this.la = !1, this.da = null;
      }
      get Pn() {
          return this.la;
      }
      get fa() {
          return this.da;
      }
      set cursor(t) {
          this._a = t;
      }
      /**
       * This function can be called to stop iteration at any point.
       */    done() {
          this.la = !0;
      }
      /**
       * This function can be called to skip to that next key, which could be
       * an index or a primary key.
       */    qr(t) {
          this.da = t;
      }
      /**
       * Delete the current cursor value from the object store.
       *
       * NOTE: You CANNOT do this with a keysOnly query.
       */    delete() {
          return Js(this._a.delete());
      }
  }
  
  /** An error that wraps exceptions that thrown during IndexedDB execution. */ class Gs extends R {
      constructor(t) {
          super(w.UNAVAILABLE, "IndexedDB transaction failed: " + t), this.name = "IndexedDbTransactionError";
      }
  }
  
  /** Verifies whether `e` is an IndexedDbTransactionError. */ function zs(t) {
      // Use name equality, as instanceof checks on errors don't work with errors
      // that wrap other errors.
      return "IndexedDbTransactionError" === t.name;
  }
  
  /**
   * Wraps an IDBTransaction and exposes a store() method to get a handle to a
   * specific object store.
   */ class Hs {
      constructor(t) {
          this.transaction = t, this.aborted = !1, 
          /**
           * A promise that resolves with the result of the IndexedDb transaction.
           */
          this.Ta = new Ke, this.transaction.oncomplete = () => {
              this.Ta.resolve();
          }, this.transaction.onabort = () => {
              t.error ? this.Ta.reject(new Gs(t.error)) : this.Ta.resolve();
          }, this.transaction.onerror = t => {
              const e = Zs(t.target.error);
              this.Ta.reject(new Gs(e));
          };
      }
      static open(t, e, s) {
          return new Hs(t.transaction(s, e));
      }
      get ca() {
          return this.Ta.promise;
      }
      abort(t) {
          t && this.Ta.reject(t), this.aborted || (ge("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 Ys(e);
      }
  }
  
  /**
   * 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 Ys {
      constructor(t) {
          this.store = t;
      }
      put(t, e) {
          let s;
          return void 0 !== e ? (ge("SimpleDb", "PUT", this.store.name, t, e), s = this.store.put(e, t)) : (ge("SimpleDb", "PUT", this.store.name, "<auto-key>", t), 
          s = this.store.put(t)), Js(s);
      }
      /**
       * 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.
       * @return The key of the value to add.
       */    add(t) {
          return ge("SimpleDb", "ADD", this.store.name, t, t), Js(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.
       * @return 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 Js(this.store.get(t)).next(e => (
          // Normalize nonexistence to null.
          void 0 === e && (e = null), ge("SimpleDb", "GET", this.store.name, t, e), e));
      }
      delete(t) {
          return ge("SimpleDb", "DELETE", this.store.name, t), Js(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() {
          return ge("SimpleDb", "COUNT", this.store.name), Js(this.store.count());
      }
      Dr(t, e) {
          const s = this.cursor(this.options(t, e)), i = [];
          return this.Ea(s, (t, e) => {
              i.push(e);
          }).next(() => i);
      }
      Ia(t, e) {
          ge("SimpleDb", "DELETE ALL", this.store.name);
          const s = this.options(t, e);
          s.Sh = !1;
          const i = this.cursor(s);
          return this.Ea(i, (t, e, s) => s.delete());
      }
      Br(t, e) {
          let s;
          e ? s = t : (s = {}, e = t);
          const i = this.cursor(s);
          return this.Ea(i, 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.
       */    Bo(t) {
          const e = this.cursor({});
          return new xe((s, i) => {
              e.onerror = t => {
                  const e = Zs(t.target.error);
                  i(e);
              }, e.onsuccess = e => {
                  const i = e.target.result;
                  i ? t(i.primaryKey, i.value).next(t => {
                      t ? i.continue() : s();
                  }) : s();
              };
          });
      }
      Ea(t, e) {
          const s = [];
          return new xe((i, n) => {
              t.onerror = t => {
                  n(t.target.error);
              }, t.onsuccess = t => {
                  const n = t.target.result;
                  if (!n) return void i();
                  const r = new Ks(n), h = e(n.primaryKey, n.value, r);
                  if (h instanceof xe) {
                      const t = h.catch(t => (r.done(), xe.reject(t)));
                      s.push(t);
                  }
                  r.Pn ? i() : null === r.fa ? n.continue() : n.continue(r.fa);
              };
          }).next(() => xe.vn(s));
      }
      options(t, e) {
          let s = void 0;
          return void 0 !== t && ("string" == typeof t ? s = t : e = t), {
              index: s,
              range: e
          };
      }
      cursor(t) {
          let e = "next";
          if (t.reverse && (e = "prev"), t.index) {
              const s = this.store.index(t.index);
              return t.Sh ? s.openKeyCursor(t.range, e) : s.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 Js(t) {
      return new xe((e, s) => {
          t.onsuccess = t => {
              const s = t.target.result;
              e(s);
          }, t.onerror = t => {
              const e = Zs(t.target.error);
              s(e);
          };
      });
  }
  
  // Guard so we only report the error once.
  let Xs = !1;
  
  function Zs(t) {
      const e = js.ha(i());
      if (e >= 12.2 && e < 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 R("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 Xs || (Xs = !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()).
   */
  class ti {
      constructor(t, e, s, i, n) {
          this.wa = t, this.Er = e, this.Ra = s, this.op = i, this.ma = n, this.Aa = new Ke, 
          this.then = this.Aa.promise.then.bind(this.Aa.promise), this.catch = this.Aa.promise.catch.bind(this.Aa.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.Aa.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 Pa(t, e, s, i, n) {
          const r = Date.now() + s, h = new ti(t, e, r, i, n);
          return h.start(s), h;
      }
      /**
       * Starts the timer. This is called immediately after construction by
       * createAndSchedule().
       */    start(t) {
          this.Va = setTimeout(() => this.ga(), t);
      }
      /**
       * Queues the operation to run immediately (if it hasn't already been run or
       * canceled).
       */    pa() {
          return this.ga();
      }
      /**
       * 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.Va && (this.clearTimeout(), this.Aa.reject(new R(w.CANCELLED, "Operation cancelled" + (t ? ": " + t : ""))));
      }
      ga() {
          this.wa.oo(() => null !== this.Va ? (this.clearTimeout(), this.op().then(t => this.Aa.resolve(t))) : Promise.resolve());
      }
      clearTimeout() {
          null !== this.Va && (this.ma(this), clearTimeout(this.Va), this.Va = null);
      }
  }
  
  class ei {
      constructor() {
          // The last promise in the queue.
          this.ya = Promise.resolve(), 
          // The last retryable operation. Retryable operation are run in order and
          // retried with backoff.
          this.ba = Promise.resolve(), 
          // Is this AsyncQueue being shut down? Once it is set to true, it will not
          // be changed again.
          this.va = !1, 
          // Operations scheduled to be queued in the future. Operations are
          // automatically removed after they are run or canceled.
          this.Sa = [], 
          // visible for testing
          this.Da = null, 
          // Flag set while there's an outstanding AsyncQueue operation, used for
          // assertion sanity-checks.
          this.Ca = !1, 
          // List of TimerIds to fast-forward delays for.
          this.Fa = [], 
          // Backoff timer used to schedule retries for retryable operations
          this.Na = new Ge(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.$a = () => {
              // eslint-disable-next-line @typescript-eslint/no-floating-promises
              this.ka("async_queue_retry" /* AsyncQueueRetry */);
          };
          const t = me.nt().window;
          t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this.$a);
      }
      // Is this AsyncQueue being shut down? If true, this instance will not enqueue
      // any new operations, Promises from enqueue requests will not resolve.
      get Ma() {
          return this.va;
      }
      /**
       * Adds a new operation to the queue without waiting for it to complete (i.e.
       * we ignore the Promise result).
       */    oo(t) {
          // eslint-disable-next-line @typescript-eslint/no-floating-promises
          this.enqueue(t);
      }
      /**
       * Regardless if the queue has initialized shutdown, adds a new operation to the
       * queue without waiting for it to complete (i.e. we ignore the Promise result).
       */    La(t) {
          this.Oa(), 
          // eslint-disable-next-line @typescript-eslint/no-floating-promises
          this.xa(t);
      }
      /**
       * Regardless if the queue has initialized shutdown, adds a new operation to the
       * queue.
       */    Ba(t) {
          return this.Oa(), this.xa(t);
      }
      /**
       * Adds a new operation to the queue and initialize the shut down of this queue.
       * Returns a promise that will be resolved when the promise returned by the new
       * operation is (with its value).
       * Once this method is called, the only possible way to request running an operation
       * is through `enqueueAndForgetEvenAfterShutdown`.
       */    async qa(t) {
          if (this.Oa(), !this.va) {
              this.va = !0;
              const e = me.nt().window;
              e && e.removeEventListener("visibilitychange", this.$a), await this.Ba(t);
          }
      }
      /**
       * Adds a new operation to the queue. Returns a promise that will be resolved
       * when the promise returned by the new operation is (with its value).
       */    enqueue(t) {
          return this.Oa(), this.va ? new Promise(t => {}) : this.xa(t);
      }
      /**
       * Enqueue a retryable operation.
       *
       * A retryable operation is rescheduled with backoff if it fails with a
       * IndexedDbTransactionError (the error type used by SimpleDb). All
       * retryable operations are executed in order and only run if all prior
       * operations were retried successfully.
       */    Ua(t) {
          this.Oa(), this.va || (this.ba = this.ba.then(() => {
              const e = new Ke, s = async () => {
                  try {
                      await t(), e.resolve(), this.Na.reset();
                  } catch (t) {
                      if (!zs(t)) throw e.resolve(), t;
   // Failure will be handled by AsyncQueue
                                          ge("AsyncQueue", "Operation failed with retryable error: " + t), 
                      this.Na.gr(s);
                  }
              };
              return this.oo(s), e.promise;
          }));
      }
      xa(t) {
          const e = this.ya.then(() => (this.Ca = !0, t().catch(t => {
              // 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 this.Da = t, this.Ca = !1, pe("INTERNAL UNHANDLED ERROR: ", t.stack || t.message || ""), 
              t;
          }).then(t => (this.Ca = !1, t))));
          return this.ya = e, e;
      }
      /**
       * Schedules an operation to be queued on the AsyncQueue once the specified
       * `delayMs` has elapsed. The returned CancelablePromise can be used to cancel
       * the operation prior to its running.
       */    yr(t, e, s) {
          this.Oa(), 
          // Fast-forward delays for timerIds that have been overriden.
          this.Fa.indexOf(t) > -1 && (e = 0);
          const i = ti.Pa(this, t, e, s, t => this.Qa(t));
          return this.Sa.push(i), i;
      }
      Oa() {
          this.Da && be();
      }
      /**
       * Verifies there's an operation currently in-progress on the AsyncQueue.
       * Unfortunately we can't verify that the running code is in the promise chain
       * of that operation, so this isn't a foolproof check, but it should be enough
       * to catch some bugs.
       */    Wa() {}
      /**
       * Waits until all currently queued tasks are finished executing. Delayed
       * operations are not run.
       */    async ja() {
          // 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.ya, await t;
          } while (t !== this.ya);
      }
      /**
       * For Tests: Determine if a delayed operation with a particular TimerId
       * exists.
       */    Ka(t) {
          for (const e of this.Sa) if (e.Er === 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. Throws if no such operation exists. Pass TimerId.All to run
       *  all delayed operations.
       * @returns a Promise that resolves once all operations have been run.
       */    ka(t) {
          // Note that draining may generate more delayed ops, so we do that first.
          return this.ja().then(() => {
              // Run ops in the same order they'd run if they ran naturally.
              this.Sa.sort((t, e) => t.Ra - e.Ra);
              for (const e of this.Sa) if (e.pa(), "all" /* All */ !== t && e.Er === t) break;
              return this.ja();
          });
      }
      /**
       * For Tests: Skip all subsequent delays for a timer id.
       */    Ga(t) {
          this.Fa.push(t);
      }
      /** Called once a DelayedOperation is run or canceled. */    Qa(t) {
          // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
          const e = this.Sa.indexOf(t);
          this.Sa.splice(e, 1);
      }
  }
  
  /**
   * Returns a FirestoreError that can be surfaced to the user if the provided
   * error is an IndexedDbTransactionError. Re-throws the error otherwise.
   */ function si(t, e) {
      if (pe("AsyncQueue", `${e}: ${t}`), zs(t)) return new R(w.UNAVAILABLE, `${e}: ${t}`);
      throw 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.
   */ function ii([t, e], [s, i]) {
      const n = Ce(t, s);
      return 0 === n ? Ce(e, i) : n;
  }
  
  /**
   * 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 ni {
      constructor(t) {
          this.za = t, this.buffer = new jt(ii), this.Ha = 0;
      }
      Ya() {
          return ++this.Ha;
      }
      Ja(t) {
          const e = [ t, this.Ya() ];
          if (this.buffer.size < this.za) this.buffer = this.buffer.add(e); else {
              const t = this.buffer.last();
              ii(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];
      }
  }
  
  const ri = {
      Xa: !1,
      Za: 0,
      tu: 0,
      eu: 0
  };
  
  class hi {
      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.
      s) {
          this.su = t, this.iu = e, this.nu = s;
      }
      static ru(t) {
          return new hi(t, hi.hu, hi.ou);
      }
  }
  
  hi.au = -1, hi.uu = 1048576, hi.cu = 41943040, hi.hu = 10, hi.ou = 1e3, hi._u = new hi(hi.cu, hi.hu, hi.ou), 
  hi.DISABLED = new hi(hi.au, 0, 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 oi {
      constructor(t, e) {
          this.No = t, this.wa = e, this.lu = !1, this.du = null;
      }
      start(t) {
          this.No.fu.su !== hi.au && this.Tu(t);
      }
      stop() {
          this.du && (this.du.cancel(), this.du = null);
      }
      get io() {
          return null !== this.du;
      }
      Tu(t) {
          const e = this.lu ? 3e5 : 6e4;
          ge("LruGarbageCollector", `Garbage collection scheduled in ${e}ms`), this.du = this.wa.yr("lru_garbage_collection" /* LruGarbageCollection */ , e, async () => {
              this.du = null, this.lu = !0;
              try {
                  await t.Eu(this.No);
              } catch (t) {
                  zs(t) ? ge("LruGarbageCollector", "Ignoring IndexedDB error during garbage collection: ", t) : await _i(t);
              }
              await this.Tu(t);
          });
      }
  }
  
  /** Implements the steps for LRU garbage collection. */ class ai {
      constructor(t, e) {
          this.Iu = t, this.fu = e;
      }
      /** Given a percentile of target to collect, returns the number of targets to collect. */    wu(t, e) {
          return this.Iu.$o(t).next(t => Math.floor(e / 100 * t));
      }
      /** Returns the nth sequence number, counting in order from the smallest. */    Ru(t, e) {
          if (0 === e) return xe.resolve(je.dr);
          const s = new ni(e);
          return this.Iu.js(t, t => s.Ja(t.sequenceNumber)).next(() => this.Iu.Mo(t, t => s.Ja(t))).next(() => s.maxValue);
      }
      /**
       * Removes targets with a sequence number equal to or less than the given upper bound, and removes
       * document associations with those targets.
       */    Rh(t, e, s) {
          return this.Iu.Rh(t, e, s);
      }
      /**
       * Removes documents that have a sequence number equal to or less than the upper bound and are not
       * otherwise pinned.
       */    qo(t, e) {
          return this.Iu.qo(t, e);
      }
      mu(t, e) {
          return this.fu.su === hi.au ? (ge("LruGarbageCollector", "Garbage collection skipped; disabled"), 
          xe.resolve(ri)) : this.Qo(t).next(s => s < this.fu.su ? (ge("LruGarbageCollector", `Garbage collection skipped; Cache size ${s} ` + `is lower than threshold ${this.fu.su}`), 
          ri) : this.Au(t, e));
      }
      Qo(t) {
          return this.Iu.Qo(t);
      }
      Au(t, e) {
          let i, n, r, h, o, a, u;
          const c = Date.now();
          return this.wu(t, this.fu.iu).next(e => (
          // Cap at the configured max
          e > this.fu.nu ? (ge("LruGarbageCollector", "Capping sequence numbers to collect down " + `to the maximum of ${this.fu.nu} ` + `from ${e}`), 
          n = this.fu.nu) : n = e, h = Date.now(), this.Ru(t, n))).next(s => (i = s, o = Date.now(), 
          this.Rh(t, i, e))).next(e => (r = e, a = Date.now(), this.qo(t, i))).next(t => {
              if (u = Date.now(), Pe() <= s.DEBUG) {
                  ge("LruGarbageCollector", "LRU Garbage Collection\n" + `\tCounted targets in ${h - c}ms\n` + `\tDetermined least recently used ${n} in ` + `${o - h}ms\n` + `\tRemoved ${r} targets in ` + `${a - o}ms\n` + `\tRemoved ${t} documents in ` + `${u - a}ms\n` + `Total Duration: ${u - c}ms`);
              }
              return xe.resolve({
                  Xa: !0,
                  Za: n,
                  tu: r,
                  eu: 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.
   */
  /**
   * Local storage in the Firestore client. Coordinates persistence components
   * like the mutation queue and remote document cache to present a
   * latency-compensated view of stored data.
   *
   * The LocalStore is responsible for accepting mutations from the Sync Engine.
   * Writes from the client are put into a queue as provisional Mutations until
   * they are processed by the RemoteStore and confirmed as having been written
   * to the server.
   *
   * The local store provides the local version of documents that have been
   * modified locally. It maintains the constraint:
   *
   *   LocalDocument = RemoteDocument + Active(LocalMutations)
   *
   * (Active mutations are those that are enqueued and have not been previously
   * acknowledged or rejected).
   *
   * The RemoteDocument ("ground truth") state is provided via the
   * applyChangeBatch method. It will be some version of a server-provided
   * document OR will be a server-provided document PLUS acknowledged mutations:
   *
   *   RemoteDocument' = RemoteDocument + Acknowledged(LocalMutations)
   *
   * Note that this "dirty" version of a RemoteDocument will not be identical to a
   * server base version, since it has LocalMutations added to it pending getting
   * an authoritative copy from the server.
   *
   * Since LocalMutations can be rejected by the server, we have to be able to
   * revert a LocalMutation that has already been applied to the LocalDocument
   * (typically done by replaying all remaining LocalMutations to the
   * RemoteDocument to re-apply).
   *
   * The LocalStore is responsible for the garbage collection of the documents it
   * contains. For now, it every doc referenced by a view, the mutation queue, or
   * the RemoteStore.
   *
   * It also maintains the persistence of mapping queries to resume tokens and
   * target ids. It needs to know this data about queries to properly know what
   * docs it would be allowed to garbage collect.
   *
   * The LocalStore must be able to efficiently execute queries against its local
   * cache of the documents, to provide the initial set of results before any
   * remote changes have been received.
   *
   * Note: In TypeScript, most methods return Promises since the implementation
   * may rely on fetching data from IndexedDB which is async.
   * These Promises will only be rejected on an I/O error or other internal
   * (unexpected) failure (e.g. failed assert) and always represent an
   * unrecoverable error (should be caught / reported by the async_queue).
   */
  class ui {
      constructor(
      /** Manages our in-memory or durable persistence. */
      t, e, s) {
          this.persistence = t, this.Pu = e, 
          /**
           * 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.Vu = new Ut(Ce), 
          /** Maps a target to its targetID. */
          // TODO(wuandy): Evaluate if TargetId can be part of Target.
          this.gu = new Me(t => t.canonicalId()), 
          /**
           * The read time of the last entry processed by `getNewDocumentChanges()`.
           *
           * PORTING NOTE: This is only used for multi-tab synchronization.
           */
          this.pu = y.min(), this.Wn = t.yo(s), this.yu = t.So(), this.zh = t.vo(), this.bu = new Qe(this.yu, this.Wn, this.persistence.Do()), 
          this.Pu.vu(this.bu);
      }
      /** Starts the LocalStore. */    start() {
          return Promise.resolve();
      }
      /**
       * 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 Su(t) {
          let e = this.Wn, s = this.bu;
          const i = await this.persistence.runTransaction("Handle user change", "readonly", i => {
              // Swap out the mutation queue, grabbing the pending mutation batches
              // before and after.
              let n;
              return this.Wn.ea(i).next(r => (n = r, e = this.persistence.yo(t), 
              // Recreate our LocalDocumentsView using the new
              // MutationQueue.
              s = new Qe(this.yu, e, this.persistence.Do()), e.ea(i))).next(t => {
                  const e = [], r = [];
                  // Union the old/new changed keys.
                  let h = ee();
                  for (const t of n) {
                      e.push(t.batchId);
                      for (const e of t.mutations) h = h.add(e.key);
                  }
                  for (const e of t) {
                      r.push(e.batchId);
                      for (const t of e.mutations) h = h.add(t.key);
                  }
                  // Return the set of all (potentially) changed documents and the list
                  // of mutation batch IDs that were affected by change.
                                  return s.Yn(i, h).next(t => ({
                      Du: t,
                      Cu: e,
                      Fu: r
                  }));
              });
          });
          return this.Wn = e, this.bu = s, this.Pu.vu(this.bu), i;
      }
      /* Accept locally generated Mutations and commit them to storage. */    Nu(t) {
          const e = p.now(), s = t.reduce((t, e) => t.add(e.key), ee());
          let i;
          return this.persistence.runTransaction("Locally write mutations", "readwrite", n => this.bu.Yn(n, s).next(s => {
              i = s;
              // 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 r = [];
              for (const e of t) {
                  const t = e.Pt(i.get(e.key));
                  null != t && 
                  // NOTE: The base state should only be applied if there's some
                  // existing document to override, so use a Precondition of
                  // exists=true
                  r.push(new Tt(e.key, t, At(t.proto.mapValue), lt.exists(!0)));
              }
              return this.Wn.Yo(n, e, r, t);
          })).then(t => {
              const e = t.In(i);
              return {
                  batchId: t.batchId,
                  Dn: e
              };
          });
      }
      /**
       * Acknowledge 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.
       */    Ko(t) {
          return this.persistence.runTransaction("Acknowledge batch", "readwrite-primary", e => {
              const s = t.batch.keys(), i = this.yu.zr({
                  Yr: !0
              });
              return this.Wn.Ko(e, t.batch, t.streamToken).next(() => this.$u(e, t, i)).next(() => i.apply(e)).next(() => this.Wn.ra(e)).next(() => this.bu.Yn(e, s));
          });
      }
      /**
       * Remove mutations from the MutationQueue for the specified batch;
       * LocalDocuments will be recalculated.
       *
       * @returns The resulting modified documents.
       */    ku(t) {
          return this.persistence.runTransaction("Reject batch", "readwrite-primary", e => {
              let s;
              return this.Wn.Jo(e, t).next(t => (ve(null !== t), s = t.keys(), this.Wn.ia(e, t))).next(() => this.Wn.ra(e)).next(() => this.bu.Yn(e, s));
          });
      }
      /**
       * Returns the largest (latest) batch id in mutation queue that is pending server response.
       * Returns `BATCHID_UNKNOWN` if the queue is empty.
       */    ta() {
          return this.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", t => this.Wn.ta(t));
      }
      /** Returns the last recorded stream token for the current user. */    zo() {
          return this.persistence.runTransaction("Get last stream token", "readonly", t => this.Wn.zo(t));
      }
      /**
       * Sets the stream token for the current user without acknowledging any
       * mutation batch. This is usually only useful after a stream handshake or in
       * response to an error that requires clearing the stream token.
       */    Ho(t) {
          return this.persistence.runTransaction("Set last stream token", "readwrite-primary", e => this.Wn.Ho(e, t));
      }
      /**
       * Returns the last consistent snapshot processed (used by the RemoteStore to
       * determine whether to buffer incoming snapshots from the backend).
       */    ah() {
          return this.persistence.runTransaction("Get last remote snapshot version", "readonly", t => this.zh.ah(t));
      }
      /**
       * Update 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.
       */    Mu(t) {
          const e = t.Ee;
          let s = this.Vu;
          return this.persistence.runTransaction("Apply remote event", "readwrite-primary", i => {
              const n = this.yu.zr({
                  Yr: !0
              });
              // Reset newTargetDataByTargetMap in case this transaction gets re-run.
                          s = this.Vu;
              const r = [];
              t.as.forEach((t, n) => {
                  const h = s.get(n);
                  if (!h) 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.
                                  r.push(this.zh.yh(i, t.Is, n).next(() => this.zh.gh(i, t.Ts, n)));
                  const o = t.resumeToken;
                  // Update the resume token if the change includes one.
                                  if (o.rt() > 0) {
                      const a = h.we(o, e).Ie(i.Mh);
                      s = s.me(n, a), 
                      // Update the target data if there are target changes (or if
                      // sufficient time has passed since the last update).
                      ui.Lu(h, a, t) && r.push(this.zh.Eh(i, a));
                  }
              });
              let h = zt(), o = ee();
              // 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 (t.cs.forEach((t, e) => {
                  o = o.add(t);
              }), 
              // Each loop iteration only affects its "own" doc, so it's safe to get all the remote
              // documents in advance in a single call.
              r.push(n.getEntries(i, o).next(s => {
                  t.cs.forEach((o, a) => {
                      const u = s.get(o);
                      // 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.
                                          a instanceof gt && a.version.isEqual(y.min()) ? (
                      // NoDocuments with SnapshotVersion.min() are used in manufactured
                      // events. We remove these documents from cache since we lost
                      // access.
                      n.kn(o, e), h = h.me(o, a)) : null == u || a.version.S(u.version) > 0 || 0 === a.version.S(u.version) && u.hasPendingWrites ? (n.Nn(a, e), 
                      h = h.me(o, a)) : ge("LocalStore", "Ignoring outdated watch update for ", o, ". Current version:", u.version, " Watch version:", a.version), 
                      t._s.has(o) && r.push(this.persistence.nh.Uo(i, o));
                  });
              })), !e.isEqual(y.min())) {
                  const t = this.zh.ah(i).next(t => this.zh.lh(i, i.Mh, e));
                  r.push(t);
              }
              return xe.vn(r).next(() => n.apply(i)).next(() => this.bu.Jn(i, h));
          }).then(t => (this.Vu = s, t));
      }
      /**
       * 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.
       */    static Lu(t, e, s) {
          // Always persist target data if we don't already have a resume token.
          if (ve(e.resumeToken.rt() > 0), 0 === t.resumeToken.rt()) 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.
                  return e.Ee.D() - t.Ee.D() >= this.Ou || s.Ts.size + s.Es.size + s.Is.size > 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.
          }
      /**
       * Notify local store of the changed views to locally pin documents.
       */    async xu(t) {
          try {
              await this.persistence.runTransaction("notifyLocalViewChanges", "readwrite", e => xe.forEach(t, t => xe.forEach(t.hr, s => this.persistence.nh.ph(e, t.targetId, s)).next(() => xe.forEach(t.or, s => this.persistence.nh.bh(e, t.targetId, s)))));
          } catch (t) {
              if (!zs(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.
              ge("LocalStore", "Failed to update sequence numbers: " + t);
          }
          for (const e of t) {
              const t = e.targetId;
              if (!e.fromCache) {
                  const e = this.Vu.get(t), s = e.Ee, i = e.Re(s);
                  // Advance the last limbo free snapshot version
                                  this.Vu = this.Vu.me(t, i);
              }
          }
      }
      /**
       * 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.
       */    Bu(t) {
          return this.persistence.runTransaction("Get next mutation batch", "readonly", e => (void 0 === t && (t = -1), 
          this.Wn.Zo(e, t)));
      }
      /**
       * Read the current value of a Document with a given key or null if not
       * found - used for testing.
       */    qu(t) {
          return this.persistence.runTransaction("read document", "readonly", e => this.bu.Kn(e, t));
      }
      /**
       * 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`.
       */    Uu(t) {
          return this.persistence.runTransaction("Allocate target", "readwrite", e => {
              let s;
              return this.zh.Vh(e, t).next(i => i ? (
              // This target has been listened to previously, so reuse the
              // previous targetID.
              // TODO(mcg): freshen last accessed date?
              s = i, xe.resolve(s)) : this.zh.rh(e).next(i => (s = new Mt(t, i, 0 /* Listen */ , e.Mh), 
              this.zh.dh(e, s).next(() => s))));
          }).then(e => (null === this.Vu.get(e.targetId) && (this.Vu = this.Vu.me(e.targetId, e), 
          this.gu.set(t, e.targetId)), e));
      }
      /**
       * Returns the TargetData as seen by the LocalStore, including updates that may
       * have not yet been persisted to the TargetCache.
       */
      // Visible for testing.
      Vh(t, e) {
          const s = this.gu.get(e);
          return void 0 !== s ? xe.resolve(this.Vu.get(s)) : this.zh.Vh(t, e);
      }
      /**
       * Unpin 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.
      Qu(t, e) {
          const s = this.Vu.get(t), i = e ? "readwrite" : "readwrite-primary";
          return this.persistence.runTransaction("Release target", i, t => e ? xe.resolve() : this.persistence.nh.removeTarget(t, s)).then(() => {
              this.Vu = this.Vu.remove(t), this.gu.delete(s.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.
       */    Wu(t, e) {
          let s = y.min(), i = ee();
          return this.persistence.runTransaction("Execute query", "readonly", n => this.Vh(n, t.ee()).next(t => {
              if (t) return s = t.lastLimboFreeSnapshotVersion, this.zh.vh(n, t.targetId).next(t => {
                  i = t;
              });
          }).next(() => this.Pu.Zn(n, t, e ? s : y.min(), e ? i : ee())).next(t => ({
              documents: t,
              ju: i
          })));
      }
      $u(t, e, s) {
          const i = e.batch, n = i.keys();
          let r = xe.resolve();
          return n.forEach(n => {
              r = r.next(() => s.Mn(t, n)).next(t => {
                  let r = t;
                  const h = e.Rn.get(n);
                  ve(null !== h), (!r || r.version.S(h) < 0) && (r = i.at(n, r, e), 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.Nn(r, e.wn));
              });
          }), r.next(() => this.Wn.ia(t, i));
      }
      Eu(t) {
          return this.persistence.runTransaction("Collect garbage", "readwrite-primary", e => t.mu(e, this.Vu));
      }
  }
  
  /**
   * The maximum time to leave a resume token buffered without writing it out.
   * This value is arbitrary: it's long enough to avoid several writes
   * (possibly indefinitely if updates come more frequently than this) but
   * short enough that restarting after crashing will still have a pretty
   * recent resume token.
   */ ui.Ou = 3e8;
  
  /**
   * An implementation of LocalStore that provides additional functionality
   * for MultiTabSyncEngine.
   */
  // PORTING NOTE: Web only.
  class ci extends ui {
      constructor(t, e, s) {
          super(t, e, s), this.persistence = t, this.Wn = t.yo(s), this.yu = t.So(), this.zh = t.vo();
      }
      /** Starts the LocalStore. */    start() {
          return this.Ku();
      }
      /** Returns the local view of the documents affected by a mutation batch. */    Gu(t) {
          return this.persistence.runTransaction("Lookup mutation documents", "readonly", e => this.Wn.Xo(e, t).next(t => t ? this.bu.Yn(e, t) : xe.resolve(null)));
      }
      zu(t) {
          this.Wn.na(t);
      }
      ho(t) {
          this.persistence.ho(t);
      }
      po() {
          return this.persistence.po();
      }
      Hu(t) {
          const e = this.Vu.get(t);
          return e ? Promise.resolve(e.target) : this.persistence.runTransaction("Get target data", "readonly", e => this.zh.si(e, t).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 changes since
       * the point of rejection.
       */    Wr() {
          return this.persistence.runTransaction("Get new document changes", "readonly", t => this.yu.Wr(t, this.pu)).then(({jr: t, readTime: e}) => (this.pu = e, 
          t));
      }
      /**
       * Reads the newest document change from persistence and forwards the internal
       * synchronization marker so that calls to `getNewDocumentChanges()`
       * only return changes that happened after client initialization.
       */    async Ku() {
          this.pu = await this.persistence.runTransaction("Synchronize last document change read time", "readonly", t => this.yu.Gr(t));
      }
  }
  
  /**
   * 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.
   * @return A Promise that resolves after we recovered, or the original error.
   */ async function _i(t) {
      if (t.code !== w.FAILED_PRECONDITION || t.message !== qe) throw t;
      ge("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 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 li {
      constructor() {
          // A set of outstanding references to a document sorted by key.
          this.Yu = new jt(di.Ju), 
          // A set of outstanding references to a document sorted by target id.
          this.Xu = new jt(di.Zu);
      }
      /** Returns true if the reference set contains no references. */    B() {
          return this.Yu.B();
      }
      /** Adds a reference to the given document key for the given ID. */    ph(t, e) {
          const s = new di(t, e);
          this.Yu = this.Yu.add(s), this.Xu = this.Xu.add(s);
      }
      /** Add references to the given document keys for the given ID. */    tc(t, e) {
          t.forEach(t => this.ph(t, e));
      }
      /**
       * Removes a reference to the given document key for the given
       * ID.
       */    bh(t, e) {
          this.ec(new di(t, e));
      }
      sc(t, e) {
          t.forEach(t => this.bh(t, e));
      }
      /**
       * Clears all references with a given ID. Calls removeRef() for each key
       * removed.
       */    ic(t) {
          const e = C.EMPTY, s = new di(e, t), i = new di(e, t + 1), n = [];
          return this.Xu.Ke([ s, i ], t => {
              this.ec(t), n.push(t.key);
          }), n;
      }
      nc() {
          this.Yu.forEach(t => this.ec(t));
      }
      ec(t) {
          this.Yu = this.Yu.delete(t), this.Xu = this.Xu.delete(t);
      }
      rc(t) {
          const e = C.EMPTY, s = new di(e, t), i = new di(e, t + 1);
          let n = ee();
          return this.Xu.Ke([ s, i ], t => {
              n = n.add(t.key);
          }), n;
      }
      Dh(t) {
          const e = new di(t, 0), s = this.Yu.ze(e);
          return null !== s && t.isEqual(s.key);
      }
  }
  
  class di {
      constructor(t, e) {
          this.key = t, this.hc = e;
      }
      /** Compare by key then by ID */    static Ju(t, e) {
          return C.N(t.key, e.key) || Ce(t.hc, e.hc);
      }
      /** Compare by ID then by key */    static Zu(t, e) {
          return Ce(t.hc, e.hc) || C.N(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.
   */
  /**
   * Validates that no arguments were passed in the invocation of functionName.
   *
   * Forward the magic "arguments" variable as second parameter on which the
   * parameter validation is performed:
   * validateNoArgs('myFunction', arguments);
   */ function fi(t, e) {
      if (0 !== e.length) throw new R(w.INVALID_ARGUMENT, `Function ${t}() does not support arguments, ` + "but was called with " + Fi(e.length, "argument") + ".");
  }
  
  /**
   * Validates the invocation of functionName has the exact number of arguments.
   *
   * Forward the magic "arguments" variable as second parameter on which the
   * parameter validation is performed:
   * validateExactNumberOfArgs('myFunction', arguments, 2);
   */ function Ti(t, e, s) {
      if (e.length !== s) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires ` + Fi(s, "argument") + ", but was called with " + Fi(e.length, "argument") + ".");
  }
  
  /**
   * Validates the invocation of functionName has at least the provided number of
   * arguments (but can have many more).
   *
   * Forward the magic "arguments" variable as second parameter on which the
   * parameter validation is performed:
   * validateAtLeastNumberOfArgs('myFunction', arguments, 2);
   */ function Ei(t, e, s) {
      if (e.length < s) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires at least ` + Fi(s, "argument") + ", but was called with " + Fi(e.length, "argument") + ".");
  }
  
  /**
   * Validates the invocation of functionName has number of arguments between
   * the values provided.
   *
   * Forward the magic "arguments" variable as second parameter on which the
   * parameter validation is performed:
   * validateBetweenNumberOfArgs('myFunction', arguments, 2, 3);
   */ function Ii(t, e, s, i) {
      if (e.length < s || e.length > i) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires between ${s} and ` + `${i} arguments, but was called with ` + Fi(e.length, "argument") + ".");
  }
  
  /**
   * Validates the provided argument is an array and has as least the expected
   * number of elements.
   */
  /**
   * Validates the provided positional argument has the native JavaScript type
   * using typeof checks.
   */
  function wi(t, e, s, i) {
      gi(t, e, `${Ci(s)} argument`, i);
  }
  
  /**
   * Validates the provided argument has the native JavaScript type using
   * typeof checks or is undefined.
   */ function Ri(t, e, s, i) {
      void 0 !== i && wi(t, e, s, i);
  }
  
  /**
   * Validates the provided named option has the native JavaScript type using
   * typeof checks.
   */ function mi(t, e, s, i) {
      gi(t, e, `${s} option`, i);
  }
  
  /**
   * Validates the provided named option has the native JavaScript type using
   * typeof checks or is undefined.
   */ function Ai(t, e, s, i) {
      void 0 !== i && mi(t, e, s, i);
  }
  
  function Pi(t, e, s, i, n) {
      void 0 !== i && function(t, e, s, i, n) {
          if (!(i instanceof Array)) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires its ${e} ` + `option to be an array, but it was: ${yi(i)}`);
          for (let r = 0; r < i.length; ++r) if (!n(i[r])) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires all ${e} ` + `elements to be ${s}, but the value at index ${r} ` + `was: ${yi(i[r])}`);
      }(t, e, s, i, n);
  }
  
  /**
   * Validates that the provided named option equals one of the expected values.
   */
  /**
   * Validates that the provided named option equals one of the expected values or
   * is undefined.
   */
  function Vi(t, e, s, i, n) {
      void 0 !== i && function(t, e, s, i, n) {
          const r = [];
          for (const t of n) {
              if (t === i) return;
              r.push(yi(t));
          }
          const h = yi(i);
          throw new R(w.INVALID_ARGUMENT, `Invalid value ${h} provided to function ${t}() for option ` + `"${s}". Acceptable values: ${r.join(", ")}`);
      }(t, 0, s, i, n);
  }
  
  /**
   * Validates that the provided argument is a valid enum.
   *
   * @param functionName Function making the validation call.
   * @param enums Array containing all possible values for the enum.
   * @param position Position of the argument in `functionName`.
   * @param argument Argument to validate.
   * @return The value as T if the argument can be converted.
   */
  /** Helper to validate the type of a provided input. */
  function gi(t, e, s, i) {
      let n = !1;
      if (n = "object" === e ? pi(i) : "non-empty string" === e ? "string" == typeof i && "" !== i : typeof i === e, 
      !n) {
          const n = yi(i);
          throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires its ${s} ` + `to be of type ${e}, but it was: ${n}`);
      }
  }
  
  /**
   * Returns true if it's a non-null object without a custom prototype
   * (i.e. excludes Array, Date, etc.).
   */ function pi(t) {
      return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));
  }
  
  /** Returns a string describing the type / value of the provided input. */ function yi(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;
              }
              /** Validates the provided argument is defined. */ (t);
              return e ? `a custom ${e} object` : "an object";
          }
      }
      return "function" == typeof t ? "a function" : be();
  }
  
  function bi(t, e, s) {
      if (void 0 === s) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires a valid ${Ci(e)} ` + "argument, but it was undefined.");
  }
  
  /**
   * Validates the provided positional argument is an object, and its keys and
   * values match the expected keys and types provided in optionTypes.
   */ function vi(t, e, s) {
      N(e, (e, i) => {
          if (s.indexOf(e) < 0) throw new R(w.INVALID_ARGUMENT, `Unknown option '${e}' passed to function ${t}(). ` + "Available options: " + s.join(", "));
      });
  }
  
  /**
   * Helper method to throw an error that the provided argument did not pass
   * an instanceof check.
   */ function Si(t, e, s, i) {
      const n = yi(i);
      return new R(w.INVALID_ARGUMENT, `Function ${t}() requires its ${Ci(s)} ` + `argument to be a ${e}, but it was: ${n}`);
  }
  
  function Di(t, e, s) {
      if (s <= 0) throw new R(w.INVALID_ARGUMENT, `Function "${t}()" requires its ${Ci(e)} argument to be a positive number, but it was: ${s}.`);
  }
  
  /** Converts a number to its english word representation */ function Ci(t) {
      switch (t) {
        case 1:
          return "first";
  
        case 2:
          return "second";
  
        case 3:
          return "third";
  
        default:
          return t + "th";
      }
  }
  
  /**
   * Formats the given word as plural conditionally given the preceding number.
   */ function Fi(t, e) {
      return `${t} ${e}` + (1 === t ? "" : "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.
   */
  /** Helper function to assert Uint8Array is available at runtime. */ function Ni() {
      if ("undefined" == typeof Uint8Array) throw new R(w.UNIMPLEMENTED, "Uint8Arrays are not available in this environment.");
  }
  
  /** Helper function to assert Base64 functions are available at runtime. */ function $i() {
      if (!me.nt().oc) throw new R(w.UNIMPLEMENTED, "Blobs are unavailable in Firestore in this environment.");
  }
  
  /**
   * Immutable class holding a blob (binary data).
   * This class is directly exposed in the public API.
   *
   * Note that while you can't hide the constructor in JavaScript code, we are
   * using the hack above to make sure no-one outside this module can call it.
   */ class ki {
      constructor(t) {
          $i(), this.ac = t;
      }
      static fromBase64String(t) {
          Ti("Blob.fromBase64String", arguments, 1), wi("Blob.fromBase64String", "string", 1, t), 
          $i();
          try {
              return new ki(k.fromBase64String(t));
          } catch (t) {
              throw new R(w.INVALID_ARGUMENT, "Failed to construct Blob from Base64 string: " + t);
          }
      }
      static fromUint8Array(t) {
          if (Ti("Blob.fromUint8Array", arguments, 1), Ni(), !(t instanceof Uint8Array)) throw Si("Blob.fromUint8Array", "Uint8Array", 1, t);
          return new ki(k.fromUint8Array(t));
      }
      toBase64() {
          return Ti("Blob.toBase64", arguments, 0), $i(), this.ac.toBase64();
      }
      toUint8Array() {
          return Ti("Blob.toUint8Array", arguments, 0), Ni(), this.ac.toUint8Array();
      }
      toString() {
          return "Blob(base64: " + this.toBase64() + ")";
      }
      isEqual(t) {
          return this.ac.isEqual(t.ac);
      }
  }
  
  /**
   * @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 Mi {
      /**
       * 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) {
          !function(t, e, s, i) {
              if (!(e instanceof Array) || e.length < i) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires its ${s} argument to be an ` + "array with at least " + `${Fi(i, "element")}.`);
          }("FieldPath", t, "fieldNames", 1);
          for (let e = 0; e < t.length; ++e) if (wi("FieldPath", "string", e, t[e]), 0 === t[e].length) throw new R(w.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty.");
          this.uc = new D(t);
      }
      static documentId() {
          return Mi.cc;
      }
      isEqual(t) {
          if (!(t instanceof Mi)) throw Si("isEqual", "FieldPath", 1, t);
          return this.uc.isEqual(t.uc);
      }
  }
  
  /**
   * 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.
   */ Mi.cc = new Mi(D.J().j());
  
  /**
   * Matches any characters in a field path string that are reserved.
   */
  const Li = new RegExp("[~\\*/\\[\\]]");
  
  /**
   * Parses a field path string into a FieldPath, treating dots as separators.
   */
  /**
   * @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 opaque base class for FieldValue sentinel objects in our public API,
   * with public static methods for creating said sentinel objects.
   */
  class Oi {
      constructor(t) {
          this._c = t;
      }
  }
  
  class xi extends Oi {
      constructor() {
          super("FieldValue.delete");
      }
      Di(t) {
          if (2 /* MergeSet */ !== t.lc) throw 1 /* Update */ === t.lc ? t.dc("FieldValue.delete() can only appear at the top level of your update data") : t.dc("FieldValue.delete() 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.Vt.push(t.path), null;
      }
      isEqual(t) {
          return t instanceof xi;
      }
  }
  
  class Bi extends Oi {
      constructor() {
          super("FieldValue.serverTimestamp");
      }
      Di(t) {
          return new ct(t.path, nt.instance);
      }
      isEqual(t) {
          return t instanceof Bi;
      }
  }
  
  class qi extends Oi {
      constructor(t) {
          super("FieldValue.arrayUnion"), this.fc = t;
      }
      Di(t) {
          // Although array transforms are used with writes, the actual elements
          // being uniomed or removed are not considered writes since they cannot
          // contain any FieldValue sentinels, etc.
          const e = new Hi({
              lc: 3 /* Argument */ ,
              methodName: this._c,
              Tc: !0
          }, t.ii, t.serializer), s = this.fc.map(t => Ji(t, e)), i = new rt(s);
          return new ct(t.path, i);
      }
      isEqual(t) {
          // TODO(mrschmidt): Implement isEquals
          return this === t;
      }
  }
  
  class Ui extends Oi {
      constructor(t) {
          super("FieldValue.arrayRemove"), this.fc = t;
      }
      Di(t) {
          // Although array transforms are used with writes, the actual elements
          // being unioned or removed are not considered writes since they cannot
          // contain any FieldValue sentinels, etc.
          const e = new Hi({
              lc: 3 /* Argument */ ,
              methodName: this._c,
              Tc: !0
          }, t.ii, t.serializer), s = this.fc.map(t => Ji(t, e)), i = new ht(s);
          return new ct(t.path, i);
      }
      isEqual(t) {
          // TODO(mrschmidt): Implement isEquals
          return this === t;
      }
  }
  
  class Qi extends Oi {
      constructor(t) {
          super("FieldValue.increment"), this.Ec = t;
      }
      Di(t) {
          const e = new Hi({
              lc: 3 /* Argument */ ,
              methodName: this._c
          }, t.ii, t.serializer), s = Ji(this.Ec, e), i = new ot(t.serializer, s);
          return new ct(t.path, i);
      }
      isEqual(t) {
          // TODO(mrschmidt): Implement isEquals
          return 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.
   */
  /**
   * Immutable class representing a geo point as latitude-longitude pair.
   * This class is directly exposed in the public API, including its constructor.
   */
  class Wi {
      constructor(t, e) {
          if (Ti("GeoPoint", arguments, 2), wi("GeoPoint", "number", 1, t), wi("GeoPoint", "number", 2, e), 
          !isFinite(t) || t < -90 || t > 90) throw new R(w.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + t);
          if (!isFinite(e) || e < -180 || e > 180) throw new R(w.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + e);
          this.Ic = t, this.wc = e;
      }
      /**
       * Returns the latitude of this geo point, a number between -90 and 90.
       */    get latitude() {
          return this.Ic;
      }
      /**
       * Returns the longitude of this geo point, a number between -180 and 180.
       */    get longitude() {
          return this.wc;
      }
      isEqual(t) {
          return this.Ic === t.Ic && this.wc === t.wc;
      }
      /**
       * Actually private to JS consumers of our API, so this function is prefixed
       * with an underscore.
       */    p(t) {
          return Ce(this.Ic, t.Ic) || Ce(this.wc, t.wc);
      }
  }
  
  /**
   * @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 ji = /^__.*__$/;
  
  /** The result of parsing document data (e.g. for a setData call). */ class Ki {
      constructor(t, e, s) {
          this.data = t, this.Vt = e, this.fieldTransforms = s;
      }
      Rc(t, e) {
          const s = [];
          return null !== this.Vt ? s.push(new Tt(t, this.data, this.Vt, e)) : s.push(new ft(t, this.data, e)), 
          this.fieldTransforms.length > 0 && s.push(new Et(t, this.fieldTransforms)), s;
      }
  }
  
  /** The result of parsing "update" data (i.e. for an updateData call). */ class Gi {
      constructor(t, e, s) {
          this.data = t, this.Vt = e, this.fieldTransforms = s;
      }
      Rc(t, e) {
          const s = [ new Tt(t, this.data, this.Vt, e) ];
          return this.fieldTransforms.length > 0 && s.push(new Et(t, this.fieldTransforms)), 
          s;
      }
  }
  
  function zi(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 be();
      }
  }
  
  /** A "context" object passed around while parsing user data. */ class Hi {
      /**
       * 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 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, s, i, n) {
          this.settings = t, this.ii = e, this.serializer = 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.mc(), this.fieldTransforms = i || [], this.Vt = n || [];
      }
      get path() {
          return this.settings.path;
      }
      get lc() {
          return this.settings.lc;
      }
      /** Returns a new context with the specified settings overwritten. */    Ac(t) {
          return new Hi(Object.assign(Object.assign({}, this.settings), t), this.ii, this.serializer, this.fieldTransforms, this.Vt);
      }
      Pc(t) {
          var e;
          const s = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), i = this.Ac({
              path: s,
              Tc: !1
          });
          return i.Vc(t), i;
      }
      gc(t) {
          var e;
          const s = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), i = this.Ac({
              path: s,
              Tc: !1
          });
          return i.mc(), i;
      }
      pc(t) {
          // TODO(b/34871131): We don't support array paths right now; so make path
          // undefined.
          return this.Ac({
              path: void 0,
              Tc: !0
          });
      }
      dc(t) {
          const e = !this.path || this.path.B() ? "" : ` (found in field ${this.path.toString()})`;
          return new R(w.INVALID_ARGUMENT, `Function ${this.settings.methodName}() called with invalid data. ` + t + e);
      }
      /** Returns 'true' if 'fieldPath' was traversed when creating this context. */    contains(t) {
          return void 0 !== this.Vt.find(e => t.q(e)) || void 0 !== this.fieldTransforms.find(e => t.q(e.field));
      }
      mc() {
          // 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.Vc(this.path.get(t));
      }
      Vc(t) {
          if (0 === t.length) throw this.dc("Document fields must not be empty");
          if (zi(this.lc) && ji.test(t)) throw this.dc('Document fields cannot begin and end with "__"');
      }
  }
  
  /**
   * Helper for parsing raw user input (provided via the API) into internal model
   * classes.
   */ class Yi {
      constructor(t, e) {
          this.ii = t, this.serializer = e || me.nt().yc(t);
      }
      /** Parse document data from a non-merge set() call. */    bc(t, e) {
          const s = this.vc(0 /* Set */ , t);
          tn("Data must be an object, but it was:", s, e);
          const i = Xi(e, s);
          return new Ki(new Rt(i), 
          /* fieldMask= */ null, s.fieldTransforms);
      }
      /** Parse document data from a set() call with '{merge:true}'. */    Sc(t, e, s) {
          const i = this.vc(2 /* MergeSet */ , t);
          tn("Data must be an object, but it was:", i, e);
          const n = Xi(e, i);
          let r, h;
          if (s) {
              const e = [];
              for (const n of s) {
                  let s;
                  if (n instanceof Mi) s = n.uc; else {
                      if ("string" != typeof n) throw be();
                      s = sn(t, n);
                  }
                  if (!i.contains(s)) throw new R(w.INVALID_ARGUMENT, `Field '${s}' is specified in your field mask but missing from your input data.`);
                  nn(e, s) || e.push(s);
              }
              r = new ut(e), h = i.fieldTransforms.filter(t => r.dt(t.field));
          } else r = new ut(i.Vt), h = i.fieldTransforms;
          return new Ki(new Rt(n), r, h);
      }
      /** Parse update data from an update() call. */    Dc(t, e) {
          const s = this.vc(1 /* Update */ , t);
          tn("Data must be an object, but it was:", s, e);
          const i = [], n = new mt;
          N(e, (e, r) => {
              const h = sn(t, e), o = s.gc(h);
              if (r instanceof xi) 
              // Add it to the field mask, but don't add anything to updateData.
              i.push(h); else {
                  const t = Ji(r, o);
                  null != t && (i.push(h), n.set(h, t));
              }
          });
          const r = new ut(i);
          return new Gi(n.yt(), r, s.fieldTransforms);
      }
      /** Parse update data from a list of field/value arguments. */    Cc(t, e, s, i) {
          const n = this.vc(1 /* Update */ , t), r = [ en(t, e) ], h = [ s ];
          if (i.length % 2 != 0) throw new R(w.INVALID_ARGUMENT, `Function ${t}() needs to be called with an even number ` + "of arguments that alternate between field names and values.");
          for (let e = 0; e < i.length; e += 2) r.push(en(t, i[e])), h.push(i[e + 1]);
          const o = [], a = new mt;
          // We iterate in reverse order to pick the last value for a field if the
          // user specified the field multiple times.
          for (let t = r.length - 1; t >= 0; --t) if (!nn(o, r[t])) {
              const e = r[t], s = h[t], i = n.gc(e);
              if (s instanceof xi) 
              // Add it to the field mask, but don't add anything to updateData.
              o.push(e); else {
                  const t = Ji(s, i);
                  null != t && (o.push(e), a.set(e, t));
              }
          }
          const u = new ut(o);
          return new Gi(a.yt(), u, n.fieldTransforms);
      }
      /** Creates a new top-level parse context. */    vc(t, e) {
          return new Hi({
              lc: t,
              methodName: e,
              path: D.G,
              Tc: !1
          }, this.ii, this.serializer);
      }
      /**
       * 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).
       */    Fc(t, e, s = !1) {
          return Ji(e, this.vc(s ? 4 /* ArrayArgument */ : 3 /* Argument */ , t));
      }
  }
  
  /**
   * 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.
   * @return The parsed value, or null if the value was a FieldValue sentinel
   * that should not be included in the resulting parsed data.
   */ function Ji(t, e) {
      if (Zi(t)) return tn("Unsupported field value:", e, t), Xi(t, e);
      if (t instanceof Oi) 
      // 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 (!zi(e.lc)) throw e.dc(`${t._c}() can only be used with update() and set()`);
          if (null === e.path) throw e.dc(`${t._c}() is not currently supported inside arrays`);
          const s = t.Di(e);
          s && e.fieldTransforms.push(s);
      }
      /**
   * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)
   *
   * @return 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.Vt.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.Tc && 4 /* ArrayArgument */ !== e.lc) throw e.dc("Nested arrays are not supported");
          return function(t, e) {
              const s = [];
              let i = 0;
              for (const n of t) {
                  let t = Ji(n, e.pc(i));
                  null == t && (
                  // Just include nulls in the array for fields being replaced with a
                  // sentinel.
                  t = {
                      nullValue: "NULL_VALUE"
                  }), s.push(t), i++;
              }
              return {
                  arrayValue: {
                      values: s
                  }
              };
          }(t, e);
      }
      return function(t, e) {
          if (null === t) return {
              nullValue: "NULL_VALUE"
          };
          if ("number" == typeof t) return e.serializer.ai(t);
          if ("boolean" == typeof t) return {
              booleanValue: t
          };
          if ("string" == typeof t) return {
              stringValue: t
          };
          if (t instanceof Date) {
              const s = p.fromDate(t);
              return {
                  timestampValue: e.serializer.C(s)
              };
          }
          if (t instanceof p) {
              // 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 s = new p(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));
              return {
                  timestampValue: e.serializer.C(s)
              };
          }
          if (t instanceof Wi) return {
              geoPointValue: {
                  latitude: t.latitude,
                  longitude: t.longitude
              }
          };
          if (t instanceof ki) return {
              bytesValue: e.serializer.ui(t)
          };
          if (t instanceof Jn) {
              const s = e.ii, i = t.firestore.Nc;
              if (!i.isEqual(s)) throw e.dc("Document reference is for database " + `${i.projectId}/${i.database} but should be ` + `for database ${s.projectId}/${s.database}`);
              return {
                  referenceValue: e.serializer._i(t.$c.path, t.firestore.Nc)
              };
          }
          throw e.dc(`Unsupported field value: ${yi(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 Xi(t, e) {
      const s = {};
      return $(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.Vt.push(e.path) : N(t, (t, i) => {
          const n = Ji(i, e.Pc(t));
          null != n && (s[t] = n);
      }), {
          mapValue: {
              fields: s
          }
      };
  }
  
  function Zi(t) {
      return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof p || t instanceof Wi || t instanceof ki || t instanceof Jn || t instanceof Oi);
  }
  
  function tn(t, e, s) {
      if (!Zi(s) || !pi(s)) {
          const i = yi(s);
          throw "an object" === i ? e.dc(t + " a custom object") : e.dc(t + " " + i);
      }
  }
  
  /**
   * Helper that calls fromDotSeparatedString() but wraps any error thrown.
   */ function en(t, e) {
      if (e instanceof Mi) return e.uc;
      if ("string" == typeof e) return sn(t, e);
      throw new R(w.INVALID_ARGUMENT, `Function ${t}() called with invalid data. ${"Field path arguments must be of type string or FieldPath."}`);
  }
  
  /**
   * 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.
   */ function sn(t, e) {
      try {
          return function(t) {
              if (t.search(Li) >= 0) throw new R(w.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not contain ` + "'~', '*', '/', '[', or ']'");
              try {
                  return new Mi(...t.split("."));
              } catch (e) {
                  throw new R(w.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, ` + "begin with '.', end with '.', or contain '..'");
              }
          }(e).uc;
      } catch (e) {
          const i = (s = e) instanceof Error ? s.message : s.toString();
          throw new R(w.INVALID_ARGUMENT, `Function ${t}() called with invalid data. ${i}`);
      }
      /**
   * Extracts the message from a caught exception, which should be an Error object
   * though JS doesn't guarantee that.
   */
      var s;
      /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */}
  
  function nn(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.
   */
  /**
   * 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 rn {
      constructor(t, e, s, i, n, r) {
          this.Tr = t, this.kc = s, this.Mc = i, this.Lc = n, 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.Oc = 0, this.xc = null, this.stream = null, this.Na = new Ge(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.
       */    Bc() {
          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.
       */    qc() {
          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.Uc();
      }
      /**
       * 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.Bc() && 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.
       */    Qc() {
          this.state = 0 /* Initial */ , this.Na.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.
       */    Wc() {
          // 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.qc() && null === this.xc && (this.xc = this.Tr.yr(this.kc, 6e4, () => this.jc()));
      }
      /** Sends a message to the underlying stream. */    Kc(t) {
          this.Gc(), this.stream.send(t);
      }
      /** Called by the idle timer when the stream should close due to inactivity. */    async jc() {
          if (this.qc()) 
          // 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. */    Gc() {
          this.xc && (this.xc.cancel(), this.xc = 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.Gc(), this.Na.cancel(), 
          // Invalidates any stream-related callbacks (e.g. from auth or the
          // underlying stream), guaranteeing they won't execute.
          this.Oc++, 3 /* Error */ !== t ? 
          // If this is an intentional close ensure we don't delay our next connection attempt.
          this.Na.reset() : e && e.code === w.RESOURCE_EXHAUSTED ? (
          // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)
          pe(e.toString()), pe("Using maximum backoff delay to prevent overloading the backend."), 
          this.Na.Vr()) : e && e.code === w.UNAUTHENTICATED && 
          // "unauthenticated" error means the token was rejected. Try force refreshing it in case it
          // just expired.
          this.Lc._(), 
          // Clean up the underlying stream because we are no longer interested in events.
          null !== this.stream && (this.zc(), 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.Hc(e);
      }
      /**
       * Can be overridden to perform additional cleanup before the stream is closed.
       * Calling super.tearDown() is not required.
       */    zc() {}
      auth() {
          this.state = 1 /* Starting */;
          const t = this.Yc(this.Oc), e = this.Oc;
          // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.
                  this.Lc.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.Oc === 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.Jc(t);
          }, e => {
              t(() => {
                  const t = new R(w.UNKNOWN, "Fetching auth token failed: " + e.message);
                  return this.Xc(t);
              });
          });
      }
      Jc(t) {
          const e = this.Yc(this.Oc);
          this.stream = this.Zc(t), this.stream.t_(() => {
              e(() => (this.state = 2 /* Open */ , this.listener.t_()));
          }), this.stream.Hc(t => {
              e(() => this.Xc(t));
          }), this.stream.onMessage(t => {
              e(() => this.onMessage(t));
          });
      }
      Uc() {
          this.state = 4 /* Backoff */ , this.Na.gr(async () => {
              this.state = 0 /* Initial */ , this.start();
          });
      }
      // Visible for tests
      Xc(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 ge("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.
       */    Yc(t) {
          return e => {
              this.Tr.oo(() => this.Oc === t ? e() : (ge("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 hn extends rn {
      constructor(t, e, s, i, n) {
          super(t, "listen_stream_connection_backoff" /* ListenStreamConnectionBackoff */ , "listen_stream_idle" /* ListenStreamIdle */ , e, s, n), 
          this.serializer = i;
      }
      Zc(t) {
          return this.Mc.e_("Listen", t);
      }
      onMessage(t) {
          // A successful response means the stream is healthy
          this.Na.reset();
          const e = this.serializer.pi(t), s = this.serializer.bi(t);
          return this.listener.s_(e, s);
      }
      /**
       * 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.
       */    i_(t) {
          const e = {};
          e.database = this.serializer.wi, e.addTarget = this.serializer.ee(t);
          const s = this.serializer.zi(t);
          s && (e.labels = s), this.Kc(e);
      }
      /**
       * Unregisters interest in the results of the target associated with the
       * given targetId.
       */    n_(t) {
          const e = {};
          e.database = this.serializer.wi, e.removeTarget = t, this.Kc(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 on extends rn {
      constructor(t, e, s, i, n) {
          super(t, "write_stream_connection_backoff" /* WriteStreamConnectionBackoff */ , "write_stream_idle" /* WriteStreamIdle */ , e, s, n), 
          this.serializer = i, this.r_ = !1, 
          /**
           * The last received stream token from the server, used to acknowledge which
           * responses the client has processed. Stream tokens are opaque checkpoint
           * markers whose only real value is their inclusion in the next request.
           *
           * PersistentWriteStream manages propagating this value from responses to the
           * next request.
           */
          this.lastStreamToken = k.ht;
      }
      /**
       * Tracks whether or not a handshake has been successfully exchanged and
       * the stream is ready to accept mutations.
       */    get h_() {
          return this.r_;
      }
      // Override of PersistentStream.start
      start() {
          this.r_ = !1, super.start();
      }
      zc() {
          this.r_ && this.o_([]);
      }
      Zc(t) {
          return this.Mc.e_("Write", t);
      }
      onMessage(t) {
          if (
          // Always capture the last stream token.
          ve(!!t.streamToken), this.lastStreamToken = this.serializer.ci(t.streamToken), this.r_) {
              // 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.Na.reset();
              const e = this.serializer.Li(t.writeResults, t.commitTime), s = this.serializer.fromVersion(t.commitTime);
              return this.listener.a_(s, e);
          }
          // The first response is always the handshake response
          return ve(!t.writeResults || 0 === t.writeResults.length), this.r_ = !0, this.listener.u_();
      }
      /**
       * 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.
       */    c_() {
          // 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 = this.serializer.wi, this.Kc(t);
      }
      /** Sends a group of mutations to the Firestore backend to apply. */    o_(t) {
          const e = {
              streamToken: this.serializer.ui(this.lastStreamToken),
              writes: t.map(t => this.serializer.vi(t))
          };
          this.Kc(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 an extends class {
      constructor() {
          // Make sure that the structural type of `Datastore` is unique.
          // See https://github.com/microsoft/TypeScript/issues/5451
          this.__ = void 0;
      }
  } {
      constructor(t, e, s) {
          super(), this.Mc = t, this.credentials = e, this.serializer = s;
      }
      /** Gets an auth token and invokes the provided RPC. */    l_(t, e) {
          return this.credentials.getToken().then(s => this.Mc.l_(t, e, s)).catch(t => {
              throw t.code === w.UNAUTHENTICATED && this.credentials._(), t;
          });
      }
      /** Gets an auth token and invokes the provided RPC with streamed results. */    d_(t, e) {
          return this.credentials.getToken().then(s => this.Mc.d_(t, e, s)).catch(t => {
              throw t.code === w.UNAUTHENTICATED && this.credentials._(), 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.
   */
  /**
   * Internal transaction object responsible for accumulating the mutations to
   * perform and the base versions for any documents read.
   */
  class un {
      constructor(t) {
          this.f_ = t, 
          // The version of each document that was read during this transaction.
          this.T_ = Zt(), this.mutations = [], this.E_ = !1, 
          /**
           * A deferred usage error that occurred previously in this transaction that
           * will cause the transaction to fail once it actually commits.
           */
          this.I_ = 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.w_ = new Set;
      }
      async R_(t) {
          if (this.m_(), this.mutations.length > 0) throw new R(w.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes.");
          const e = await async function(t, e) {
              const s = Se(t), i = {
                  database: s.serializer.wi,
                  documents: e.map(t => s.serializer.fi(t))
              }, n = await s.d_("BatchGetDocuments", i), r = new Map;
              n.forEach(t => {
                  const e = s.serializer.gi(t);
                  r.set(e.key.toString(), e);
              });
              const h = [];
              return e.forEach(t => {
                  const e = r.get(t.toString());
                  ve(!!e), h.push(e);
              }), h;
          }(this.f_, t);
          return e.forEach(t => {
              t instanceof gt || t instanceof Vt ? this.A_(t) : be();
          }), e;
      }
      set(t, e) {
          this.write(e.Rc(t, this.Rt(t))), this.w_.add(t);
      }
      update(t, e) {
          try {
              this.write(e.Rc(t, this.P_(t)));
          } catch (t) {
              this.I_ = t;
          }
          this.w_.add(t);
      }
      delete(t) {
          this.write([ new It(t, this.Rt(t)) ]), this.w_.add(t);
      }
      async commit() {
          if (this.m_(), this.I_) throw this.I_;
          let t = this.T_;
          // For each mutation, note that the doc was written.
                  this.mutations.forEach(e => {
              t = t.remove(e.key);
          }), 
          // For each document that was read but not written to, we want to perform
          // a `verify` operation.
          t.forEach((t, e) => {
              this.mutations.push(new wt(t, this.Rt(t)));
          }), await async function(t, e) {
              const s = Se(t), i = {
                  database: s.serializer.wi,
                  writes: e.map(t => s.serializer.vi(t))
              }, n = await s.l_("Commit", i);
              return s.serializer.Li(n.writeResults, n.commitTime);
          }(this.f_, this.mutations), this.E_ = !0;
      }
      A_(t) {
          let e;
          if (t instanceof Vt) e = t.version; else {
              if (!(t instanceof gt)) throw be();
              // For deleted docs, we must use baseVersion 0 when we overwrite them.
              e = y.min();
          }
          const s = this.T_.get(t.key);
          if (null !== s) {
              if (!e.isEqual(s)) 
              // This transaction will fail no matter what.
              throw new R(w.ABORTED, "Document version changed between two reads.");
          } else this.T_ = this.T_.me(t.key, 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.
       */    Rt(t) {
          const e = this.T_.get(t);
          return !this.w_.has(t) && e ? lt.updateTime(e) : lt.ft();
      }
      /**
       * Returns the precondition for a document if the operation is an update.
       */    P_(t) {
          const e = this.T_.get(t);
          // The first time a document is written, we want to take into account the
          // read time and existence
                  if (!this.w_.has(t) && e) {
              if (e.isEqual(y.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 R(w.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
              // Document exists, base precondition on document update time.
                          return lt.updateTime(e);
          }
          // Document was not read, so we just use the preconditions for a blind
          // update.
          return lt.exists(!0);
      }
      write(t) {
          this.m_(), this.mutations = this.mutations.concat(t);
      }
      m_() {}
  }
  
  /**
   * @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.
   */
  /**
   * 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 cn {
      constructor(t, e) {
          this.wa = t, this.V_ = 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.g_ = 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.p_ = 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.y_ = !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.
       */    b_() {
          0 === this.g_ && (this.v_("Unknown" /* Unknown */), this.p_ = this.wa.yr("online_state_timeout" /* OnlineStateTimeout */ , 1e4, () => (this.p_ = null, 
          this.S_("Backend didn't respond within 10 seconds."), this.v_("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.
       */    D_(t) {
          "Online" /* Online */ === this.state ? this.v_("Unknown" /* Unknown */) : (this.g_++, 
          this.g_ >= 1 && (this.C_(), this.S_("Connection failed 1 " + `times. Most recent error: ${t.toString()}`), 
          this.v_("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.C_(), this.g_ = 0, "Online" /* Online */ === t && (
          // We've connected to watch at least once. Don't warn the developer
          // about being offline going forward.
          this.y_ = !1), this.v_(t);
      }
      v_(t) {
          t !== this.state && (this.state = t, this.V_(t));
      }
      S_(t) {
          const e = `Could not reach Cloud Firestore backend. ${t}\n` + "This 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.y_ ? (pe(e), this.y_ = !1) : ge("OnlineStateTracker", e);
      }
      C_() {
          null !== this.p_ && (this.p_.cancel(), this.p_ = 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.
   */
  /**
   * RemoteStore - An interface to remotely stored data, basically providing a
   * wrapper around the Datastore that is more reliable for the rest of the
   * system.
   *
   * RemoteStore is responsible for maintaining the connection to the server.
   * - maintaining a list of active listens.
   * - reconnecting when the connection is dropped.
   * - resuming all the active listens on reconnect.
   *
   * RemoteStore handles all incoming events from the Datastore.
   * - listening to the watch stream and repackaging the events as RemoteEvents
   * - notifying SyncEngine of any changes to the active listens.
   *
   * RemoteStore takes writes from other components and handles them reliably.
   * - pulling pending mutations from LocalStore and sending them to Datastore.
   * - retrying mutations that failed because of network problems.
   * - acking mutations to the SyncEngine once they are accepted or rejected.
   */
  class _n {
      constructor(
      /**
       * The local store, used to fill the write pipeline with outbound mutations.
       */
      t, 
      /** The client-side proxy for interacting with the backend. */
      e, s, i, n) {
          this.F_ = t, this.f_ = e, this.wa = s, 
          /**
           * 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.N_ = [], 
          /**
           * 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.k_ = new Map, this.M_ = null, 
          /**
           * Set to true by enableNetwork() and false by disableNetwork() and indicates
           * the user-preferred network state.
           */
          this.networkEnabled = !1, this.isPrimary = !1, 
          /**
           * When set to `true`, the network was taken offline due to an IndexedDB
           * failure. The state is flipped to `false` when access becomes available
           * again.
           */
          this.L_ = !1, this.O_ = n, this.O_.x_(t => {
              s.oo(async () => {
                  this.B_() && (ge("RemoteStore", "Restarting streams for network reachability change."), 
                  await this.q_());
              });
          }), this.U_ = new cn(s, i), 
          // Create streams (but note they're not started yet).
          this.Q_ = function(t, e, s) {
              const i = Se(t);
              return new hn(e, i.Mc, i.credentials, i.serializer, s);
          }(this.f_, s, {
              t_: this.W_.bind(this),
              Hc: this.j_.bind(this),
              s_: this.K_.bind(this)
          }), this.G_ = function(t, e, s) {
              const i = Se(t);
              return new on(e, i.Mc, i.credentials, i.serializer, s);
          }(this.f_, s, {
              t_: this.z_.bind(this),
              Hc: this.H_.bind(this),
              u_: this.Y_.bind(this),
              a_: this.a_.bind(this)
          });
      }
      /**
       * Starts up the remote store, creating streams, restoring state from
       * LocalStore, etc.
       */    start() {
          return this.enableNetwork();
      }
      /** Re-enables the network. Idempotent. */    enableNetwork() {
          return this.networkEnabled = !0, this.J_();
      }
      async J_() {
          this.B_() && (this.G_.lastStreamToken = await this.F_.zo(), this.X_() ? this.Z_() : this.U_.set("Unknown" /* Unknown */), 
          // This will start the write stream if necessary.
          await this.tl());
      }
      /**
       * Temporarily disables the network. The network can be re-enabled using
       * enableNetwork().
       */    async disableNetwork() {
          this.networkEnabled = !1, await this.el(), 
          // Set the OnlineState to Offline so get()s return from cache, etc.
          this.U_.set("Offline" /* Offline */);
      }
      async el() {
          await this.G_.stop(), await this.Q_.stop(), this.N_.length > 0 && (ge("RemoteStore", `Stopping write stream with ${this.N_.length} pending writes`), 
          this.N_ = []), this.sl();
      }
      async Ro() {
          ge("RemoteStore", "RemoteStore shutting down."), this.networkEnabled = !1, await this.el(), 
          this.O_.Ro(), 
          // Set the OnlineState to Unknown (rather than Offline) to avoid potentially
          // triggering spurious listener events with cached data, etc.
          this.U_.set("Unknown" /* Unknown */);
      }
      /**
       * 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.
       */    listen(t) {
          this.k_.has(t.targetId) || (
          // Mark this as something the client is currently listening for.
          this.k_.set(t.targetId, t), this.X_() ? 
          // The listen will be sent in onWatchStreamOpen
          this.Z_() : this.Q_.qc() && this.il(t));
      }
      /**
       * Removes the listen from server. It is a no-op if the given target id is
       * not being listened to.
       */    nl(t) {
          this.k_.delete(t), this.Q_.qc() && this.rl(t), 0 === this.k_.size && (this.Q_.qc() ? this.Q_.Wc() : this.B_() && 
          // 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.
          this.U_.set("Unknown" /* Unknown */));
      }
      /** {@link TargetMetadataProvider.getTargetDataForTarget} */    si(t) {
          return this.k_.get(t) || null;
      }
      /** {@link TargetMetadataProvider.getRemoteKeysForTarget} */    ei(t) {
          return this.hl.ei(t);
      }
      /**
       * 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.
       */    il(t) {
          this.M_.Ns(t.targetId), this.Q_.i_(t);
      }
      /**
       * 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.
       */    rl(t) {
          this.M_.Ns(t), this.Q_.n_(t);
      }
      Z_() {
          this.M_ = new de(this), this.Q_.start(), this.U_.b_();
      }
      /**
       * Returns whether the watch stream should be started because it's necessary
       * and has not yet been started.
       */    X_() {
          return this.B_() && !this.Q_.Bc() && this.k_.size > 0;
      }
      B_() {
          return !this.L_ && this.isPrimary && this.networkEnabled;
      }
      sl() {
          this.M_ = null;
      }
      async W_() {
          this.k_.forEach((t, e) => {
              this.il(t);
          });
      }
      async j_(t) {
          this.sl(), 
          // If we still need the watch stream, retry the connection.
          this.X_() ? (this.U_.D_(t), this.Z_()) : 
          // 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
          this.U_.set("Unknown" /* Unknown */);
      }
      async K_(t, e) {
          if (
          // Mark the client as online since we got a message from the server
          this.U_.set("Online" /* Online */), t instanceof _e && 2 /* Removed */ === t.state && t.cause) 
          // There was an error on a target, don't wait for a consistent snapshot
          // to raise events
          try {
              await this.ol(t);
          } catch (e) {
              ge("RemoteStore", "Failed to remove targets %s: %s ", t.targetIds.join(","), e), 
              await this.al(e);
          } else if (t instanceof ue ? this.M_.qs(t) : t instanceof ce ? this.M_.Hs(t) : this.M_.Ws(t), 
          !e.isEqual(y.min())) try {
              const t = await this.F_.ah();
              e.S(t) >= 0 && 
              // We have received a target change with a global snapshot if the snapshot
              // version is not equal to SnapshotVersion.min().
              await this.ul(e);
          } catch (t) {
              ge("RemoteStore", "Failed to raise snapshot:", t), await this.al(t);
          }
      }
      /**
       * Recovery logic for IndexedDB errors that takes the network offline until
       * IndexedDb probing succeeds. Retries are scheduled with backoff using
       * `enqueueRetryable()`.
       */    async al(t) {
          if (!zs(t)) throw t;
          this.L_ = !0, 
          // Disable network and raise offline snapshots
          await this.el(), this.U_.set("Offline" /* Offline */), 
          // Probe IndexedDB periodically and re-enable network
          this.wa.Ua(async () => {
              ge("RemoteStore", "Retrying IndexedDB access"), 
              // Issue 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.
              await this.F_.ah(), this.L_ = !1, await this.J_();
          });
      }
      /**
       * 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.
       */    ul(t) {
          const e = this.M_.Xs(t);
          // Update in-memory resume tokens. LocalStore will update the
          // persistent view of these when applying the completed RemoteEvent.
                  // Finally raise remote event
          return e.as.forEach((e, s) => {
              if (e.resumeToken.rt() > 0) {
                  const i = this.k_.get(s);
                  // A watched target might have been removed already.
                                  i && this.k_.set(s, i.we(e.resumeToken, t));
              }
          }), 
          // Re-establish listens for the targets that have been invalidated by
          // existence filter mismatches.
          e.us.forEach(t => {
              const e = this.k_.get(t);
              if (!e) 
              // A watched target might have been removed already.
              return;
              // Clear the resume token for the target, since we're in a known mismatch
              // state.
                          this.k_.set(t, e.we(k.ht, e.Ee)), 
              // Cause a hard reset by unwatching and rewatching immediately, but
              // deliberately don't send a resume token so that we get a full update.
              this.rl(t);
              // 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 Mt(e.target, t, 1 /* ExistenceFilterMismatch */ , e.sequenceNumber);
              this.il(s);
          }), this.hl.Mu(e);
      }
      /** Handles an error on a target */    async ol(t) {
          const e = t.cause;
          for (const s of t.targetIds) 
          // A watched target might have been removed already.
          this.k_.has(s) && (await this.hl.cl(s, e), this.k_.delete(s), this.M_.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.
       */    async tl() {
          if (this._l()) {
              const t = this.N_.length > 0 ? this.N_[this.N_.length - 1].batchId : -1, e = await this.F_.Bu(t);
              null === e ? 0 === this.N_.length && this.G_.Wc() : (this.ll(e), await this.tl());
          }
          this.dl() && this.fl();
      }
      /**
       * Returns true if we can add to the write pipeline (i.e. the network is
       * enabled and the write pipeline is not full).
       */    _l() {
          return this.B_() && this.N_.length < 10;
      }
      // For testing
      Tl() {
          return this.N_.length;
      }
      /**
       * Queues additional writes to be sent to the write stream, sending them
       * immediately if the write stream is established.
       */    ll(t) {
          this.N_.push(t), this.G_.qc() && this.G_.h_ && this.G_.o_(t.mutations);
      }
      dl() {
          return this.B_() && !this.G_.Bc() && this.N_.length > 0;
      }
      fl() {
          this.G_.start();
      }
      async z_() {
          this.G_.c_();
      }
      Y_() {
          // Record the stream token.
          return this.F_.Ho(this.G_.lastStreamToken).then(() => {
              // Send the write pipeline now that the stream is established.
              for (const t of this.N_) this.G_.o_(t.mutations);
          }).catch(_i);
      }
      a_(t, e) {
          const s = this.N_.shift(), i = Oe.from(s, t, e, this.G_.lastStreamToken);
          return this.hl.El(i).then(() => this.tl());
      }
      async H_(t) {
          // If the write stream closed due to an error, invoke the error callbacks if
          // there are pending writes.
          t && this.N_.length > 0 && (this.G_.h_ ? 
          // This error affects the actual write.
          await this.Il(t) : 
          // If there was an error before the handshake has finished, it's
          // possible that the server is unable to process the stream token
          // we're sending. (Perhaps it's too old?)
          await this.wl(t), 
          // The write stream might have been started by refilling the write
          // pipeline for failed writes
          this.dl() && this.fl());
          // No pending writes, nothing to do
          }
      async wl(t) {
          // Reset the token if it's a permanent error, signaling the write stream is
          // no longer valid. Note that the handshake does not count as a write: see
          // comments on isPermanentWriteError for details.
          if (Bt(t.code)) return ge("RemoteStore", "RemoteStore error before completed handshake; resetting stream token: ", this.G_.lastStreamToken), 
          this.G_.lastStreamToken = k.ht, this.F_.Ho(k.ht).catch(_i);
      }
      async Il(t) {
          // Only handle permanent errors here. If it's transient, just let the retry
          // logic kick in.
          if (Bt(e = t.code) && e !== w.ABORTED) {
              // This was a permanent error, the request itself was the problem
              // so it's not going to succeed if we resend it.
              const e = this.N_.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.
                          return this.G_.Qc(), this.hl.Rl(e.batchId, t).then(() => this.tl());
          }
          var 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.
   */    }
      ml() {
          return new un(this.f_);
      }
      async q_() {
          this.networkEnabled = !1, await this.el(), this.U_.set("Unknown" /* Unknown */), 
          await this.enableNetwork();
      }
      async Al() {
          this.B_() && (
          // 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).
          ge("RemoteStore", "RemoteStore restarting streams for new credential"), await this.q_());
      }
      /**
       * Toggles the network state when the client gains or loses its primary lease.
       */    async Pl(t) {
          this.isPrimary = t, t && this.networkEnabled ? await this.enableNetwork() : t || (await this.el(), 
          this.U_.set("Unknown" /* Unknown */));
      }
  }
  
  /**
   * @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 ln(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 dn(t, e, s) {
      let i = `firestore_mutations_${t}_${s}`;
      return e.t() && (i += `_${e.uid}`), i;
  }
  
  // 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 fn(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 Tn {
      constructor(t, e, s, i) {
          this.user = t, this.batchId = e, this.state = s, this.error = i;
      }
      /**
       * 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 Vl(t, e, s) {
          const i = JSON.parse(s);
          let n = "object" == typeof i && -1 !== [ "pending", "acknowledged", "rejected" ].indexOf(i.state) && (void 0 === i.error || "object" == typeof i.error), r = void 0;
          return n && i.error && (n = "string" == typeof i.error.message && "string" == typeof i.error.code, 
          n && (r = new R(i.error.code, i.error.message))), n ? new Tn(t, e, i.state, r) : (pe("SharedClientState", `Failed to parse mutation state for ID '${e}': ${s}`), 
          null);
      }
      gl() {
          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 En {
      constructor(t, e, s) {
          this.targetId = t, this.state = e, this.error = s;
      }
      /**
       * 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 Vl(t, e) {
          const s = JSON.parse(e);
          let i = "object" == typeof s && -1 !== [ "not-current", "current", "rejected" ].indexOf(s.state) && (void 0 === s.error || "object" == typeof s.error), n = void 0;
          return i && s.error && (i = "string" == typeof s.error.message && "string" == typeof s.error.code, 
          i && (n = new R(s.error.code, s.error.message))), i ? new En(t, s.state, n) : (pe("SharedClientState", `Failed to parse target state for ID '${t}': ${e}`), 
          null);
      }
      gl() {
          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 In {
      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 Vl(t, e) {
          const s = JSON.parse(e);
          let i = "object" == typeof s && s.activeTargetIds instanceof Array, n = ie();
          for (let t = 0; i && t < s.activeTargetIds.length; ++t) i = O(s.activeTargetIds[t]), 
          n = n.add(s.activeTargetIds[t]);
          return i ? new In(t, n) : (pe("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 wn {
      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 Vl(t) {
          const e = JSON.parse(t);
          return "object" == typeof e && -1 !== [ "Unknown", "Online", "Offline" ].indexOf(e.onlineState) && "string" == typeof e.clientId ? new wn(e.clientId, e.onlineState) : (pe("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 Rn {
      constructor() {
          this.activeTargetIds = ie();
      }
      pl(t) {
          this.activeTargetIds = this.activeTargetIds.add(t);
      }
      yl(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.
       */    gl() {
          const t = {
              activeTargetIds: this.activeTargetIds.W(),
              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 mn {
      constructor(t, e, s, i, n) {
          if (this.Tr = t, this.platform = e, this.persistenceKey = s, this.bl = i, this.hl = null, 
          this.V_ = null, this.ur = null, this.vl = this.Sl.bind(this), this.Dl = new Ut(Ce), 
          this.io = !1, 
          /**
           * Captures WebStorage events that occur before `start()` is called. These
           * events are replayed once `WebStorageSharedClientState` is started.
           */
          this.Cl = [], !mn.jh(this.platform)) throw new R(w.UNIMPLEMENTED, "LocalStorage is not available on this platform.");
          // Escape the special characters mentioned here:
          // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
                  const r = s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
          this.storage = this.platform.window.localStorage, this.currentUser = n, this.Fl = ln(this.persistenceKey, this.bl), 
          this.Nl = 
          /** 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.Dl = this.Dl.me(this.bl, new Rn), this.$l = new RegExp(`^firestore_clients_${r}_([^_]*)$`), 
          this.kl = new RegExp(`^firestore_mutations_${r}_(\\d+)(?:_(.*))?$`), this.Ml = new RegExp(`^firestore_targets_${r}_(\\d+)$`), 
          this.Ll = 
          /** Assembles the key for the online state of the primary tab. */
          function(t) {
              return `firestore_online_state_${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.platform.window.addEventListener("storage", this.vl);
      }
      /** Returns 'true' if WebStorage is available in the current environment. */    static jh(t) {
          return !(!t.window || null == t.window.localStorage);
      }
      async start() {
          // Retrieve the list of existing clients to backfill the data in
          // SharedClientState.
          const t = await this.hl.po();
          for (const e of t) {
              if (e === this.bl) continue;
              const t = this.getItem(ln(this.persistenceKey, e));
              if (t) {
                  const s = In.Vl(e, t);
                  s && (this.Dl = this.Dl.me(s.clientId, s));
              }
          }
          this.Ol();
          // Check if there is an existing online state and call the callback handler
          // if applicable.
          const e = this.storage.getItem(this.Ll);
          if (e) {
              const t = this.xl(e);
              t && this.Bl(t);
          }
          for (const t of this.Cl) this.Sl(t);
          this.Cl = [], 
          // Register a window unload hook to remove the client metadata entry from
          // WebStorage even if `shutdown()` was not called.
          this.platform.window.addEventListener("unload", () => this.Ro()), this.io = !0;
      }
      lr(t) {
          this.setItem(this.Nl, JSON.stringify(t));
      }
      ql() {
          return this.Ul(this.Dl);
      }
      Ql(t) {
          let e = !1;
          return this.Dl.forEach((s, i) => {
              i.activeTargetIds.has(t) && (e = !0);
          }), e;
      }
      Wl(t) {
          this.jl(t, "pending");
      }
      Kl(t, e, s) {
          this.jl(t, e, s), 
          // 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.Gl(t);
      }
      zl(t) {
          let e = "not-current";
          // Lookup an existing query state if the target ID was already registered
          // by another tab
                  if (this.Ql(t)) {
              const s = this.storage.getItem(fn(this.persistenceKey, t));
              if (s) {
                  const i = En.Vl(t, s);
                  i && (e = i.state);
              }
          }
          return this.Hl.pl(t), this.Ol(), e;
      }
      Yl(t) {
          this.Hl.yl(t), this.Ol();
      }
      Jl(t) {
          return this.Hl.activeTargetIds.has(t);
      }
      Xl(t) {
          this.removeItem(fn(this.persistenceKey, t));
      }
      Zl(t, e, s) {
          this.td(t, e, s);
      }
      Su(t, e, s) {
          e.forEach(t => {
              this.Gl(t);
          }), this.currentUser = t, s.forEach(t => {
              this.Wl(t);
          });
      }
      ed(t) {
          this.sd(t);
      }
      Ro() {
          this.io && (this.platform.window.removeEventListener("storage", this.vl), this.removeItem(this.Fl), 
          this.io = !1);
      }
      getItem(t) {
          const e = this.storage.getItem(t);
          return ge("SharedClientState", "READ", t, e), e;
      }
      setItem(t, e) {
          ge("SharedClientState", "SET", t, e), this.storage.setItem(t, e);
      }
      removeItem(t) {
          ge("SharedClientState", "REMOVE", t), this.storage.removeItem(t);
      }
      Sl(t) {
          if (t.storageArea === this.storage) {
              if (ge("SharedClientState", "EVENT", t.key, t.newValue), t.key === this.Fl) return void pe("Received WebStorage notification for local change. Another client might have garbage-collected our state");
              this.Tr.Ua(async () => {
                  if (this.io) {
                      if (null !== t.key) if (this.$l.test(t.key)) {
                          if (null == t.newValue) {
                              const e = this.nd(t.key);
                              return this.rd(e, null);
                          }
                          {
                              const e = this.hd(t.key, t.newValue);
                              if (e) return this.rd(e.clientId, e);
                          }
                      } else if (this.kl.test(t.key)) {
                          if (null !== t.newValue) {
                              const e = this.od(t.key, t.newValue);
                              if (e) return this.ad(e);
                          }
                      } else if (this.Ml.test(t.key)) {
                          if (null !== t.newValue) {
                              const e = this.ud(t.key, t.newValue);
                              if (e) return this._d(e);
                          }
                      } else if (t.key === this.Ll) {
                          if (null !== t.newValue) {
                              const e = this.xl(t.newValue);
                              if (e) return this.Bl(e);
                          }
                      } else if (t.key === this.Nl) {
                          const e = function(t) {
                              let e = je.dr;
                              if (null != t) try {
                                  const s = JSON.parse(t);
                                  ve("number" == typeof s), e = s;
                              } catch (t) {
                                  pe("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.
   */ (t.newValue);
                          e !== je.dr && this.ur(e);
                      }
                  } else this.Cl.push(t);
              });
          }
      }
      get Hl() {
          return this.Dl.get(this.bl);
      }
      Ol() {
          this.setItem(this.Fl, this.Hl.gl());
      }
      jl(t, e, s) {
          const i = new Tn(this.currentUser, t, e, s), n = dn(this.persistenceKey, this.currentUser, t);
          this.setItem(n, i.gl());
      }
      Gl(t) {
          const e = dn(this.persistenceKey, this.currentUser, t);
          this.removeItem(e);
      }
      sd(t) {
          const e = {
              clientId: this.bl,
              onlineState: t
          };
          this.storage.setItem(this.Ll, JSON.stringify(e));
      }
      td(t, e, s) {
          const i = fn(this.persistenceKey, t), n = new En(t, e, s);
          this.setItem(i, n.gl());
      }
      /**
       * Parses a client state key in WebStorage. Returns null if the key does not
       * match the expected key format.
       */    nd(t) {
          const e = this.$l.exec(t);
          return e ? e[1] : null;
      }
      /**
       * Parses a client state in WebStorage. Returns 'null' if the value could not
       * be parsed.
       */    hd(t, e) {
          const s = this.nd(t);
          return In.Vl(s, e);
      }
      /**
       * Parses a mutation batch state in WebStorage. Returns 'null' if the value
       * could not be parsed.
       */    od(t, e) {
          const s = this.kl.exec(t), i = Number(s[1]), n = void 0 !== s[2] ? s[2] : null;
          return Tn.Vl(new I(n), i, e);
      }
      /**
       * Parses a query target state from WebStorage. Returns 'null' if the value
       * could not be parsed.
       */    ud(t, e) {
          const s = this.Ml.exec(t), i = Number(s[1]);
          return En.Vl(i, e);
      }
      /**
       * Parses an online state from WebStorage. Returns 'null' if the value
       * could not be parsed.
       */    xl(t) {
          return wn.Vl(t);
      }
      async ad(t) {
          if (t.user.uid === this.currentUser.uid) return this.hl.ld(t.batchId, t.state, t.error);
          ge("SharedClientState", `Ignoring mutation for non-active user ${t.user.uid}`);
      }
      _d(t) {
          return this.hl.dd(t.targetId, t.state, t.error);
      }
      rd(t, e) {
          const s = e ? this.Dl.me(t, e) : this.Dl.remove(t), i = this.Ul(this.Dl), n = this.Ul(s), r = [], h = [];
          return n.forEach(t => {
              i.has(t) || r.push(t);
          }), i.forEach(t => {
              n.has(t) || h.push(t);
          }), this.hl.fd(r, h).then(() => {
              this.Dl = s;
          });
      }
      Bl(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.Dl.get(t.clientId) && this.V_(t.onlineState);
      }
      Ul(t) {
          let e = ie();
          return t.forEach((t, s) => {
              e = e.He(s.activeTargetIds);
          }), e;
      }
  }
  
  class An {
      constructor() {
          this.Td = new Rn, this.Ed = {}, this.hl = null, this.V_ = null, this.ur = null;
      }
      Wl(t) {
          // No op.
      }
      Kl(t, e, s) {
          // No op.
      }
      zl(t) {
          return this.Td.pl(t), this.Ed[t] || "not-current";
      }
      Zl(t, e, s) {
          this.Ed[t] = e;
      }
      Yl(t) {
          this.Td.yl(t);
      }
      Jl(t) {
          return this.Td.activeTargetIds.has(t);
      }
      Xl(t) {
          delete this.Ed[t];
      }
      ql() {
          return this.Td.activeTargetIds;
      }
      Ql(t) {
          return this.Td.activeTargetIds.has(t);
      }
      start() {
          return this.Td = new Rn, Promise.resolve();
      }
      Su(t, e, s) {
          // No op.
      }
      ed(t) {
          // No op.
      }
      Ro() {}
      lr(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 Pn {
      constructor(t) {
          this.key = t;
      }
  }
  
  class Vn {
      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 gn {
      constructor(t, 
      /** Documents included in the remote target */
      e) {
          this.query = t, this.Id = e, this.wd = 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.fs = !1, 
          /** Documents in the view but not in the remote target */
          this.Rd = ee(), 
          /** Document Keys that have local changes */
          this.ns = ee(), this.md = new ne(t.se.bind(t));
      }
      /**
       * The set of remote documents that the server has told us belongs to the target associated with
       * this view.
       */    get Ad() {
          return this.Id;
      }
      /**
       * 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.
       * @return a new set of docs, changes, and refill flag.
       */    Pd(t, e) {
          const s = e ? e.Vd : new re, i = e ? e.md : this.md;
          let n = e ? e.ns : this.ns, r = i, h = !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 o = this.query.oe() && i.size === this.query.limit ? i.last() : null, a = this.query.ae() && i.size === this.query.limit ? i.first() : null;
          // Drop documents out to meet limit/limitToLast requirement.
          if (t.pe((t, e) => {
              const u = i.get(t);
              let c = e instanceof Vt ? e : null;
              c && (c = this.query.matches(c) ? c : null);
              const _ = !!u && this.ns.has(u.key), l = !!c && (c.At || 
              // We only consider committed mutations for documents that were
              // mutated during the lifetime of the view.
              this.ns.has(c.key) && c.hasCommittedMutations);
              let d = !1;
              // Calculate change
                          if (u && c) {
                  u.data().isEqual(c.data()) ? _ !== l && (s.track({
                      type: 3 /* Metadata */ ,
                      doc: c
                  }), d = !0) : this.gd(u, c) || (s.track({
                      type: 2 /* Modified */ ,
                      doc: c
                  }), d = !0, (o && this.query.se(c, o) > 0 || a && this.query.se(c, 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.
                  h = !0));
              } else !u && c ? (s.track({
                  type: 0 /* Added */ ,
                  doc: c
              }), d = !0) : u && !c && (s.track({
                  type: 1 /* Removed */ ,
                  doc: u
              }), d = !0, (o || 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.
              h = !0));
              d && (c ? (r = r.add(c), n = l ? n.add(t) : n.delete(t)) : (r = r.delete(t), n = n.delete(t)));
          }), this.query.oe() || this.query.ae()) for (;r.size > this.query.limit; ) {
              const t = this.query.oe() ? r.last() : r.first();
              r = r.delete(t.key), n = n.delete(t.key), s.track({
                  type: 1 /* Removed */ ,
                  doc: t
              });
          }
          return {
              md: r,
              Vd: s,
              pd: h,
              ns: n
          };
      }
      gd(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.At && e.hasCommittedMutations && !e.At;
      }
      /**
       * 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.
       * @return A new ViewChange with the given docs, changes, and sync state.
       */
      // PORTING NOTE: The iOS/Android clients always compute limbo document changes.
      xn(t, e, s) {
          const i = this.md;
          this.md = t.md, this.ns = t.ns;
          // Sort changes based on type and query comparator
          const n = t.Vd.es();
          n.sort((t, e) => function(t, e) {
              const s = 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 be();
                  }
              };
              return s(t) - s(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.
   */ (t.type, e.type) || this.query.se(t.doc, e.doc)), this.yd(s);
          const r = e ? this.bd() : [], h = 0 === this.Rd.size && this.fs ? 1 /* Synced */ : 0 /* Local */ , o = h !== this.wd;
          if (this.wd = h, 0 !== n.length || o) {
              return {
                  snapshot: new he(this.query, t.md, i, n, t.ns, 0 /* Local */ === h, o, 
                  /* excludesMetadataChanges= */ !1),
                  vd: r
              };
          }
          // no changes
          return {
              vd: r
          };
      }
      /**
       * Applies an OnlineState change to the view, potentially generating a
       * ViewChange if the view's syncState changes as a result.
       */    Sd(t) {
          return this.fs && "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.fs = !1, this.xn({
              md: this.md,
              Vd: new re,
              ns: this.ns,
              pd: !1
          }, 
          /* updateLimboDocuments= */ !1)) : {
              vd: []
          };
      }
      /**
       * Returns whether the doc for the given key should be in limbo.
       */    Dd(t) {
          // If the remote end says it's part of this query, it's not in limbo.
          return !this.Id.has(t) && (
          // The local store doesn't think it's a result, so it shouldn't be in limbo.
          !!this.md.has(t) && !this.md.get(t).At);
      }
      /**
       * Updates syncedDocuments, current, and limbo docs based on the given change.
       * Returns the list of changes to which docs are in limbo.
       */    yd(t) {
          t && (t.Ts.forEach(t => this.Id = this.Id.add(t)), t.Es.forEach(t => {}), t.Is.forEach(t => this.Id = this.Id.delete(t)), 
          this.fs = t.fs);
      }
      bd() {
          // We can only determine limbo documents when we're in-sync with the server.
          if (!this.fs) return [];
          // TODO(klimt): Do this incrementally so that it's not quadratic when
          // updating many documents.
                  const t = this.Rd;
          this.Rd = ee(), this.md.forEach(t => {
              this.Dd(t.key) && (this.Rd = this.Rd.add(t.key));
          });
          // Diff the new limbo docs with the old limbo docs.
          const e = [];
          return t.forEach(t => {
              this.Rd.has(t) || e.push(new Vn(t));
          }), this.Rd.forEach(s => {
              t.has(s) || e.push(new Pn(s));
          }), 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.
       *
       * @return The ViewChange that resulted from this synchronization.
       */
      // PORTING NOTE: Multi-tab only.
      Cd(t) {
          this.Id = t.ju, this.Rd = ee();
          const e = this.Pd(t.documents);
          return this.xn(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.
      Fd() {
          return he.os(this.query, this.md, this.ns, 0 /* Local */ === this.wd);
      }
  }
  
  /**
   * TransactionRunner encapsulates the logic needed to run and retry transactions
   * with backoff.
   */
  class pn {
      constructor(t, e, s, i) {
          this.wa = t, this.Nd = e, this.updateFunction = s, this.Aa = i, this.$d = 5, this.Na = new Ge(this.wa, "transaction_retry" /* TransactionRetry */);
      }
      /** Runs the transaction and sets the result on deferred. */    kd() {
          this.Md();
      }
      Md() {
          this.Na.gr(async () => {
              const t = this.Nd.ml(), e = this.Ld(t);
              e && e.then(e => {
                  this.wa.oo(() => t.commit().then(() => {
                      this.Aa.resolve(e);
                  }).catch(t => {
                      this.Od(t);
                  }));
              }).catch(t => {
                  this.Od(t);
              });
          });
      }
      Ld(t) {
          try {
              const e = this.updateFunction(t);
              return !M(e) && e.catch && e.then ? e : (this.Aa.reject(Error("Transaction callback must return a Promise")), 
              null);
          } catch (t) {
              // Do not retry errors thrown by user provided updateFunction.
              return this.Aa.reject(t), null;
          }
      }
      Od(t) {
          this.$d > 0 && this.xd(t) ? (this.$d -= 1, this.wa.oo(() => (this.Md(), Promise.resolve()))) : this.Aa.reject(t);
      }
      xd(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 || !Bt(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.
   */
  /**
   * QueryView contains all of the data that SyncEngine needs to keep track of for
   * a particular query.
   */
  class yn {
      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.
       */
      s) {
          this.query = t, this.targetId = e, this.view = s;
      }
  }
  
  /** Tracks a limbo resolution. */ class bn {
      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.Bd = !1;
      }
  }
  
  /**
   * SyncEngine is the central controller in the client SDK architecture. It is
   * the glue code between the EventManager, LocalStore, and RemoteStore. Some of
   * SyncEngine's responsibilities include:
   * 1. Coordinating client requests and remote events between the EventManager
   *    and the local and remote data stores.
   * 2. Managing a View object for each query, providing the unified view between
   *    the local and remote data stores.
   * 3. Notifying the RemoteStore when the LocalStore has new mutations in its
   *    queue that need sending to the backend.
   *
   * The SyncEngine’s methods should only ever be called by methods running in the
   * global async queue.
   */ class vn {
      constructor(t, e, 
      // PORTING NOTE: Manages state synchronization in multi-tab environments.
      s, i, n) {
          this.F_ = t, this.Nd = e, this.qd = s, this.currentUser = i, this.Ud = n, this.Qd = null, 
          this.Wd = new Me(t => t.canonicalId()), this.jd = new Map, 
          /**
           * The keys of documents that are in limbo for which we haven't yet started a
           * limbo resolution query.
           */
          this.Kd = [], 
          /**
           * Keeps track of the target ID for each document that is in limbo with an
           * active target.
           */
          this.Gd = new Ut(C.N), 
          /**
           * 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.zd = new Map, this.Hd = new li, 
          /** Stores user completion handlers, indexed by User and BatchId. */
          this.Yd = {}, 
          /** Stores user callbacks waiting for all pending writes to be acknowledged. */
          this.Jd = new Map, this.Xd = os.ih(), this.onlineState = "Unknown" /* Unknown */;
      }
      get Zd() {
          return !0;
      }
      /** Subscribes to SyncEngine notifications. Has to be called exactly once. */    subscribe(t) {
          this.Qd = t;
      }
      /**
       * 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 listen(t) {
          let e, s;
          this.tf("listen()");
          const i = this.Wd.get(t);
          if (i) 
          // 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.
          e = i.targetId, this.qd.zl(e), s = i.view.Fd(); else {
              const i = await this.F_.Uu(t.ee()), n = this.qd.zl(i.targetId);
              e = i.targetId, s = await this.ef(t, e, "current" === n), this.Zd && this.Nd.listen(i);
          }
          return s;
      }
      /**
       * Registers a view for a previously unknown query and computes its initial
       * snapshot.
       */    async ef(t, e, s) {
          const i = await this.F_.Wu(t, 
          /* usePreviousResults= */ !0), n = new gn(t, i.ju), r = n.Pd(i.documents), h = ae.ds(e, s && "Offline" /* Offline */ !== this.onlineState), o = n.xn(r, 
          /* updateLimboDocuments= */ this.Zd, h);
          this.sf(e, o.vd);
          const a = new yn(t, e, n);
          return this.Wd.set(t, a), this.jd.has(e) ? this.jd.get(e).push(t) : this.jd.set(e, [ t ]), 
          o.snapshot;
      }
      /** Stops listening to the query. */    async nl(t) {
          this.tf("unlisten()");
          const e = this.Wd.get(t), s = this.jd.get(e.targetId);
          // Only clean up the query view and target if this is the only query mapped
          // to the target.
                  if (s.length > 1) return this.jd.set(e.targetId, s.filter(e => !e.isEqual(t))), 
          void this.Wd.delete(t);
          // No other queries are mapped to the target, clean up the query and the target.
                  if (this.Zd) {
              // We need to remove the local query target first to allow us to verify
              // whether any other client is still interested in this target.
              this.qd.Yl(e.targetId), this.qd.Ql(e.targetId) || await this.F_.Qu(e.targetId, /*keepPersistedTargetData=*/ !1).then(() => {
                  this.qd.Xl(e.targetId), this.Nd.nl(e.targetId), this.if(e.targetId);
              }).catch(_i);
          } else this.if(e.targetId), await this.F_.Qu(e.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 write(t, e) {
          this.tf("write()");
          try {
              const s = await this.F_.Nu(t);
              this.qd.Wl(s.batchId), this.nf(s.batchId, e), await this.rf(s.Dn), await this.Nd.tl();
          } 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 s = si(t, "Failed to persist write");
              e.reject(s);
          }
      }
      /**
       * 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.
       *
       * The Deferred input is resolved when the transaction is fully committed.
       */    runTransaction(t, e, s) {
          new pn(t, this.Nd, e, s).kd();
      }
      async Mu(t) {
          this.tf("applyRemoteEvent()");
          try {
              const e = await this.F_.Mu(t);
              // Update `receivedDocument` as appropriate for any limbo targets.
                          t.as.forEach((t, e) => {
                  const s = this.zd.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.
                  ve(t.Ts.size + t.Es.size + t.Is.size <= 1), t.Ts.size > 0 ? s.Bd = !0 : t.Es.size > 0 ? ve(s.Bd) : t.Is.size > 0 && (ve(s.Bd), 
                  s.Bd = !1));
              }), await this.rf(e, t);
          } catch (t) {
              await _i(t);
          }
      }
      /**
       * Applies an OnlineState change to the sync engine and notifies any views of
       * the change.
       */    Sd(t, e) {
          this.tf("applyOnlineStateChange()");
          const s = [];
          this.Wd.forEach((e, i) => {
              const n = i.view.Sd(t);
              n.snapshot && s.push(n.snapshot);
          }), this.Qd.hf(t), this.Qd.s_(s), this.onlineState = t;
      }
      async cl(t, e) {
          this.tf("rejectListens()"), 
          // PORTING NOTE: Multi-tab only.
          this.qd.Zl(t, "rejected", e);
          const s = this.zd.get(t), i = s && s.key;
          if (i) {
              // 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 e = new Ut(C.N);
              e = e.me(i, new gt(i, y.min()));
              const s = ee().add(i), n = new oe(y.min(), 
              /* targetChanges= */ new Map, 
              /* targetMismatches= */ new jt(Ce), e, s);
              await this.Mu(n), 
              // 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.
              this.Gd = this.Gd.remove(i), this.zd.delete(t), this.af();
          } else await this.F_.Qu(t, /* keepPersistedTargetData */ !1).then(() => this.if(t, e)).catch(_i);
      }
      async El(t) {
          this.tf("applySuccessfulWrite()");
          const e = t.batch.batchId;
          // 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.
                  this.uf(e, /*error=*/ null), this.cf(e);
          try {
              const s = await this.F_.Ko(t);
              this.qd.Kl(e, "acknowledged"), await this.rf(s);
          } catch (t) {
              await _i(t);
          }
      }
      async Rl(t, e) {
          this.tf("rejectFailedWrite()"), 
          // 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.
          this.uf(t, e), this.cf(t);
          try {
              const s = await this.F_.ku(t);
              this.qd.Kl(t, "rejected", e), await this.rf(s);
          } catch (e) {
              await _i(e);
          }
      }
      /**
       * Registers a user callback that resolves when all pending mutations at the moment of calling
       * are acknowledged .
       */    async _f(t) {
          this.Nd.B_() || ge("SyncEngine", "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");
          try {
              const e = await this.F_.ta();
              if (-1 === e) 
              // Trigger the callback right away if there is no pending writes at the moment.
              return void t.resolve();
              const s = this.Jd.get(e) || [];
              s.push(t), this.Jd.set(e, s);
          } catch (e) {
              const s = si(e, "Initialization of waitForPendingWrites() operation failed");
              t.reject(s);
          }
      }
      /**
       * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,
       * if there are any.
       */    cf(t) {
          (this.Jd.get(t) || []).forEach(t => {
              t.resolve();
          }), this.Jd.delete(t);
      }
      /** Reject all outstanding callbacks waiting for pending writes to complete. */    lf(t) {
          this.Jd.forEach(e => {
              e.forEach(e => {
                  e.reject(new R(w.CANCELLED, t));
              });
          }), this.Jd.clear();
      }
      nf(t, e) {
          let s = this.Yd[this.currentUser.s()];
          s || (s = new Ut(Ce)), s = s.me(t, e), this.Yd[this.currentUser.s()] = s;
      }
      /**
       * Resolves or rejects the user callback for the given batch and then discards
       * it.
       */    uf(t, e) {
          let s = this.Yd[this.currentUser.s()];
          // NOTE: Mutations restored from persistence won't have callbacks, so it's
          // okay for there to be no callback for this ID.
                  if (s) {
              const i = s.get(t);
              i && (e ? i.reject(e) : i.resolve(), s = s.remove(t)), this.Yd[this.currentUser.s()] = s;
          }
      }
      if(t, e = null) {
          this.qd.Yl(t);
          for (const s of this.jd.get(t)) this.Wd.delete(s), e && this.Qd.df(s, e);
          if (this.jd.delete(t), this.Zd) {
              this.Hd.ic(t).forEach(t => {
                  this.Hd.Dh(t) || 
                  // We removed the last reference for this key
                  this.ff(t);
              });
          }
      }
      ff(t) {
          // 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 e = this.Gd.get(t);
          null !== e && (this.Nd.nl(e), this.Gd = this.Gd.remove(t), this.zd.delete(e), this.af());
      }
      sf(t, e) {
          for (const s of e) if (s instanceof Pn) this.Hd.ph(s.key, t), this.Tf(s); else if (s instanceof Vn) {
              ge("SyncEngine", "Document no longer in limbo: " + s.key), this.Hd.bh(s.key, t), 
              this.Hd.Dh(s.key) || 
              // We removed the last reference for this key
              this.ff(s.key);
          } else be();
      }
      Tf(t) {
          const e = t.key;
          this.Gd.get(e) || (ge("SyncEngine", "New document in limbo: " + e), this.Kd.push(e), 
          this.af());
      }
      /**
       * 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.
       */    af() {
          for (;this.Kd.length > 0 && this.Gd.size < this.Ud; ) {
              const t = this.Kd.shift(), e = this.Xd.next();
              this.zd.set(e, new bn(t)), this.Gd = this.Gd.me(t, e), this.Nd.listen(new Mt(bt.Wt(t.path).ee(), e, 2 /* LimboResolution */ , je.dr));
          }
      }
      // Visible for testing
      Ef() {
          return this.Gd;
      }
      // Visible for testing
      If() {
          return this.Kd;
      }
      async rf(t, e) {
          const s = [], i = [], n = [];
          this.Wd.forEach((r, h) => {
              n.push(Promise.resolve().then(() => {
                  const e = h.view.Pd(t);
                  return e.pd ? this.F_.Wu(h.query, /* usePreviousResults= */ !1).then(({documents: t}) => h.view.Pd(t, e)) : e;
                  // 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.
                          }).then(t => {
                  const n = e && e.as.get(h.targetId), r = h.view.xn(t, 
                  /* updateLimboDocuments= */ this.Zd, n);
                  if (this.sf(h.targetId, r.vd), r.snapshot) {
                      this.Zd && this.qd.Zl(h.targetId, r.snapshot.fromCache ? "not-current" : "current"), 
                      s.push(r.snapshot);
                      const t = We.ar(h.targetId, r.snapshot);
                      i.push(t);
                  }
              }));
          }), await Promise.all(n), this.Qd.s_(s), await this.F_.xu(i);
      }
      tf(t) {}
      async Al(t) {
          const e = !this.currentUser.isEqual(t);
          if (this.currentUser = t, e) {
              // Fails tasks waiting for pending writes requested by previous user.
              this.lf("'waitForPendingWrites' promise is rejected due to a user change.");
              const e = await this.F_.Su(t);
              // TODO(b/114226417): Consider calling this only in the primary tab.
                          this.qd.Su(t, e.Cu, e.Fu), await this.rf(e.Du);
          }
          await this.Nd.Al();
      }
      enableNetwork() {
          return this.Nd.enableNetwork();
      }
      disableNetwork() {
          return this.Nd.disableNetwork();
      }
      ei(t) {
          const e = this.zd.get(t);
          if (e && e.Bd) return ee().add(e.key);
          {
              let e = ee();
              const s = this.jd.get(t);
              if (!s) return e;
              for (const t of s) {
                  const s = this.Wd.get(t);
                  e = e.He(s.view.Ad);
              }
              return e;
          }
      }
  }
  
  /**
   * An impplementation of SyncEngine that implement SharedClientStateSyncer for
   * Multi-Tab synchronization.
   */
  // PORTING NOTE: Web only
  class Sn extends vn {
      constructor(t, e, s, i, n) {
          super(t, e, s, i, n), this.F_ = t, 
          // 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.wf = void 0;
      }
      get Zd() {
          return !0 === this.wf;
      }
      enableNetwork() {
          return this.F_.ho(!0), super.enableNetwork();
      }
      disableNetwork() {
          return this.F_.ho(!1), super.disableNetwork();
      }
      /**
       * Reconcile the list of synced documents in an existing view with those
       * from persistence.
       */    async Rf(t) {
          const e = await this.F_.Wu(t.query, 
          /* usePreviousResults= */ !0), s = t.view.Cd(e);
          return this.wf && this.sf(t.targetId, s.vd), s;
      }
      Sd(t, e) {
          // If we are the primary client, the online state of all clients only
          // depends on the online state of the local RemoteStore.
          this.Zd && 0 /* RemoteStore */ === e && (super.Sd(t, e), this.qd.ed(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.
          this.Zd || 1 /* SharedClientState */ !== e || super.Sd(t, e);
      }
      async ld(t, e, s) {
          this.tf("applyBatchState()");
          const i = await this.F_.Gu(t);
          null !== i ? ("pending" === e ? 
          // 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 this.Nd.tl() : "acknowledged" === e || "rejected" === e ? (
          // NOTE: Both these methods are no-ops for batches that originated from
          // other clients.
          this.uf(t, s || null), this.F_.zu(t)) : be(), await this.rf(i)) : 
          // 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.
          ge("SyncEngine", "Cannot apply mutation batch with id: " + t);
      }
      async Pl(t) {
          if (!0 === t && !0 !== this.wf) {
              // 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 = this.qd.ql(), e = await this.mf(t.W(), 
              /*transitionToPrimary=*/ !0);
              this.wf = !0, await this.Nd.Pl(!0);
              for (const t of e) this.Nd.listen(t);
          } else if (!1 === t && !1 !== this.wf) {
              const t = [];
              let e = Promise.resolve();
              this.jd.forEach((s, i) => {
                  this.qd.Jl(i) ? t.push(i) : e = e.then(() => (this.if(i), this.F_.Qu(i, 
                  /*keepPersistedTargetData=*/ !0))), this.Nd.nl(i);
              }), await e, await this.mf(t, 
              /*transitionToPrimary=*/ !1), this.Af(), this.wf = !1, await this.Nd.Pl(!1);
          }
      }
      Af() {
          this.zd.forEach((t, e) => {
              this.Nd.nl(e);
          }), this.Hd.nc(), this.zd = new Map, this.Gd = new Ut(C.N);
      }
      /**
       * 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 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
       */    async mf(t, e) {
          const s = [], i = [];
          for (const e of t) {
              let t;
              const n = this.jd.get(e);
              if (n && 0 !== n.length) {
                  // For queries that have a local View, we need to update their state
                  // in 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).
                  await this.F_.Qu(e, 
                  /*keepPersistedTargetData=*/ !0), t = await this.F_.Uu(n[0].ee());
                  for (const t of n) {
                      const e = this.Wd.get(t), s = await this.Rf(e);
                      s.snapshot && i.push(s.snapshot);
                  }
              } else {
                  // For queries that never executed on this client, we need to
                  // allocate the target in LocalStore and initialize a new View.
                  const s = await this.F_.Hu(e);
                  t = await this.F_.Uu(s), await this.ef(this.Pf(s), e, 
                  /*current=*/ !1);
              }
              s.push(t);
          }
          return this.Qd.s_(i), s;
      }
      /**
       * 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.
       */    Pf(t) {
          return new bt(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, "F" /* First */ , t.startAt, t.endAt);
      }
      po() {
          return this.F_.po();
      }
      async dd(t, e, s) {
          if (this.wf) 
          // If we receive a target state notification via WebStorage, we are
          // either already secondary or another tab has taken the primary lease.
          ge("SyncEngine", "Ignoring unexpected query state notification."); else if (this.jd.has(t)) switch (e) {
            case "current":
            case "not-current":
              {
                  const s = await this.F_.Wr(), i = oe.ls(t, "current" === e);
                  await this.rf(s, i);
                  break;
              }
  
            case "rejected":
              await this.F_.Qu(t, 
              /* keepPersistedTargetData */ !0), this.if(t, s);
              break;
  
            default:
              be();
          }
      }
      async fd(t, e) {
          if (this.wf) {
              for (const e of t) {
                  if (this.jd.has(e)) {
                      // A target might have been added in a previous attempt
                      ge("SyncEngine", "Adding an already active target " + e);
                      continue;
                  }
                  const t = await this.F_.Hu(e), s = await this.F_.Uu(t);
                  await this.ef(this.Pf(t), s.targetId, 
                  /*current=*/ !1), this.Nd.listen(s);
              }
              for (const t of e) 
              // Check that the target is still active since the target might have been
              // removed if it has been rejected by the backend.
              this.jd.has(t) && 
              // Release queries that are still active.
              await this.F_.Qu(t, /* keepPersistedTargetData */ !1).then(() => {
                  this.Nd.nl(t), this.if(t);
              }).catch(_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.
   */
  /**
   * Holds the listeners and the last received ViewSnapshot for a query being
   * tracked by EventManager.
   */ class Dn {
      constructor() {
          this.Vf = void 0, this.gf = [];
      }
  }
  
  /**
   * EventManager is responsible for mapping queries to query event emitters.
   * It handles "fan-out". -- Identical queries will re-use the same watch on the
   * backend.
   */ class Cn {
      constructor(t) {
          this.hl = t, this.pf = new Me(t => t.canonicalId()), this.onlineState = "Unknown" /* Unknown */ , 
          this.yf = new Set, this.hl.subscribe(this);
      }
      async listen(t) {
          const e = t.query;
          let s = !1, i = this.pf.get(e);
          if (i || (s = !0, i = new Dn), s) try {
              i.Vf = await this.hl.listen(e);
          } catch (e) {
              const s = si(e, `Initialization of query '${t.query}' failed`);
              return void t.onError(s);
          }
          this.pf.set(e, i), i.gf.push(t);
          // Run global snapshot listeners if a consistent snapshot has been emitted.
          t.Sd(this.onlineState);
          if (i.Vf) {
              t.bf(i.Vf) && this.vf();
          }
      }
      async nl(t) {
          const e = t.query;
          let s = !1;
          const i = this.pf.get(e);
          if (i) {
              const e = i.gf.indexOf(t);
              e >= 0 && (i.gf.splice(e, 1), s = 0 === i.gf.length);
          }
          if (s) return this.pf.delete(e), this.hl.nl(e);
      }
      s_(t) {
          let e = !1;
          for (const s of t) {
              const t = s.query, i = this.pf.get(t);
              if (i) {
                  for (const t of i.gf) t.bf(s) && (e = !0);
                  i.Vf = s;
              }
          }
          e && this.vf();
      }
      df(t, e) {
          const s = this.pf.get(t);
          if (s) for (const t of s.gf) t.onError(e);
          // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()
          // after an error.
                  this.pf.delete(t);
      }
      hf(t) {
          this.onlineState = t;
          let e = !1;
          this.pf.forEach((s, i) => {
              for (const s of i.gf) 
              // Run global snapshot listeners if a consistent snapshot has been emitted.
              s.Sd(t) && (e = !0);
          }), e && this.vf();
      }
      Sf(t) {
          this.yf.add(t), 
          // Immediately fire an initial event, indicating all existing listeners
          // are in-sync.
          t.next();
      }
      Df(t) {
          this.yf.delete(t);
      }
      // Call all global snapshot listeners that have been set.
      vf() {
          this.yf.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 Fn {
      constructor(t, e, s) {
          this.query = t, this.Cf = 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.Ff = !1, this.Nf = null, this.onlineState = "Unknown" /* Unknown */ , this.options = s || {};
      }
      /**
       * 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.
       */    bf(t) {
          if (!this.options.includeMetadataChanges) {
              // Remove the metadata only changes.
              const e = [];
              for (const s of t.docChanges) 3 /* Metadata */ !== s.type && e.push(s);
              t = new he(t.query, t.docs, t.ss, e, t.ns, t.fromCache, t.rs, 
              /* excludesMetadataChanges= */ !0);
          }
          let e = !1;
          return this.Ff ? this.$f(t) && (this.Cf.next(t), e = !0) : this.kf(t, this.onlineState) && (this.Mf(t), 
          e = !0), this.Nf = t, e;
      }
      onError(t) {
          this.Cf.error(t);
      }
      /** Returns whether a snapshot was raised. */    Sd(t) {
          this.onlineState = t;
          let e = !1;
          return this.Nf && !this.Ff && this.kf(this.Nf, t) && (this.Mf(this.Nf), e = !0), 
          e;
      }
      kf(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 s = "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.Lf || !s) && (!t.docs.B() || "Offline" /* Offline */ === e);
          // Raise data from cache if we have any documents or we are offline
          }
      $f(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.Nf && this.Nf.hasPendingWrites !== t.hasPendingWrites;
          return !(!t.rs && !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.
          }
      Mf(t) {
          t = he.os(t.query, t.docs, t.ns, t.fromCache), this.Ff = !0, this.Cf.next(t);
      }
  }
  
  /**
   * @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.
   */
  // TOOD(b/140938512): Drop SimpleQueryEngine and rename IndexFreeQueryEngine.
  /**
   * A query engine that takes advantage of the target document mapping in the
   * QueryCache. The IndexFreeQueryEngine optimizes query execution 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 where Index-Free queries are not guaranteed to produce
   * the same results as full collection scans. In these cases, the
   * IndexFreeQueryEngine falls back to full query processing. 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 Nn {
      vu(t) {
          this.Of = t;
      }
      Zn(t, e, i, n) {
          // Queries that match all documents don't benefit from using
          // IndexFreeQueries. It is more efficient to scan all documents in a
          // collection, rather than to perform individual lookups.
          return e.te() || i.isEqual(y.min()) ? this.xf(t, e) : this.Of.Yn(t, n).next(r => {
              const h = this.Bf(e, r);
              return (e.oe() || e.ae()) && this.pd(e.Bt, h, n, i) ? this.xf(t, e) : (Pe() <= s.DEBUG && ge("IndexFreeQueryEngine", "Re-using previous result from %s to execute query: %s", i.toString(), e.toString()), 
              this.Of.Zn(t, e, i).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.
              h.forEach(e => {
                  t = t.me(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.  */    Bf(t, e) {
          // Sort the documents and re-apply the query filter since previously
          // matching documents do not necessarily still match the query.
          let s = new jt((e, s) => t.se(e, s));
          return e.forEach((e, i) => {
              i instanceof Vt && t.matches(i) && (s = s.add(i));
          }), s;
      }
      /**
       * 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.
       */    pd(t, e, s, i) {
          // The query needs to be refilled if a previously matching document no
          // longer matches.
          if (s.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 n = "F" /* First */ === t ? e.last() : e.first();
          return !!n && (n.hasPendingWrites || n.version.S(i) > 0);
      }
      xf(t, e) {
          return Pe() <= s.DEBUG && ge("IndexFreeQueryEngine", "Using full collection scan to execute query: %s", e.toString()), 
          this.Of.Zn(t, e, y.min());
      }
  }
  
  /**
   * @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 $n {
      constructor(t, e) {
          this.jn = t, this.nh = e, 
          /**
           * The set of all mutations that have been sent but not yet been applied to
           * the backend.
           */
          this.Wn = [], 
          /** Next value to use when assigning sequential IDs to each mutation batch. */
          this.qf = 1, 
          /** The last received stream token from the server, used to acknowledge which
           * responses the client has processed. Stream tokens are opaque checkpoint
           * markers whose only real value is their inclusion in the next request.
           */
          this.lastStreamToken = k.ht, 
          /** An ordered mapping between documents and the mutations batch IDs. */
          this.Uf = new jt(di.Ju);
      }
      jo(t) {
          return xe.resolve(0 === this.Wn.length);
      }
      Ko(t, e, s) {
          const i = e.batchId, n = this.Qf(i, "acknowledged");
          ve(0 === n);
          // Verify that the batch in the queue is the one to be acknowledged.
          this.Wn[n];
          return this.lastStreamToken = s, xe.resolve();
      }
      zo(t) {
          return xe.resolve(this.lastStreamToken);
      }
      Ho(t, e) {
          return this.lastStreamToken = e, xe.resolve();
      }
      Yo(t, e, s, i) {
          const n = this.qf;
          if (this.qf++, this.Wn.length > 0) {
              this.Wn[this.Wn.length - 1];
          }
          const r = new Le(n, e, s, i);
          this.Wn.push(r);
          // Track references by document key and index collection parents.
          for (const e of i) this.Uf = this.Uf.add(new di(e.key, n)), this.jn.vr(t, e.key.path.M());
          return xe.resolve(r);
      }
      Jo(t, e) {
          return xe.resolve(this.Wf(e));
      }
      Zo(t, e) {
          const s = e + 1, i = this.jf(s), n = i < 0 ? 0 : i;
          // The requested batchId may still be out of range so normalize it to the
          // start of the queue.
                  return xe.resolve(this.Wn.length > n ? this.Wn[n] : null);
      }
      ta() {
          return xe.resolve(0 === this.Wn.length ? -1 : this.qf - 1);
      }
      ea(t) {
          return xe.resolve(this.Wn.slice());
      }
      Gn(t, e) {
          const s = new di(e, 0), i = new di(e, Number.POSITIVE_INFINITY), n = [];
          return this.Uf.Ke([ s, i ], t => {
              const e = this.Wf(t.hc);
              n.push(e);
          }), xe.resolve(n);
      }
      Xn(t, e) {
          let s = new jt(Ce);
          return e.forEach(t => {
              const e = new di(t, 0), i = new di(t, Number.POSITIVE_INFINITY);
              this.Uf.Ke([ e, i ], t => {
                  s = s.add(t.hc);
              });
          }), xe.resolve(this.Kf(s));
      }
      nr(t, e) {
          // Use the query path as a prefix for testing if a document matches the
          // query.
          const s = e.path, i = s.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 n = s;
          C.et(n) || (n = n.child(""));
          const r = new di(new C(n), 0);
          // Find unique batchIDs referenced by all documents potentially matching the
          // query.
                  let h = new jt(Ce);
          return this.Uf.Ge(t => {
              const e = t.key.path;
              return !!s.q(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 === i && (h = h.add(t.hc)), !0);
          }, r), xe.resolve(this.Kf(h));
      }
      Kf(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 s = this.Wf(t);
              null !== s && e.push(s);
          }), e;
      }
      ia(t, e) {
          ve(0 === this.Qf(e.batchId, "removed")), this.Wn.shift();
          let s = this.Uf;
          return xe.forEach(e.mutations, i => {
              const n = new di(i.key, e.batchId);
              return s = s.delete(n), this.nh.Oo(t, i.key);
          }).next(() => {
              this.Uf = s;
          });
      }
      na(t) {
          // No-op since the memory mutation queue does not maintain a separate cache.
      }
      Dh(t, e) {
          const s = new di(e, 0), i = this.Uf.ze(s);
          return xe.resolve(e.isEqual(i && i.key));
      }
      ra(t) {
          return this.Wn.length, xe.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).
       */    Qf(t, e) {
          return this.jf(t);
      }
      /**
       * Finds the index of the given batchId in the mutation queue. This operation
       * is O(1).
       *
       * @return 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.
       */    jf(t) {
          if (0 === this.Wn.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.Wn[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.
       */    Wf(t) {
          const e = this.jf(t);
          return e < 0 || e >= this.Wn.length ? null : this.Wn[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 kn {
      /**
       * @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.jn = t, this.Gf = e, 
          /** Underlying cache of documents and their read times. */
          this.docs = new Ut(C.N), 
          /** 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()`.
       */    Nn(t, e, s) {
          const i = e.key, n = this.docs.get(i), r = n ? n.size : 0, h = this.Gf(e);
          return this.docs = this.docs.me(i, {
              kr: e,
              size: h,
              readTime: s
          }), this.size += h - r, this.jn.vr(t, i.path.M());
      }
      /**
       * 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()`.
       */    kn(t) {
          const e = this.docs.get(t);
          e && (this.docs = this.docs.remove(t), this.size -= e.size);
      }
      Mn(t, e) {
          const s = this.docs.get(e);
          return xe.resolve(s ? s.kr : null);
      }
      getEntries(t, e) {
          let s = Ht();
          return e.forEach(t => {
              const e = this.docs.get(t);
              s = s.me(t, e ? e.kr : null);
          }), xe.resolve(s);
      }
      Zn(t, e, s) {
          let i = Jt();
          // 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 n = new C(e.path.child("")), r = this.docs.ve(n);
          for (;r.$e(); ) {
              const {key: t, value: {kr: n, readTime: h}} = r.Ne();
              if (!e.path.q(t.path)) break;
              h.S(s) <= 0 || n instanceof Vt && e.matches(n) && (i = i.me(n.key, n));
          }
          return xe.resolve(i);
      }
      zf(t, e) {
          return xe.forEach(this.docs, t => e(t));
      }
      zr(t) {
          // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps
          // a separate changelog and does not need special handling for removals.
          return new kn.Hr(this);
      }
      Jr(t) {
          return xe.resolve(this.size);
      }
  }
  
  /**
   * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.
   */ kn.Hr = class extends Be {
      constructor(t) {
          super(), this.Xr = t;
      }
      xn(t) {
          const e = [];
          return this.Dn.forEach((s, i) => {
              i ? e.push(this.Xr.Nn(t, i, this.readTime)) : this.Xr.kn(s);
          }), xe.vn(e);
      }
      Ln(t, e) {
          return this.Xr.Mn(t, e);
      }
      On(t, e) {
          return this.Xr.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 Mn {
      constructor(t) {
          this.persistence = t, 
          /**
           * Maps a target to the data about that target
           */
          this.Hf = new Me(t => t.canonicalId()), 
          /** The last received snapshot version. */
          this.lastRemoteSnapshotVersion = y.min(), 
          /** The highest numbered target ID encountered. */
          this.highestTargetId = 0, 
          /** The highest sequence number encountered. */
          this.Yf = 0, 
          /**
           * A ordered bidirectional mapping between documents and the remote target
           * IDs.
           */
          this.Jf = new li, this.targetCount = 0, this.Xf = os.sh();
      }
      js(t, e) {
          return this.Hf.forEach((t, s) => e(s)), xe.resolve();
      }
      ah(t) {
          return xe.resolve(this.lastRemoteSnapshotVersion);
      }
      uh(t) {
          return xe.resolve(this.Yf);
      }
      rh(t) {
          return this.highestTargetId = this.Xf.next(), xe.resolve(this.highestTargetId);
      }
      lh(t, e, s) {
          return s && (this.lastRemoteSnapshotVersion = s), e > this.Yf && (this.Yf = e), 
          xe.resolve();
      }
      fh(t) {
          this.Hf.set(t.target, t);
          const e = t.targetId;
          e > this.highestTargetId && (this.Xf = new os(e), this.highestTargetId = e), t.sequenceNumber > this.Yf && (this.Yf = t.sequenceNumber);
      }
      dh(t, e) {
          return this.fh(e), this.targetCount += 1, xe.resolve();
      }
      Eh(t, e) {
          return this.fh(e), xe.resolve();
      }
      Ih(t, e) {
          return this.Hf.delete(e.target), this.Jf.ic(e.targetId), this.targetCount -= 1, 
          xe.resolve();
      }
      Rh(t, e, s) {
          let i = 0;
          const n = [];
          return this.Hf.forEach((r, h) => {
              h.sequenceNumber <= e && null === s.get(h.targetId) && (this.Hf.delete(r), n.push(this.wh(t, h.targetId)), 
              i++);
          }), xe.vn(n).next(() => i);
      }
      Ph(t) {
          return xe.resolve(this.targetCount);
      }
      Vh(t, e) {
          const s = this.Hf.get(e) || null;
          return xe.resolve(s);
      }
      gh(t, e, s) {
          return this.Jf.tc(e, s), xe.resolve();
      }
      yh(t, e, s) {
          this.Jf.sc(e, s);
          const i = this.persistence.nh, n = [];
          return i && e.forEach(e => {
              n.push(i.Oo(t, e));
          }), xe.vn(n);
      }
      wh(t, e) {
          return this.Jf.ic(e), xe.resolve();
      }
      vh(t, e) {
          const s = this.Jf.rc(e);
          return xe.resolve(s);
      }
      Dh(t, e) {
          return xe.resolve(this.Jf.Dh(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 Ln {
      /**
       * 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) {
          this.Zf = {}, this.Oh = new je(0), this.xh = !1, this.xh = !0, this.nh = t(this), 
          this.zh = new Mn(this);
          this.jn = new Xe, this.Qn = new kn(this.jn, t => this.nh.tT(t));
      }
      start() {
          return Promise.resolve();
      }
      Ro() {
          // No durable state to ensure is closed on shutdown.
          return this.xh = !1, Promise.resolve();
      }
      get io() {
          return this.xh;
      }
      no() {
          // No op.
      }
      Do() {
          return this.jn;
      }
      yo(t) {
          let e = this.Zf[t.s()];
          return e || (e = new $n(this.jn, this.nh), this.Zf[t.s()] = e), e;
      }
      vo() {
          return this.zh;
      }
      So() {
          return this.Qn;
      }
      runTransaction(t, e, s) {
          ge("MemoryPersistence", "Starting transaction:", t);
          const i = new On(this.Oh.next());
          return this.nh.eT(), s(i).next(t => this.nh.sT(i).next(() => t)).yn().then(t => (i.Un(), 
          t));
      }
      iT(t, e) {
          return xe.Sn(Object.values(this.Zf).map(s => () => s.Dh(t, e)));
      }
  }
  
  /**
   * Memory persistence is not actually transactional, but future implementations
   * may have transaction-scoped state.
   */ class On extends Ue {
      constructor(t) {
          super(), this.Mh = t;
      }
  }
  
  class xn {
      constructor(t) {
          this.persistence = t, 
          /** Tracks all documents that are active in Query views. */
          this.nT = new li, 
          /** The list of documents that are potentially GCed after each transaction. */
          this.rT = null;
      }
      static hT(t) {
          return new xn(t);
      }
      get oT() {
          if (this.rT) return this.rT;
          throw be();
      }
      ph(t, e, s) {
          return this.nT.ph(s, e), this.oT.delete(s), xe.resolve();
      }
      bh(t, e, s) {
          return this.nT.bh(s, e), this.oT.add(s), xe.resolve();
      }
      Oo(t, e) {
          return this.oT.add(e), xe.resolve();
      }
      removeTarget(t, e) {
          this.nT.ic(e.targetId).forEach(t => this.oT.add(t));
          const s = this.persistence.vo();
          return s.vh(t, e.targetId).next(t => {
              t.forEach(t => this.oT.add(t));
          }).next(() => s.Ih(t, e));
      }
      eT() {
          this.rT = new Set;
      }
      sT(t) {
          // Remove newly orphaned documents.
          const e = this.persistence.So().zr();
          return xe.forEach(this.oT, s => this.aT(t, s).next(t => {
              t || e.kn(s);
          })).next(() => (this.rT = null, e.apply(t)));
      }
      Uo(t, e) {
          return this.aT(t, e).next(t => {
              t ? this.oT.delete(e) : this.oT.add(e);
          });
      }
      tT(t) {
          // For eager GC, we don't care about the document size, there are no size thresholds.
          return 0;
      }
      aT(t, e) {
          return xe.Sn([ () => xe.resolve(this.nT.Dh(e)), () => this.persistence.vo().Dh(t, e), () => this.persistence.iT(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.
   */
  /**
   * Provides all components needed for Firestore with in-memory persistence.
   * Uses EagerGC garbage collection.
   */
  class Bn {
      async initialize(t) {
          this.qd = this.uT(t), this.persistence = this.cT(t), await this.persistence.start(), 
          this._T = this.lT(t), this.F_ = this.dT(t), this.Nd = this.fT(t), this.hl = this.TT(t), 
          this.ET = this.IT(t), this.qd.V_ = t => this.hl.Sd(t, 1 /* SharedClientState */), 
          this.Nd.hl = this.hl, await this.F_.start(), await this.qd.start(), await this.Nd.start(), 
          await this.Nd.Pl(this.hl.Zd);
      }
      IT(t) {
          return new Cn(this.hl);
      }
      lT(t) {
          return null;
      }
      dT(t) {
          return new ui(this.persistence, new Nn, t.wT);
      }
      cT(t) {
          return new Ln(xn.hT);
      }
      fT(t) {
          return new _n(this.F_, t.f_, t.wa, t => this.hl.Sd(t, 0 /* RemoteStore */), t.platform.RT());
      }
      uT(t) {
          return new An;
      }
      TT(t) {
          return new vn(this.F_, this.Nd, this.qd, t.wT, t.Ud);
      }
      clearPersistence(t) {
          throw new R(w.FAILED_PRECONDITION, "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.");
      }
  }
  
  /**
   * Provides all components needed for Firestore with IndexedDB persistence.
   */ class qn extends Bn {
      async initialize(t) {
          await super.initialize(t), 
          // NOTE: This will immediately call the listener, so we make sure to
          // set it after localStore / remoteStore are started.
          await this.persistence.so(async t => {
              await this.hl.Pl(t), this._T && (t && !this._T.io ? this._T.start(this.F_) : t || this._T.stop());
          });
      }
      dT(t) {
          return new ci(this.persistence, new Nn, t.wT);
      }
      TT(t) {
          const e = new Sn(this.F_, this.Nd, this.qd, t.wT, t.Ud);
          return this.qd instanceof mn && (this.qd.hl = e), e;
      }
      lT(t) {
          const e = this.persistence.nh.No;
          return new oi(e, t.wa);
      }
      cT(t) {
          const e = Es.Fo(t.mT), s = t.platform.yc(t.mT.ii);
          return new Es(t.AT.synchronizeTabs, e, t.clientId, t.platform, hi.ru(t.AT.cacheSizeBytes), t.wa, s, this.qd);
      }
      uT(t) {
          if (t.AT.PT && t.AT.synchronizeTabs) {
              if (!mn.jh(t.platform)) throw new R(w.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
              const e = Es.Fo(t.mT);
              return new mn(t.wa, t.platform, e, t.clientId, t.wT);
          }
          return new An;
      }
      clearPersistence(t) {
          const e = Es.Fo(t);
          return Es.clearPersistence(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.
   */
  /**
   * 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 Un {
      constructor(t, e, s, 
      /**
       * 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).
       */
      i) {
          this.platform = t, this.mT = e, this.credentials = s, this.wa = i, this.clientId = De.cn();
      }
      /**
       * Starts up the FirestoreClient, returning only whether or not enabling
       * persistence succeeded.
       *
       * The intent here is to "do the right thing" as far as users are concerned.
       * Namely, in cases where offline persistence is requested and possible,
       * enable it, but otherwise fall back to persistence disabled. For the most
       * part we expect this to succeed one way or the other so we don't expect our
       * users to actually wait on the firestore.enablePersistence Promise since
       * they generally won't care.
       *
       * Of course some users actually do care about whether or not persistence
       * was successfully enabled, so the Promise returned from this method
       * indicates this outcome.
       *
       * This presents a problem though: even before enablePersistence resolves or
       * rejects, users may have made calls to e.g. firestore.collection() which
       * means that the FirestoreClient in there will be available and will be
       * enqueuing actions on the async queue.
       *
       * Meanwhile any failure of an operation on the async queue causes it to
       * panic and reject any further work, on the premise that unhandled errors
       * are fatal.
       *
       * Consequently the fallback is handled internally here in start, and if the
       * fallback succeeds we signal success to the async queue even though the
       * start() itself signals failure.
       *
       * @param componentProvider Provider that returns all core components.
       * @param persistenceSettings Settings object to configure offline
       *     persistence.
       * @returns A deferred result indicating the user-visible result of enabling
       *     offline persistence. This method will reject this if IndexedDB fails to
       *     start for any reason. If usePersistence is false this is
       *     unconditionally resolved.
       */    start(t, e) {
          this.VT();
          // We defer our initialization until we get the current user from
          // setChangeListener(). We block the async queue until we got the initial
          // user and the initialization is completed. This will prevent any scheduled
          // work from happening before initialization is completed.
          // If initializationDone resolved then the FirestoreClient is in a usable
          // state.
          const s = new Ke, i = new Ke;
          // If usePersistence is true, certain classes of errors while starting are
          // recoverable but only by falling back to persistence disabled.
          
          // If there's an error in the first case but not in recovery we cannot
          // reject the promise blocking the async queue because this will cause the
          // async queue to panic.
                  let n = !1;
          // Return only the result of enabling persistence. Note that this does not
          // need to await the completion of initializationDone because the result of
          // this method should not reflect any other kind of failure to start.
          return this.credentials.l(r => {
              if (!n) return n = !0, ge("FirestoreClient", "Initializing. user=", r.uid), this.gT(t, e, r, i).then(s.resolve, s.reject);
              this.wa.oo(() => this.Al(r));
          }), 
          // Block the async queue until initialization is done
          this.wa.oo(() => s.promise), i.promise;
      }
      /** Enables the network connection and requeues all pending operations. */    enableNetwork() {
          return this.VT(), this.wa.enqueue(() => this.hl.enableNetwork());
      }
      /**
       * Initializes persistent storage, attempting to use IndexedDB if
       * usePersistence is true or memory-only if false.
       *
       * If IndexedDB fails because it's already open in another tab or because the
       * platform can't possibly support our implementation then this method rejects
       * the persistenceResult and falls back on memory-only persistence.
       *
       * @param componentProvider The provider that provides all core componennts
       *     for IndexedDB or memory-backed persistence
       * @param persistenceSettings Settings object to configure offline persistence
       * @param user The initial user
       * @param persistenceResult A deferred result indicating the user-visible
       *     result of enabling offline persistence. This method will reject this if
       *     IndexedDB fails to start for any reason. If usePersistence is false
       *     this is unconditionally resolved.
       * @returns a Promise indicating whether or not initialization should
       *     continue, i.e. that one of the persistence implementations actually
       *     succeeded.
       */    async gT(t, e, s, i) {
          try {
              // TODO(mrschmidt): Ideally, ComponentProvider would also initialize
              // Datastore (without duplicating the initializing logic once per
              // provider).
              const n = await this.platform.pT(this.mT), r = this.platform.yc(this.mT.ii), h = function(t, e, s) {
                  return new an(t, e, s);
              }(n, this.credentials, r);
              await t.initialize({
                  wa: this.wa,
                  mT: this.mT,
                  platform: this.platform,
                  f_: h,
                  clientId: this.clientId,
                  wT: s,
                  Ud: 100,
                  AT: e
              }), this.persistence = t.persistence, this.qd = t.qd, this.F_ = t.F_, this.Nd = t.Nd, 
              this.hl = t.hl, this._T = t._T, this.yT = t.ET, 
              // When a user calls clearPersistence() in one client, all other clients
              // need to be terminated to allow the delete to succeed.
              this.persistence.no(async () => {
                  await this.terminate();
              }), i.resolve();
          } catch (t) {
              // An unknown failure on the first stage shuts everything down.
              if (
              // Regardless of whether or not the retry succeeds, from an user
              // perspective, offline persistence has failed.
              i.reject(t), !this.bT(t)) throw t;
              return console.warn("Error enabling offline persistence. Falling back to persistence disabled: " + t), 
              this.gT(new Bn, {
                  PT: !1
              }, s, i);
          }
      }
      /**
       * Decides whether the provided error allows us to gracefully disable
       * persistence (as opposed to crashing the client).
       */    bT(t) {
          return "FirebaseError" === t.name ? t.code === w.FAILED_PRECONDITION || t.code === w.UNIMPLEMENTED : !("undefined" != typeof DOMException && t instanceof DOMException) || (
          // 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.
          22 === t.code || 20 === t.code || 
          // Firefox Private Browsing mode disables IndexedDb and returns
          // INVALID_STATE for any usage.
          11 === t.code);
      }
      /**
       * Checks that the client has not been terminated. Ensures that other methods on
       * this class cannot be called after the client is terminated.
       */    VT() {
          if (this.wa.Ma) throw new R(w.FAILED_PRECONDITION, "The client has already been terminated.");
      }
      Al(t) {
          return this.wa.Wa(), ge("FirestoreClient", "Credential Changed. Current user: " + t.uid), 
          this.hl.Al(t);
      }
      /** Disables the network connection. Pending operations will not complete. */    disableNetwork() {
          return this.VT(), this.wa.enqueue(() => this.hl.disableNetwork());
      }
      terminate() {
          return this.wa.qa(async () => {
              // PORTING NOTE: LocalStore does not need an explicit shutdown on web.
              this._T && this._T.stop(), await this.Nd.Ro(), await this.qd.Ro(), await this.persistence.Ro(), 
              // `removeChangeListener` must be called after shutting down the
              // RemoteStore as it will prevent the RemoteStore from retrieving
              // auth tokens.
              this.credentials.T();
          });
      }
      /**
       * 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.
       */    waitForPendingWrites() {
          this.VT();
          const t = new Ke;
          return this.wa.oo(() => this.hl._f(t)), t.promise;
      }
      listen(t, e, s) {
          this.VT();
          const i = new Fn(t, e, s);
          return this.wa.oo(() => this.yT.listen(i)), i;
      }
      nl(t) {
          // Checks for termination but does not raise error, allowing unlisten after
          // termination to be a no-op.
          this.vT || this.wa.oo(() => this.yT.nl(t));
      }
      async ST(t) {
          this.VT();
          const e = new Ke;
          return await this.wa.enqueue(async () => {
              try {
                  const s = await this.F_.qu(t);
                  s instanceof Vt ? e.resolve(s) : s instanceof gt ? e.resolve(null) : e.reject(new R(w.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 (s) {
                  const i = si(s, `Failed to get document '${t} from cache`);
                  e.reject(i);
              }
          }), e.promise;
      }
      async DT(t) {
          this.VT();
          const e = new Ke;
          return await this.wa.enqueue(async () => {
              try {
                  const s = await this.F_.Wu(t, 
                  /* usePreviousResults= */ !0), i = new gn(t, s.ju), n = i.Pd(s.documents), r = i.xn(n, 
                  /* updateLimboDocuments= */ !1);
                  e.resolve(r.snapshot);
              } catch (s) {
                  const i = si(s, `Failed to execute query '${t} against cache`);
                  e.reject(i);
              }
          }), e.promise;
      }
      write(t) {
          this.VT();
          const e = new Ke;
          return this.wa.oo(() => this.hl.write(t, e)), e.promise;
      }
      ii() {
          return this.mT.ii;
      }
      Sf(t) {
          this.VT(), this.wa.oo(() => (this.yT.Sf(t), Promise.resolve()));
      }
      Df(t) {
          // Checks for shutdown but does not raise error, allowing remove after
          // shutdown to be a no-op.
          this.vT || this.wa.oo(() => (this.yT.Df(t), Promise.resolve()));
      }
      get vT() {
          // Technically, the asyncQueue is still running, but only accepting operations
          // related to termination or supposed to be run after termination. It is effectively
          // terminated to the eyes of users.
          return this.wa.Ma;
      }
      transaction(t) {
          this.VT();
          const e = new Ke;
          return this.wa.oo(() => (this.hl.runTransaction(this.wa, t, e), Promise.resolve())), 
          e.promise;
      }
  }
  
  /**
   * @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 Qn {
      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.CT(this.observer.next, t);
      }
      error(t) {
          this.CT(this.observer.error, t);
      }
      FT() {
          this.muted = !0;
      }
      CT(t, e) {
          this.muted || setTimeout(() => {
              this.muted || t(e);
          }, 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.
   */ function Wn(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 s = t;
          for (const t of e) if (t in s && "function" == typeof s[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 Firestore's internal types to the JavaScript types that we expose
   * to the user.
   */ (t, [ "next", "error", "complete" ]);
  }
  
  class jn {
      constructor(t, e, s, i) {
          this.firestore = t, this.timestampsInSnapshots = e, this.NT = s, this.converter = i;
      }
      $T(t) {
          switch (U(t)) {
            case 0 /* NullValue */ :
              return null;
  
            case 1 /* BooleanValue */ :
              return t.booleanValue;
  
            case 2 /* NumberValue */ :
              return Y(t.integerValue || t.doubleValue);
  
            case 3 /* TimestampValue */ :
              return this.kT(t.timestampValue);
  
            case 4 /* ServerTimestampValue */ :
              return this.MT(t);
  
            case 5 /* StringValue */ :
              return t.stringValue;
  
            case 6 /* BlobValue */ :
              return new ki(J(t.bytesValue));
  
            case 7 /* RefValue */ :
              return this.LT(t.referenceValue);
  
            case 8 /* GeoPointValue */ :
              return this.OT(t.geoPointValue);
  
            case 9 /* ArrayValue */ :
              return this.xT(t.arrayValue);
  
            case 10 /* ObjectValue */ :
              return this.BT(t.mapValue);
  
            default:
              throw be();
          }
      }
      BT(t) {
          const e = {};
          return N(t.fields || {}, (t, s) => {
              e[t] = this.$T(s);
          }), e;
      }
      OT(t) {
          return new Wi(Y(t.latitude), Y(t.longitude));
      }
      xT(t) {
          return (t.values || []).map(t => this.$T(t));
      }
      MT(t) {
          switch (this.NT) {
            case "previous":
              const e = function t(e) {
                  const s = e.mapValue.fields.__previous_value__;
                  return x(s) ? t(s) : s;
              }(t);
              return null == e ? null : this.$T(e);
  
            case "estimate":
              return this.kT(B(t));
  
            default:
              return null;
          }
      }
      kT(t) {
          const e = H(t), s = new p(e.seconds, e.nanos);
          return this.timestampsInSnapshots ? s : s.toDate();
      }
      LT(t) {
          const e = v.K(t);
          ve(Re(e));
          const s = new ke(e.get(1), e.get(3)), i = new C(e.k(5));
          return s.isEqual(this.firestore.Nc) || 
          // TODO(b/64130202): Somehow support foreign references.
          pe(`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 (${this.firestore.Nc.projectId}/${this.firestore.Nc.database}) ` + "instead."), 
          new Jn(i, this.firestore, this.converter);
      }
  }
  
  /**
   * @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.
   */
  // settings() defaults:
  const Kn = hi.au;
  
  /**
   * 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 Gn {
      constructor(t) {
          var e, s;
          if (void 0 === t.host) {
              if (void 0 !== t.ssl) throw new R(w.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
              this.host = "firestore.googleapis.com", this.ssl = !0;
          } else mi("settings", "non-empty string", "host", t.host), this.host = t.host, Ai("settings", "boolean", "ssl", t.ssl), 
          this.ssl = null === (e = t.ssl) || void 0 === e || e;
          if (vi("settings", t, [ "host", "ssl", "credentials", "timestampsInSnapshots", "cacheSizeBytes", "experimentalForceLongPolling" ]), 
          Ai("settings", "object", "credentials", t.credentials), this.credentials = t.credentials, 
          Ai("settings", "boolean", "timestampsInSnapshots", t.timestampsInSnapshots), 
          // Nobody should set timestampsInSnapshots anymore, but the error depends on
          // whether they set it to true or false...
          !0 === t.timestampsInSnapshots ? pe("The setting 'timestampsInSnapshots: true' is no longer required and should be removed.") : !1 === t.timestampsInSnapshots && pe("Support for 'timestampsInSnapshots: false' will be removed soon. You must update your code to handle Timestamp objects."), 
          this.timestampsInSnapshots = null === (s = t.timestampsInSnapshots) || void 0 === s || s, 
          Ai("settings", "number", "cacheSizeBytes", t.cacheSizeBytes), void 0 === t.cacheSizeBytes) this.cacheSizeBytes = hi.cu; else {
              if (t.cacheSizeBytes !== Kn && t.cacheSizeBytes < hi.uu) throw new R(w.INVALID_ARGUMENT, `cacheSizeBytes must be at least ${hi.uu}`);
              this.cacheSizeBytes = t.cacheSizeBytes;
          }
          Ai("settings", "boolean", "experimentalForceLongPolling", t.experimentalForceLongPolling), 
          this.forceLongPolling = void 0 !== t.experimentalForceLongPolling && t.experimentalForceLongPolling;
      }
      isEqual(t) {
          return this.host === t.host && this.ssl === t.ssl && this.timestampsInSnapshots === t.timestampsInSnapshots && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.forceLongPolling === t.forceLongPolling;
      }
  }
  
  /**
   * The root reference to the database.
   */ class zn {
      // Note: We are using `MemoryComponentProvider` as a default
      // ComponentProvider to ensure backwards compatibility with the format
      // expected by the console build.
      constructor(t, e, s = new Bn) {
          if (this.qT = null, 
          // Public for use in tests.
          // TODO(mikelehen): Use modularized initialization instead.
          this.UT = new ei, this.INTERNAL = {
              delete: async () => {
                  // The client must be initalized to ensure that all subsequent API usage
                  // throws an exception.
                  this.QT(), await this.WT.terminate();
              }
          }, "object" == typeof t.options) {
              // This is very likely a Firebase app object
              // TODO(b/34177605): Can we somehow use instanceof?
              const s = t;
              this.qT = s, this.Nc = zn.jT(s), this.KT = s.name, this.GT = new P(e);
          } else {
              const e = t;
              if (!e.projectId) throw new R(w.INVALID_ARGUMENT, "Must provide projectId");
              this.Nc = new ke(e.projectId, e.database), 
              // Use a default persistenceKey that lines up with FirebaseApp.
              this.KT = "[DEFAULT]", this.GT = new A;
          }
          this.zT = s, this.HT = new Gn({}), this.YT = new Yi(this.Nc);
      }
      settings(t) {
          Ti("Firestore.settings", arguments, 1), wi("Firestore.settings", "object", 1, t);
          const e = new Gn(t);
          if (this.WT && !this.HT.isEqual(e)) throw new R(w.FAILED_PRECONDITION, "Firestore has already been started and its settings can no longer be changed. You can only call settings() before calling any other methods on a Firestore object.");
          this.HT = e, void 0 !== e.credentials && (this.GT = function(t) {
              if (!t) return new A;
              switch (t.type) {
                case "gapi":
                  const e = t.JT;
                  // Make sure this really is a Gapi client.
                                  return ve(!("object" != typeof e || null === e || !e.auth || !e.auth.getAuthHeaderValueForFirstParty)), 
                  new g(e, t.V || "0");
  
                case "provider":
                  return t.JT;
  
                default:
                  throw new R(w.INVALID_ARGUMENT, "makeCredentialsProvider failed due to invalid credential type");
              }
          }
          /**
   * @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 earlist date supported by Firestore timestamps (0001-01-01T00:00:00Z).
          (e.credentials));
      }
      enableNetwork() {
          return this.QT(), this.WT.enableNetwork();
      }
      disableNetwork() {
          return this.QT(), this.WT.disableNetwork();
      }
      enablePersistence(t) {
          var e, s;
          if (this.WT) throw new R(w.FAILED_PRECONDITION, "Firestore has already been started and persistence can no longer be enabled. You can only call enablePersistence() before calling any other methods on a Firestore object.");
          let i = !1;
          return t && (void 0 !== t.experimentalTabSynchronization && pe("The 'experimentalTabSynchronization' setting will be removed. Use 'synchronizeTabs' instead."), 
          i = null !== (s = null !== (e = t.synchronizeTabs) && void 0 !== e ? e : t.experimentalTabSynchronization) && void 0 !== s && s), 
          this.XT(this.zT, {
              PT: !0,
              cacheSizeBytes: this.HT.cacheSizeBytes,
              synchronizeTabs: i
          });
      }
      async clearPersistence() {
          if (void 0 !== this.WT && !this.WT.vT) throw new R(w.FAILED_PRECONDITION, "Persistence cannot be cleared after this Firestore instance is initialized.");
          const t = new Ke;
          return this.UT.La(async () => {
              try {
                  const e = this.ZT();
                  await this.zT.clearPersistence(e), t.resolve();
              } catch (e) {
                  t.reject(e);
              }
          }), t.promise;
      }
      terminate() {
          return this.app._removeServiceInstance("firestore"), this.INTERNAL.delete();
      }
      get tE() {
          return this.QT(), this.WT.vT;
      }
      waitForPendingWrites() {
          return this.QT(), this.WT.waitForPendingWrites();
      }
      onSnapshotsInSync(t) {
          if (this.QT(), Wn(t)) return this.eE(t);
          {
              wi("Firestore.onSnapshotsInSync", "function", 1, t);
              const e = {
                  next: t
              };
              return this.eE(e);
          }
      }
      eE(t) {
          const e = new Qn({
              next: () => {
                  t.next && t.next();
              },
              error: t => {
                  throw be();
              }
          });
          return this.WT.Sf(e), () => {
              e.FT(), this.WT.Df(e);
          };
      }
      QT() {
          return this.WT || 
          // Kick off starting the client but don't actually wait for it.
          // eslint-disable-next-line @typescript-eslint/no-floating-promises
          this.XT(new Bn, {
              PT: !1
          }), this.WT;
      }
      ZT() {
          return new $e(this.Nc, this.KT, this.HT.host, this.HT.ssl, this.HT.forceLongPolling);
      }
      XT(t, e) {
          const s = this.ZT();
          return this.WT = new Un(me.nt(), s, this.GT, this.UT), this.WT.start(t, e);
      }
      static jT(t) {
          if (e = t.options, s = "projectId", !Object.prototype.hasOwnProperty.call(e, s)) throw new R(w.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
          var e, 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.
   */
          /**
   * Helper function to prevent instantiation through the constructor.
   *
   * This method creates a new constructor that throws when it's invoked.
   * The prototype of that constructor is then set to the prototype of the hidden
   * "class" to expose all the prototype methods and allow for instanceof
   * checks.
   *
   * To also make all the static methods available, all properties of the
   * original constructor are copied to the new constructor.
   */        const i = t.options.projectId;
          if (!i || "string" != typeof i) throw new R(w.INVALID_ARGUMENT, "projectId must be a string in FirebaseApp.options");
          return new ke(i);
      }
      get app() {
          if (!this.qT) throw new R(w.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
          return this.qT;
      }
      collection(t) {
          return Ti("Firestore.collection", arguments, 1), wi("Firestore.collection", "non-empty string", 1, t), 
          this.QT(), new ir(v.K(t), this);
      }
      doc(t) {
          return Ti("Firestore.doc", arguments, 1), wi("Firestore.doc", "non-empty string", 1, t), 
          this.QT(), Jn.sE(v.K(t), this);
      }
      collectionGroup(t) {
          if (Ti("Firestore.collectionGroup", arguments, 1), wi("Firestore.collectionGroup", "non-empty string", 1, t), 
          t.indexOf("/") >= 0) throw new R(w.INVALID_ARGUMENT, `Invalid collection ID '${t}' passed to function ` + "Firestore.collectionGroup(). Collection IDs must not contain '/'.");
          return this.QT(), new er(new bt(v.G, t), this);
      }
      runTransaction(t) {
          return Ti("Firestore.runTransaction", arguments, 1), wi("Firestore.runTransaction", "function", 1, t), 
          this.QT().transaction(e => t(new Hn(this, e)));
      }
      batch() {
          return this.QT(), new Yn(this);
      }
      static get logLevel() {
          switch (Pe()) {
            case s.DEBUG:
              return "debug";
  
            case s.SILENT:
              return "silent";
  
            default:
              // The default log level is error
              return "error";
          }
      }
      static setLogLevel(t) {
          switch (Ti("Firestore.setLogLevel", arguments, 1), wi("Firestore.setLogLevel", "non-empty string", 1, t), 
          t) {
            case "debug":
              Ve(s.DEBUG);
              break;
  
            case "error":
              Ve(s.ERROR);
              break;
  
            case "silent":
              Ve(s.SILENT);
              break;
  
            default:
              throw new R(w.INVALID_ARGUMENT, "Invalid log level: " + t);
          }
      }
      // Note: this is not a property because the minifier can't work correctly with
      // the way TypeScript compiler outputs properties.
      iE() {
          return this.HT.timestampsInSnapshots;
      }
  }
  
  /**
   * A reference to a transaction.
   */ class Hn {
      constructor(t, e) {
          this.nE = t, this.rE = e;
      }
      get(t) {
          Ti("Transaction.get", arguments, 1);
          const e = or("Transaction.get", t, this.nE);
          return this.rE.R_([ e.$c ]).then(t => {
              if (!t || 1 !== t.length) return be();
              const s = t[0];
              if (s instanceof gt) return new Zn(this.nE, e.$c, null, 
              /* fromCache= */ !1, 
              /* hasPendingWrites= */ !1, e.hE);
              if (s instanceof Vt) return new Zn(this.nE, e.$c, s, 
              /* fromCache= */ !1, 
              /* hasPendingWrites= */ !1, e.hE);
              throw be();
          });
      }
      set(t, e, s) {
          Ii("Transaction.set", arguments, 2, 3);
          const i = or("Transaction.set", t, this.nE);
          s = nr("Transaction.set", s);
          const [n, r] = ur(i.hE, e, "Transaction.set"), h = s.merge || s.mergeFields ? this.nE.YT.Sc(r, n, s.mergeFields) : this.nE.YT.bc(r, n);
          return this.rE.set(i.$c, h), this;
      }
      update(t, e, s, ...i) {
          let n, r;
          return "string" == typeof e || e instanceof Mi ? (Ei("Transaction.update", arguments, 3), 
          n = or("Transaction.update", t, this.nE), r = this.nE.YT.Cc("Transaction.update", e, s, i)) : (Ti("Transaction.update", arguments, 2), 
          n = or("Transaction.update", t, this.nE), r = this.nE.YT.Dc("Transaction.update", e)), 
          this.rE.update(n.$c, r), this;
      }
      delete(t) {
          Ti("Transaction.delete", arguments, 1);
          const e = or("Transaction.delete", t, this.nE);
          return this.rE.delete(e.$c), this;
      }
  }
  
  class Yn {
      constructor(t) {
          this.nE = t, this.oE = [], this.aE = !1;
      }
      set(t, e, s) {
          Ii("WriteBatch.set", arguments, 2, 3), this.uE();
          const i = or("WriteBatch.set", t, this.nE);
          s = nr("WriteBatch.set", s);
          const [n, r] = ur(i.hE, e, "WriteBatch.set"), h = s.merge || s.mergeFields ? this.nE.YT.Sc(r, n, s.mergeFields) : this.nE.YT.bc(r, n);
          return this.oE = this.oE.concat(h.Rc(i.$c, lt.ft())), this;
      }
      update(t, e, s, ...i) {
          let n, r;
          return this.uE(), "string" == typeof e || e instanceof Mi ? (Ei("WriteBatch.update", arguments, 3), 
          n = or("WriteBatch.update", t, this.nE), r = this.nE.YT.Cc("WriteBatch.update", e, s, i)) : (Ti("WriteBatch.update", arguments, 2), 
          n = or("WriteBatch.update", t, this.nE), r = this.nE.YT.Dc("WriteBatch.update", e)), 
          this.oE = this.oE.concat(r.Rc(n.$c, lt.exists(!0))), this;
      }
      delete(t) {
          Ti("WriteBatch.delete", arguments, 1), this.uE();
          const e = or("WriteBatch.delete", t, this.nE);
          return this.oE = this.oE.concat(new It(e.$c, lt.ft())), this;
      }
      commit() {
          return this.uE(), this.aE = !0, this.oE.length > 0 ? this.nE.QT().write(this.oE) : Promise.resolve();
      }
      uE() {
          if (this.aE) throw new R(w.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called.");
      }
  }
  
  /**
   * A reference to a particular document in a collection in the database.
   */ class Jn {
      constructor(t, e, s) {
          this.$c = t, this.firestore = e, this.hE = s, this.WT = this.firestore.QT();
      }
      static sE(t, e, s) {
          if (t.length % 2 != 0) throw new R(w.INVALID_ARGUMENT, "Invalid document reference. Document references must have an even number of segments, but " + `${t.j()} has ${t.length}`);
          return new Jn(new C(t), e, s);
      }
      get id() {
          return this.$c.path.O();
      }
      get parent() {
          return new ir(this.$c.path.M(), this.firestore, this.hE);
      }
      get path() {
          return this.$c.path.j();
      }
      collection(t) {
          if (Ti("DocumentReference.collection", arguments, 1), wi("DocumentReference.collection", "non-empty string", 1, t), 
          !t) throw new R(w.INVALID_ARGUMENT, "Must provide a non-empty collection name to collection()");
          const e = v.K(t);
          return new ir(this.$c.path.child(e), this.firestore);
      }
      isEqual(t) {
          if (!(t instanceof Jn)) throw Si("isEqual", "DocumentReference", 1, t);
          return this.firestore === t.firestore && this.$c.isEqual(t.$c) && this.hE === t.hE;
      }
      set(t, e) {
          Ii("DocumentReference.set", arguments, 1, 2), e = nr("DocumentReference.set", e);
          const [s, i] = ur(this.hE, t, "DocumentReference.set"), n = e.merge || e.mergeFields ? this.firestore.YT.Sc(i, s, e.mergeFields) : this.firestore.YT.bc(i, s);
          return this.WT.write(n.Rc(this.$c, lt.ft()));
      }
      update(t, e, ...s) {
          let i;
          return "string" == typeof t || t instanceof Mi ? (Ei("DocumentReference.update", arguments, 2), 
          i = this.firestore.YT.Cc("DocumentReference.update", t, e, s)) : (Ti("DocumentReference.update", arguments, 1), 
          i = this.firestore.YT.Dc("DocumentReference.update", t)), this.WT.write(i.Rc(this.$c, lt.exists(!0)));
      }
      delete() {
          return Ti("DocumentReference.delete", arguments, 0), this.WT.write([ new It(this.$c, lt.ft()) ]);
      }
      onSnapshot(...t) {
          Ii("DocumentReference.onSnapshot", arguments, 1, 4);
          let e, s = {
              includeMetadataChanges: !1
          }, i = 0;
          "object" != typeof t[i] || Wn(t[i]) || (s = t[i], vi("DocumentReference.onSnapshot", s, [ "includeMetadataChanges" ]), 
          Ai("DocumentReference.onSnapshot", "boolean", "includeMetadataChanges", s.includeMetadataChanges), 
          i++);
          const n = {
              includeMetadataChanges: s.includeMetadataChanges
          };
          return Wn(t[i]) ? e = t[i] : (wi("DocumentReference.onSnapshot", "function", i, t[i]), 
          Ri("DocumentReference.onSnapshot", "function", i + 1, t[i + 1]), Ri("DocumentReference.onSnapshot", "function", i + 2, t[i + 2]), 
          e = {
              next: t[i],
              error: t[i + 1],
              complete: t[i + 2]
          }), this.cE(n, e);
      }
      cE(t, e) {
          let s = t => {
              console.error("Uncaught Error in onSnapshot:", t);
          };
          e.error && (s = e.error.bind(e));
          const i = new Qn({
              next: t => {
                  if (e.next) {
                      const s = t.docs.get(this.$c);
                      e.next(new Zn(this.firestore, this.$c, s, t.fromCache, t.hasPendingWrites, this.hE));
                  }
              },
              error: s
          }), n = this.WT.listen(bt.Wt(this.$c.path), i, t);
          return () => {
              i.FT(), this.WT.nl(n);
          };
      }
      get(t) {
          return Ii("DocumentReference.get", arguments, 0, 1), hr("DocumentReference.get", t), 
          new Promise((e, s) => {
              t && "cache" === t.source ? this.firestore.QT().ST(this.$c).then(t => {
                  e(new Zn(this.firestore, this.$c, t, 
                  /*fromCache=*/ !0, t instanceof Vt && t.At, this.hE));
              }, s) : this._E(e, s, t);
          });
      }
      _E(t, e, s) {
          const i = this.cE({
              includeMetadataChanges: !0,
              Lf: !0
          }, {
              next: n => {
                  // Remove query first before passing event to user to avoid
                  // user actions affecting the now stale query.
                  i(), !n.exists && n.metadata.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.
                  e(new R(w.UNAVAILABLE, "Failed to get document because the client is offline.")) : n.exists && n.metadata.fromCache && s && "server" === s.source ? e(new R(w.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.)')) : t(n);
              },
              error: e
          });
      }
      withConverter(t) {
          return new Jn(this.$c, this.firestore, t);
      }
  }
  
  class Xn {
      constructor(t, e) {
          this.hasPendingWrites = t, this.fromCache = e;
      }
      isEqual(t) {
          return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;
      }
  }
  
  class Zn {
      constructor(t, e, s, i, n, r) {
          this.nE = t, this.$c = e, this.lE = s, this.dE = i, this.fE = n, this.hE = r;
      }
      data(t) {
          if (Ii("DocumentSnapshot.data", arguments, 0, 1), t = rr("DocumentSnapshot.data", t), 
          this.lE) {
              // We only want to use the converter and create a new DocumentSnapshot
              // if a converter has been provided.
              if (this.hE) {
                  const e = new tr(this.nE, this.$c, this.lE, this.dE, this.fE);
                  return this.hE.fromFirestore(e, t);
              }
              return new jn(this.nE, this.nE.iE(), t.serverTimestamps, 
              /* converter= */ void 0).$T(this.lE.Mt());
          }
      }
      get(t, e) {
          if (Ii("DocumentSnapshot.get", arguments, 1, 2), e = rr("DocumentSnapshot.get", e), 
          this.lE) {
              const s = this.lE.data().field(en("DocumentSnapshot.get", t));
              if (null !== s) {
                  return new jn(this.nE, this.nE.iE(), e.serverTimestamps, this.hE).$T(s);
              }
          }
      }
      get id() {
          return this.$c.path.O();
      }
      get ref() {
          return new Jn(this.$c, this.nE, this.hE);
      }
      get exists() {
          return null !== this.lE;
      }
      get metadata() {
          return new Xn(this.fE, this.dE);
      }
      isEqual(t) {
          if (!(t instanceof Zn)) throw Si("isEqual", "DocumentSnapshot", 1, t);
          return this.nE === t.nE && this.dE === t.dE && this.$c.isEqual(t.$c) && (null === this.lE ? null === t.lE : this.lE.isEqual(t.lE)) && this.hE === t.hE;
      }
  }
  
  class tr extends Zn {
      data(t) {
          return super.data(t);
      }
  }
  
  class er {
      constructor(t, e, s) {
          this.TE = t, this.firestore = e, this.hE = s;
      }
      where(t, e, s) {
          Ti("Query.where", arguments, 3), bi("Query.where", 3, s);
          // Enumerated from the WhereFilterOp type in index.d.ts.
          const i = function(t, e, s, i) {
              if (!e.some(t => t === i)) throw new R(w.INVALID_ARGUMENT, `Invalid value ${yi(i)} provided to function ` + `${t}() for its ${Ci(s)} argument. Acceptable ` + `values: ${e.join(", ")}`);
              return i;
          }("Query.where", [ "<" /* LESS_THAN */ , "<=" /* LESS_THAN_OR_EQUAL */ , "==" /* EQUAL */ , ">=" /* GREATER_THAN_OR_EQUAL */ , ">" /* GREATER_THAN */ , "array-contains" /* ARRAY_CONTAINS */ , "in" /* IN */ , "array-contains-any" /* ARRAY_CONTAINS_ANY */ ], 2, e);
          let n;
          const r = en("Query.where", t);
          if (r.Y()) {
              if ("array-contains" /* ARRAY_CONTAINS */ === i || "array-contains-any" /* ARRAY_CONTAINS_ANY */ === i) throw new R(w.INVALID_ARGUMENT, `Invalid Query. You can't perform '${i}' ` + "queries on FieldPath.documentId().");
              if ("in" /* IN */ === i) {
                  this.EE(s, i);
                  const t = [];
                  for (const e of s) t.push(this.IE(e));
                  n = {
                      arrayValue: {
                          values: t
                      }
                  };
              } else n = this.IE(s);
          } else "in" /* IN */ !== i && "array-contains-any" /* ARRAY_CONTAINS_ANY */ !== i || this.EE(s, i), 
          n = this.firestore.YT.Fc("Query.where", s, 
          // We only allow nested arrays for IN queries.
          /** allowArrays = */ "in" /* IN */ === i);
          const h = vt.create(r, i, n);
          return this.wE(h), new er(this.TE.Gt(h), this.firestore, this.hE);
      }
      orderBy(t, e) {
          let s;
          if (Ii("Query.orderBy", arguments, 1, 2), Ri("Query.orderBy", "non-empty string", 2, e), 
          void 0 === e || "asc" === e) s = "asc" /* ASCENDING */; else {
              if ("desc" !== e) throw new R(w.INVALID_ARGUMENT, `Function Query.orderBy() has unknown direction '${e}', ` + "expected 'asc' or 'desc'.");
              s = "desc" /* DESCENDING */;
          }
          if (null !== this.TE.startAt) throw new R(w.INVALID_ARGUMENT, "Invalid query. You must not call Query.startAt() or Query.startAfter() before calling Query.orderBy().");
          if (null !== this.TE.endAt) throw new R(w.INVALID_ARGUMENT, "Invalid query. You must not call Query.endAt() or Query.endBefore() before calling Query.orderBy().");
          const i = en("Query.orderBy", t), n = new kt(i, s);
          return this.RE(n), new er(this.TE.zt(n), this.firestore, this.hE);
      }
      limit(t) {
          return Ti("Query.limit", arguments, 1), wi("Query.limit", "number", 1, t), Di("Query.limit", 1, t), 
          new er(this.TE.Ht(t), this.firestore, this.hE);
      }
      limitToLast(t) {
          return Ti("Query.limitToLast", arguments, 1), wi("Query.limitToLast", "number", 1, t), 
          Di("Query.limitToLast", 1, t), new er(this.TE.Yt(t), this.firestore, this.hE);
      }
      startAt(t, ...e) {
          Ei("Query.startAt", arguments, 1);
          const s = this.mE("Query.startAt", t, e, 
          /*before=*/ !0);
          return new er(this.TE.Jt(s), this.firestore, this.hE);
      }
      startAfter(t, ...e) {
          Ei("Query.startAfter", arguments, 1);
          const s = this.mE("Query.startAfter", t, e, 
          /*before=*/ !1);
          return new er(this.TE.Jt(s), this.firestore, this.hE);
      }
      endBefore(t, ...e) {
          Ei("Query.endBefore", arguments, 1);
          const s = this.mE("Query.endBefore", t, e, 
          /*before=*/ !0);
          return new er(this.TE.Xt(s), this.firestore, this.hE);
      }
      endAt(t, ...e) {
          Ei("Query.endAt", arguments, 1);
          const s = this.mE("Query.endAt", t, e, 
          /*before=*/ !1);
          return new er(this.TE.Xt(s), this.firestore, this.hE);
      }
      isEqual(t) {
          if (!(t instanceof er)) throw Si("isEqual", "Query", 1, t);
          return this.firestore === t.firestore && this.TE.isEqual(t.TE);
      }
      withConverter(t) {
          return new er(this.TE, this.firestore, t);
      }
      /** Helper function to create a bound from a document or fields */    mE(t, e, s, i) {
          if (bi(t, 1, e), e instanceof Zn) {
              if (s.length > 0) throw new R(w.INVALID_ARGUMENT, `Too many arguments provided to ${t}().`);
              const n = e;
              if (!n.exists) throw new R(w.NOT_FOUND, "Can't use a DocumentSnapshot that doesn't exist for " + `${t}().`);
              return this.AE(n.lE, i);
          }
          {
              const n = [ e ].concat(s);
              return this.PE(t, n, i);
          }
      }
      /**
       * 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.
       */    AE(t, e) {
          const s = [];
          // 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 e of this.TE.orderBy) if (e.field.Y()) s.push(X(this.firestore.Nc, t.key)); else {
              const i = t.field(e.field);
              if (x(i)) throw new R(w.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + e.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');
              if (null === i) {
                  const t = e.field.j();
                  throw new R(w.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.");
              }
              s.push(i);
          }
          return new $t(s, e);
      }
      /**
       * Converts a list of field values to a Bound for the given query.
       */    PE(t, e, s) {
          // Use explicit order by's because it has to match the query the user made
          const i = this.TE.xt;
          if (e.length > i.length) throw new R(w.INVALID_ARGUMENT, `Too many arguments provided to ${t}(). ` + "The number of arguments must be less than or equal to the number of Query.orderBy() clauses");
          const n = [];
          for (let s = 0; s < e.length; s++) {
              const r = e[s];
              if (i[s].field.Y()) {
                  if ("string" != typeof r) throw new R(w.INVALID_ARGUMENT, "Invalid query. Expected a string for document ID in " + `${t}(), but got a ${typeof r}`);
                  if (!this.TE._e() && -1 !== r.indexOf("/")) throw new R(w.INVALID_ARGUMENT, "Invalid query. When querying a collection and ordering by FieldPath.documentId(), " + `the value passed to ${t}() must be a plain document ID, but ` + `'${r}' contains a slash.`);
                  const e = this.TE.path.child(v.K(r));
                  if (!C.et(e)) throw new R(w.INVALID_ARGUMENT, "Invalid query. When querying a collection group and ordering by " + `FieldPath.documentId(), the value passed to ${t}() must result in a ` + `valid document path, but '${e}' is not because it contains an odd number ` + "of segments.");
                  const s = new C(e);
                  n.push(X(this.firestore.Nc, s));
              } else {
                  const e = this.firestore.YT.Fc(t, r);
                  n.push(e);
              }
          }
          return new $t(n, s);
      }
      onSnapshot(...t) {
          Ii("Query.onSnapshot", arguments, 1, 4);
          let e, s = {}, i = 0;
          return "object" != typeof t[i] || Wn(t[i]) || (s = t[i], vi("Query.onSnapshot", s, [ "includeMetadataChanges" ]), 
          Ai("Query.onSnapshot", "boolean", "includeMetadataChanges", s.includeMetadataChanges), 
          i++), Wn(t[i]) ? e = t[i] : (wi("Query.onSnapshot", "function", i, t[i]), Ri("Query.onSnapshot", "function", i + 1, t[i + 1]), 
          Ri("Query.onSnapshot", "function", i + 2, t[i + 2]), e = {
              next: t[i],
              error: t[i + 1],
              complete: t[i + 2]
          }), this.VE(this.TE), this.cE(s, e);
      }
      cE(t, e) {
          let s = t => {
              console.error("Uncaught Error in onSnapshot:", t);
          };
          e.error && (s = e.error.bind(e));
          const i = new Qn({
              next: t => {
                  e.next && e.next(new sr(this.firestore, this.TE, t, this.hE));
              },
              error: s
          }), n = this.firestore.QT(), r = n.listen(this.TE, i, t);
          return () => {
              i.FT(), n.nl(r);
          };
      }
      VE(t) {
          if (t.ae() && 0 === t.xt.length) throw new R(w.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause");
      }
      get(t) {
          return Ii("Query.get", arguments, 0, 1), hr("Query.get", t), this.VE(this.TE), new Promise((e, s) => {
              t && "cache" === t.source ? this.firestore.QT().DT(this.TE).then(t => {
                  e(new sr(this.firestore, this.TE, t, this.hE));
              }, s) : this._E(e, s, t);
          });
      }
      _E(t, e, s) {
          const i = this.cE({
              includeMetadataChanges: !0,
              Lf: !0
          }, {
              next: n => {
                  // Remove query first before passing event to user to avoid
                  // user actions affecting the now stale query.
                  i(), n.metadata.fromCache && s && "server" === s.source ? e(new R(w.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.)')) : t(n);
              },
              error: e
          });
      }
      /**
       * 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.
       */    IE(t) {
          if ("string" == typeof t) {
              if ("" === t) throw new R(w.INVALID_ARGUMENT, "Invalid query. When querying with FieldPath.documentId(), you must provide a valid document ID, but it was an empty string.");
              if (!this.TE._e() && -1 !== t.indexOf("/")) throw new R(w.INVALID_ARGUMENT, "Invalid query. When querying a collection by FieldPath.documentId(), you must provide a plain document ID, but " + `'${t}' contains a '/' character.`);
              const e = this.TE.path.child(v.K(t));
              if (!C.et(e)) throw new R(w.INVALID_ARGUMENT, "Invalid query. When querying a collection group by FieldPath.documentId(), the value provided must result in a valid document path, " + `but '${e}' is not because it has an odd number of segments (${e.length}).`);
              return X(this.firestore.Nc, new C(e));
          }
          if (t instanceof Jn) {
              const e = t;
              return X(this.firestore.Nc, e.$c);
          }
          throw new R(w.INVALID_ARGUMENT, "Invalid query. When querying with FieldPath.documentId(), you must provide a valid string or a DocumentReference, but it was: " + `${yi(t)}.`);
      }
      /**
       * Validates that the value passed into a disjunctrive filter satisfies all
       * array requirements.
       */    EE(t, e) {
          if (!Array.isArray(t) || 0 === t.length) throw new R(w.INVALID_ARGUMENT, "Invalid Query. A non-empty array is required for " + `'${e.toString()}' filters.`);
          if (t.length > 10) throw new R(w.INVALID_ARGUMENT, `Invalid Query. '${e.toString()}' filters support a ` + "maximum of 10 elements in the value array.");
          if (t.indexOf(null) >= 0) throw new R(w.INVALID_ARGUMENT, `Invalid Query. '${e.toString()}' filters cannot contain 'null' ` + "in the value array.");
          if (t.filter(t => Number.isNaN(t)).length > 0) throw new R(w.INVALID_ARGUMENT, `Invalid Query. '${e.toString()}' filters cannot contain 'NaN' ` + "in the value array.");
      }
      wE(t) {
          if (t instanceof vt) {
              const e = [ "array-contains" /* ARRAY_CONTAINS */ , "array-contains-any" /* ARRAY_CONTAINS_ANY */ ], s = [ "in" /* IN */ , "array-contains-any" /* ARRAY_CONTAINS_ANY */ ], i = e.indexOf(t.op) >= 0, n = s.indexOf(t.op) >= 0;
              if (t.ue()) {
                  const e = this.TE.jt();
                  if (null !== e && !e.isEqual(t.field)) throw new R(w.INVALID_ARGUMENT, "Invalid query. All where filters with an inequality (<, <=, >, or >=) must be on the same field. But you have" + ` inequality filters on '${e.toString()}'` + ` and '${t.field.toString()}'`);
                  const s = this.TE.Kt();
                  null !== s && this.gE(t.field, s);
              } else if (n || i) {
                  // You can have at most 1 disjunctive filter and 1 array filter. Check if
                  // the new filter conflicts with an existing one.
                  let r = null;
                  if (n && (r = this.TE.ce(s)), null === r && i && (r = this.TE.ce(e)), null != r) 
                  // We special case when it's a duplicate op to give a slightly clearer error message.
                  throw r === t.op ? new R(w.INVALID_ARGUMENT, "Invalid query. You cannot use more than one " + `'${t.op.toString()}' filter.`) : new R(w.INVALID_ARGUMENT, `Invalid query. You cannot use '${t.op.toString()}' filters ` + `with '${r.toString()}' filters.`);
              }
          }
      }
      RE(t) {
          if (null === this.TE.Kt()) {
              // This is the first order by. It must match any inequality.
              const e = this.TE.jt();
              null !== e && this.gE(e, t.field);
          }
      }
      gE(t, e) {
          if (!e.isEqual(t)) throw new R(w.INVALID_ARGUMENT, "Invalid query. You have a where filter with an inequality " + `(<, <=, >, or >=) on field '${t.toString()}' ` + `and so you must also use '${t.toString()}' ` + "as your first Query.orderBy(), but your first Query.orderBy() " + `is on field '${e.toString()}' instead.`);
      }
  }
  
  class sr {
      constructor(t, e, s, i) {
          this.nE = t, this.pE = e, this.yE = s, this.hE = i, this.bE = null, this.vE = null, 
          this.metadata = new Xn(s.hasPendingWrites, s.fromCache);
      }
      get docs() {
          const t = [];
          return this.forEach(e => t.push(e)), t;
      }
      get empty() {
          return this.yE.docs.B();
      }
      get size() {
          return this.yE.docs.size;
      }
      forEach(t, e) {
          Ii("QuerySnapshot.forEach", arguments, 1, 2), wi("QuerySnapshot.forEach", "function", 1, t), 
          this.yE.docs.forEach(s => {
              t.call(e, this.SE(s));
          });
      }
      get query() {
          return new er(this.pE, this.nE, this.hE);
      }
      docChanges(t) {
          t && (vi("QuerySnapshot.docChanges", t, [ "includeMetadataChanges" ]), Ai("QuerySnapshot.docChanges", "boolean", "includeMetadataChanges", t.includeMetadataChanges));
          const e = !(!t || !t.includeMetadataChanges);
          if (e && this.yE.hs) throw new R(w.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");
          return this.bE && this.vE === e || (this.bE = 
          /**
   * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot.
   *
   * Exported for testing.
   */
          function(t, e, s, i) {
              if (s.ss.B()) {
                  // Special case the first snapshot because index calculation is easy and
                  // fast
                  let e, n = 0;
                  return s.docChanges.map(r => {
                      const h = new tr(t, r.doc.key, r.doc, s.fromCache, s.ns.has(r.doc.key), i);
                      return e = r.doc, {
                          type: "added",
                          doc: h,
                          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 = s.ss;
                  return s.docChanges.filter(t => e || 3 /* Metadata */ !== t.type).map(e => {
                      const r = new tr(t, e.doc.key, e.doc, s.fromCache, s.ns.has(e.doc.key), i);
                      let h = -1, o = -1;
                      return 0 /* Added */ !== e.type && (h = n.indexOf(e.doc.key), n = n.delete(e.doc.key)), 
                      1 /* Removed */ !== e.type && (n = n.add(e.doc), o = n.indexOf(e.doc.key)), {
                          type: ar(e.type),
                          doc: r,
                          oldIndex: h,
                          newIndex: o
                      };
                  });
              }
          }(this.nE, e, this.yE, this.hE), this.vE = e), this.bE;
      }
      /** Check the equality. The call can be very expensive. */    isEqual(t) {
          if (!(t instanceof sr)) throw Si("isEqual", "QuerySnapshot", 1, t);
          return this.nE === t.nE && this.pE.isEqual(t.pE) && this.yE.isEqual(t.yE) && this.hE === t.hE;
      }
      SE(t) {
          return new tr(this.nE, t.key, t, this.metadata.fromCache, this.yE.ns.has(t.key), this.hE);
      }
  }
  
  class ir extends er {
      constructor(t, e, s) {
          if (super(bt.Wt(t), e, s), this.DE = t, t.length % 2 != 1) throw new R(w.INVALID_ARGUMENT, "Invalid collection reference. Collection references must have an odd number of segments, but " + `${t.j()} has ${t.length}`);
      }
      get id() {
          return this.TE.path.O();
      }
      get parent() {
          const t = this.TE.path.M();
          return t.B() ? null : new Jn(new C(t), this.firestore);
      }
      get path() {
          return this.TE.path.j();
      }
      doc(t) {
          if (Ii("CollectionReference.doc", arguments, 0, 1), 
          // We allow omission of 'pathString' but explicitly prohibit passing in both
          // 'undefined' and 'null'.
          0 === arguments.length && (t = De.cn()), wi("CollectionReference.doc", "non-empty string", 1, t), 
          "" === t) throw new R(w.INVALID_ARGUMENT, "Document path must be a non-empty string");
          const e = v.K(t);
          return Jn.sE(this.TE.path.child(e), this.firestore, this.hE);
      }
      add(t) {
          Ti("CollectionReference.add", arguments, 1), wi("CollectionReference.add", "object", 1, this.hE ? this.hE.toFirestore(t) : t);
          const e = this.doc();
          return e.set(t).then(() => e);
      }
      withConverter(t) {
          return new ir(this.DE, this.firestore, t);
      }
  }
  
  function nr(t, e) {
      if (void 0 === e) return {
          merge: !1
      };
      if (vi(t, e, [ "merge", "mergeFields" ]), Ai(t, "boolean", "merge", e.merge), Pi(t, "mergeFields", "a string or a FieldPath", e.mergeFields, t => "string" == typeof t || t instanceof Mi), 
      void 0 !== e.mergeFields && void 0 !== e.merge) throw new R(w.INVALID_ARGUMENT, `Invalid options passed to function ${t}(): You cannot specify both "merge" ` + 'and "mergeFields".');
      return e;
  }
  
  function rr(t, e) {
      return void 0 === e ? {} : (vi(t, e, [ "serverTimestamps" ]), Vi(t, 0, "serverTimestamps", e.serverTimestamps, [ "estimate", "previous", "none" ]), 
      e);
  }
  
  function hr(t, e) {
      Ri(t, "object", 1, e), e && (vi(t, e, [ "source" ]), Vi(t, 0, "source", e.source, [ "default", "server", "cache" ]));
  }
  
  function or(t, e, s) {
      if (e instanceof Jn) {
          if (e.firestore !== s) throw new R(w.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance.");
          return e;
      }
      throw Si(t, "DocumentReference", 1, e);
  }
  
  function ar(t) {
      switch (t) {
        case 0 /* Added */ :
          return "added";
  
        case 2 /* Modified */ :
        case 3 /* Metadata */ :
          return "modified";
  
        case 1 /* Removed */ :
          return "removed";
  
        default:
          return be();
      }
  }
  
  /**
   * 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.
   */ function ur(t, e, s) {
      let i;
      return t ? (i = t.toFirestore(e), s = "toFirestore() in " + s) : i = e, [ i, s ];
  }
  
  function cr(t, e) {
      function s() {
          let t = "This constructor is private.";
          throw e && (t += " ", t += e), new R(w.INVALID_ARGUMENT, t);
      }
      // Make sure instanceof checks work and all methods are exposed on the public
      // constructor
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
      return s.prototype = t.prototype, 
      // Copy any static methods/members
      Object.assign(s, t), 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.
   */
  // Public instance that disallows construction at runtime. Note that this still
  // allows instanceof checks.
  const _r = cr(zn, "Use firebase.firestore() instead."), lr = cr(Hn, "Use firebase.firestore().runTransaction() instead."), dr = cr(Yn, "Use firebase.firestore().batch() instead."), fr = cr(Jn, "Use firebase.firestore().doc() instead."), Tr = cr(Zn), Er = cr(tr), Ir = cr(er), wr = cr(sr), Rr = cr(ir, "Use firebase.firestore().collection() instead."), mr = cr(class {
      static delete() {
          return fi("FieldValue.delete", arguments), new xi;
      }
      static serverTimestamp() {
          return fi("FieldValue.serverTimestamp", arguments), new Bi;
      }
      static arrayUnion(...t) {
          // NOTE: We don't actually parse the data until it's used in set() or
          // update() since we need access to the Firestore instance.
          return Ei("FieldValue.arrayUnion", arguments, 1), new qi(t);
      }
      static arrayRemove(...t) {
          // NOTE: We don't actually parse the data until it's used in set() or
          // update() since we need access to the Firestore instance.
          return Ei("FieldValue.arrayRemove", arguments, 1), new Ui(t);
      }
      static increment(t) {
          return wi("FieldValue.increment", "number", 1, t), Ti("FieldValue.increment", arguments, 1), 
          new Qi(t);
      }
      isEqual(t) {
          return this === t;
      }
  }, "Use FieldValue.<field>() instead."), Ar = cr(ki, "Use Blob.fromUint8Array() or Blob.fromBase64String() instead."), Pr = {
      Firestore: _r,
      GeoPoint: Wi,
      Timestamp: p,
      Blob: Ar,
      Transaction: lr,
      WriteBatch: dr,
      DocumentReference: fr,
      DocumentSnapshot: Tr,
      Query: Ir,
      QueryDocumentSnapshot: Er,
      QuerySnapshot: wr,
      CollectionReference: Rr,
      FieldPath: Mi,
      FieldValue: mr,
      setLogLevel: zn.setLogLevel,
      CACHE_SIZE_UNLIMITED: Kn
  };
  
  /**
   * @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 Vr {
      x_(t) {
          // No-op.
      }
      Ro() {
          // 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 gr {
      constructor() {
          this.CE = () => this.FE(), this.NE = () => this.$E(), this.kE = [], this.ME();
      }
      x_(t) {
          this.kE.push(t);
      }
      Ro() {
          window.removeEventListener("online", this.CE), window.removeEventListener("offline", this.NE);
      }
      ME() {
          window.addEventListener("online", this.CE), window.addEventListener("offline", this.NE);
      }
      FE() {
          ge("ConnectivityMonitor", "Network connectivity changed: AVAILABLE");
          for (const t of this.kE) t(0 /* AVAILABLE */);
      }
      $E() {
          ge("ConnectivityMonitor", "Network connectivity changed: UNAVAILABLE");
          for (const t of this.kE) 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 jh() {
          return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;
      }
  }
  
  /**
   * @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 pr {
      constructor(t) {
          this.LE = t.LE, this.OE = t.OE;
      }
      t_(t) {
          this.xE = t;
      }
      Hc(t) {
          this.BE = t;
      }
      onMessage(t) {
          this.qE = t;
      }
      close() {
          this.OE();
      }
      send(t) {
          this.LE(t);
      }
      UE() {
          this.xE();
      }
      QE(t) {
          this.BE(t);
      }
      WE(t) {
          this.qE(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.
   */ const yr = {
      BatchGetDocuments: "batchGet",
      Commit: "commit"
  }, br = "gl-js/ fire/" + E;
  
  class vr {
      constructor(t) {
          this.ii = t.ii;
          const e = t.ssl ? "https" : "http";
          this.jE = e + "://" + t.host, this.forceLongPolling = t.forceLongPolling;
      }
      /**
       * Modifies the headers for a request, adding any authorization token if
       * present and any additional headers for the request.
       */    KE(t, e) {
          if (e) for (const s in e.o) e.o.hasOwnProperty(s) && (t[s] = e.o[s]);
          t["X-Goog-Api-Client"] = br;
      }
      l_(t, e, s) {
          const i = this.GE(t);
          return new Promise((n, r) => {
              const h = new _;
              h.listenOnce(l.COMPLETE, () => {
                  try {
                      switch (h.getLastErrorCode()) {
                        case d.NO_ERROR:
                          const e = h.getResponseJson();
                          ge("Connection", "XHR received:", JSON.stringify(e)), n(e);
                          break;
  
                        case d.TIMEOUT:
                          ge("Connection", 'RPC "' + t + '" timed out'), r(new R(w.DEADLINE_EXCEEDED, "Request time out"));
                          break;
  
                        case d.HTTP_ERROR:
                          const s = h.getStatus();
                          if (ge("Connection", 'RPC "' + t + '" failed with status:', s, "response text:", h.getResponseText()), 
                          s > 0) {
                              const t = h.getResponseJson().error;
                              if (t && t.status && t.message) {
                                  const e = function(t) {
                                      const e = t.toLowerCase().replace("_", "-");
                                      return Object.values(w).indexOf(e) >= 0 ? e : w.UNKNOWN;
                                  }(t.status);
                                  r(new R(e, t.message));
                              } else r(new R(w.UNKNOWN, "Server responded with status " + h.getStatus()));
                          } else 
                          // If we received an HTTP_ERROR but there's no status code,
                          // it's most probably a connection issue
                          ge("Connection", 'RPC "' + t + '" failed'), r(new R(w.UNAVAILABLE, "Connection failed."));
                          break;
  
                        default:
                          be();
                      }
                  } finally {
                      ge("Connection", 'RPC "' + t + '" completed.');
                  }
              });
              // The database field is already encoded in URL. Specifying it again in
              // the body is not necessary in production, and will cause duplicate field
              // errors in the Firestore Emulator. Let's remove it.
              const o = Object.assign({}, e);
              delete o.database;
              const a = JSON.stringify(o);
              ge("Connection", "XHR sending: ", i + " " + a);
              // 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.
              const u = {
                  "Content-Type": "text/plain"
              };
              this.KE(u, s), h.send(i, "POST", a, u, 15);
          });
      }
      d_(t, e, s) {
          // The REST API automatically aggregates all of the streamed results, so we
          // can just use the normal invoke() method.
          return this.l_(t, e, s);
      }
      e_(t, e) {
          const s = [ this.jE, "/", "google.firestore.v1.Firestore", "/", t, "/channel" ], i = f(), c = {
              // 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.ii.projectId}/databases/${this.ii.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
          };
          this.KE(c.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() || r() || h() || o() || a() || u() || (c.httpHeadersOverwriteParam = "$httpHeaders");
          const _ = s.join("");
          ge("Connection", "Creating WebChannel: " + _ + " " + c);
          const l = i.createWebChannel(_, c);
          // 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 d = !1, E = !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 I = new pr({
              LE: t => {
                  E ? ge("Connection", "Not sending because WebChannel is closed:", t) : (d || (ge("Connection", "Opening WebChannel transport."), 
                  l.open(), d = !0), ge("Connection", "WebChannel sending:", t), l.send(t));
              },
              OE: () => l.close()
          }), m = (t, e) => {
              // TODO(dimond): closure typing seems broken because WebChannel does
              // not implement goog.events.Listenable
              l.listen(t, t => {
                  try {
                      e(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 m(T.EventType.OPEN, () => {
              E || ge("Connection", "WebChannel transport opened.");
          }), m(T.EventType.CLOSE, () => {
              E || (E = !0, ge("Connection", "WebChannel transport closed"), I.QE());
          }), m(T.EventType.ERROR, t => {
              E || (E = !0, ge("Connection", "WebChannel transport errored:", t), I.QE(new R(w.UNAVAILABLE, "The operation could not be completed")));
          }), m(T.EventType.MESSAGE, t => {
              var e;
              if (!E) {
                  const s = t.data[0];
                  ve(!!s);
                  // 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 i = s, n = i.error || (null === (e = i[0]) || void 0 === e ? void 0 : e.error);
                  if (n) {
                      ge("Connection", "WebChannel received error:", n);
                      // error.status will be a string like 'OK' or 'NOT_FOUND'.
                      const t = n.status;
                      let e = function(t) {
                          // lookup by string
                          // eslint-disable-next-line @typescript-eslint/no-explicit-any
                          const e = Ot[t];
                          if (void 0 !== e) return qt(e);
                      }(t), s = n.message;
                      void 0 === e && (e = w.INTERNAL, s = "Unknown error status: " + t + " with message " + n.message), 
                      // Mark closed so no further events are propagated
                      E = !0, I.QE(new R(e, s)), l.close();
                  } else ge("Connection", "WebChannel received:", s), I.WE(s);
              }
          }), 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.
              I.UE();
          }, 0), I;
      }
      // visible for testing
      GE(t) {
          const e = yr[t];
          return this.jE + "/v1/projects/" + this.ii.projectId + "/databases/" + this.ii.database + "/documents:" + 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.
   */
  // Implements the Platform API for browsers and some browser-like environments
  // (including ReactNative).
  /**
   * @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.
   */
  /**
   * Registers the main Firestore build with the components framework.
   * Persistence can be enabled via `firebase.firestore().enablePersistence()`.
   */
  function Sr(t) {
      !
      /**
   * Configures Firestore as part of the Firebase SDK by calling registerService.
   *
   * @param firebase The FirebaseNamespace to register Firestore with
   * @param firestoreFactory A factory function that returns a new Firestore
   *    instance.
   */
      function(t, e) {
          t.INTERNAL.registerComponent(new c("firestore", t => {
              const s = t.getProvider("app").getImmediate();
              return e(s, t.getProvider("auth-internal"));
          }, "PUBLIC" /* PUBLIC */).setServiceProps(Object.assign({}, Pr)));
      }(t, (t, e) => new zn(t, e, new qn)), t.registerVersion("@firebase/firestore", "1.14.5");
  }
  
  /**
   * @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 code needs to run before Firestore is used. This can be achieved in
   * several ways:
   *   1) Through the JSCompiler compiling this code and then (automatically)
   *      executing it before exporting the Firestore symbols.
   *   2) Through importing this module first in a Firestore main module
   */
  me.an(new class {
      constructor() {
          this.oc = "undefined" != typeof atob;
      }
      get document() {
          // `document` is not always available, e.g. in ReactNative and WebWorkers.
          // eslint-disable-next-line no-restricted-globals
          return "undefined" != typeof document ? document : null;
      }
      get window() {
          // `window` is not always available, e.g. in ReactNative and WebWorkers.
          // eslint-disable-next-line no-restricted-globals
          return "undefined" != typeof window ? window : null;
      }
      pT(t) {
          return Promise.resolve(new vr(t));
      }
      RT() {
          return gr.jh() ? new gr : new Vr;
      }
      yc(t) {
          return new we(t, {
              hi: !0
          });
      }
      un(t) {
          return JSON.stringify(t);
      }
      atob(t) {
          return atob(t);
      }
      btoa(t) {
          return btoa(t);
      }
      _n(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), s = new Uint8Array(t);
          if (e) e.getRandomValues(s); else 
          // Falls back to Math.random
          for (let e = 0; e < t; e++) s[e] = Math.floor(256 * Math.random());
          return s;
      }
  }), Sr(t);
  
  export { Sr as __PRIVATE_registerFirestore };
  //# sourceMappingURL=index.esm2017.js.map
  