GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

21200 lines
867 KiB

2 months ago
  1. import { __extends as t, __awaiter as e, __generator as n, __spreadArray as r } from "tslib";
  2. import { SDK_VERSION as i, _registerComponent as o, registerVersion as u, _getProvider, getApp as a, _removeServiceInstance as s } from "@firebase/app";
  3. import { Component as c } from "@firebase/component";
  4. import { Logger as l, LogLevel as h } from "@firebase/logger";
  5. import { FirebaseError as f, getUA as d, isSafari as p, getModularInstance as y, isIndexedDBAvailable as v, createMockUserToken as m, deepEqual as g, getDefaultEmulatorHostnameAndPort as w } from "@firebase/util";
  6. import { XhrIo as b, EventType as I, ErrorCode as T, createWebChannelTransport as E, getStatEventTarget as S, FetchXmlHttpFactory as _, WebChannel as D, Event as x, Stat as A } from "@firebase/webchannel-wrapper";
  7. var C = "@firebase/firestore", N = /** @class */ function() {
  8. function t(t) {
  9. this.uid = t;
  10. }
  11. return t.prototype.isAuthenticated = function() {
  12. return null != this.uid;
  13. },
  14. /**
  15. * Returns a key representing this user, suitable for inclusion in a
  16. * dictionary.
  17. */
  18. t.prototype.toKey = function() {
  19. return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
  20. }, t.prototype.isEqual = function(t) {
  21. return t.uid === this.uid;
  22. }, t;
  23. }();
  24. /**
  25. * @license
  26. * Copyright 2017 Google LLC
  27. *
  28. * Licensed under the Apache License, Version 2.0 (the "License");
  29. * you may not use this file except in compliance with the License.
  30. * You may obtain a copy of the License at
  31. *
  32. * http://www.apache.org/licenses/LICENSE-2.0
  33. *
  34. * Unless required by applicable law or agreed to in writing, software
  35. * distributed under the License is distributed on an "AS IS" BASIS,
  36. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37. * See the License for the specific language governing permissions and
  38. * limitations under the License.
  39. */
  40. /**
  41. * Simple wrapper around a nullable UID. Mostly exists to make code more
  42. * readable.
  43. */
  44. /** A user with a null UID. */ N.UNAUTHENTICATED = new N(null),
  45. // TODO(mikelehen): Look into getting a proper uid-equivalent for
  46. // non-FirebaseAuth providers.
  47. N.GOOGLE_CREDENTIALS = new N("google-credentials-uid"), N.FIRST_PARTY = new N("first-party-uid"),
  48. N.MOCK_USER = new N("mock-user");
  49. /**
  50. * @license
  51. * Copyright 2017 Google LLC
  52. *
  53. * Licensed under the Apache License, Version 2.0 (the "License");
  54. * you may not use this file except in compliance with the License.
  55. * You may obtain a copy of the License at
  56. *
  57. * http://www.apache.org/licenses/LICENSE-2.0
  58. *
  59. * Unless required by applicable law or agreed to in writing, software
  60. * distributed under the License is distributed on an "AS IS" BASIS,
  61. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  62. * See the License for the specific language governing permissions and
  63. * limitations under the License.
  64. */
  65. var k = "9.16.0", F = new l("@firebase/firestore");
  66. /**
  67. * @license
  68. * Copyright 2017 Google LLC
  69. *
  70. * Licensed under the Apache License, Version 2.0 (the "License");
  71. * you may not use this file except in compliance with the License.
  72. * You may obtain a copy of the License at
  73. *
  74. * http://www.apache.org/licenses/LICENSE-2.0
  75. *
  76. * Unless required by applicable law or agreed to in writing, software
  77. * distributed under the License is distributed on an "AS IS" BASIS,
  78. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  79. * See the License for the specific language governing permissions and
  80. * limitations under the License.
  81. */
  82. // Helper methods are needed because variables can't be exported as read/write
  83. function O() {
  84. return F.logLevel;
  85. }
  86. /**
  87. * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
  88. *
  89. * @param logLevel - The verbosity you set for activity and error logging. Can
  90. * be any of the following values:
  91. *
  92. * <ul>
  93. * <li>`debug` for the most verbose logging level, primarily for
  94. * debugging.</li>
  95. * <li>`error` to log errors only.</li>
  96. * <li><code>`silent` to turn off logging.</li>
  97. * </ul>
  98. */ function R(t) {
  99. F.setLogLevel(t);
  100. }
  101. function V(t) {
  102. for (var e = [], n = 1; n < arguments.length; n++) e[n - 1] = arguments[n];
  103. if (F.logLevel <= h.DEBUG) {
  104. var i = e.map(P);
  105. F.debug.apply(F, r([ "Firestore (".concat(k, "): ").concat(t) ], i, !1));
  106. }
  107. }
  108. function M(t) {
  109. for (var e = [], n = 1; n < arguments.length; n++) e[n - 1] = arguments[n];
  110. if (F.logLevel <= h.ERROR) {
  111. var i = e.map(P);
  112. F.error.apply(F, r([ "Firestore (".concat(k, "): ").concat(t) ], i, !1));
  113. }
  114. }
  115. /**
  116. * @internal
  117. */ function L(t) {
  118. for (var e = [], n = 1; n < arguments.length; n++) e[n - 1] = arguments[n];
  119. if (F.logLevel <= h.WARN) {
  120. var i = e.map(P);
  121. F.warn.apply(F, r([ "Firestore (".concat(k, "): ").concat(t) ], i, !1));
  122. }
  123. }
  124. /**
  125. * Converts an additional log parameter to a string representation.
  126. */ function P(t) {
  127. if ("string" == typeof t) return t;
  128. try {
  129. return e = t, JSON.stringify(e);
  130. } catch (e) {
  131. // Converting to JSON failed, just log the object directly
  132. return t;
  133. }
  134. /**
  135. * @license
  136. * Copyright 2020 Google LLC
  137. *
  138. * Licensed under the Apache License, Version 2.0 (the "License");
  139. * you may not use this file except in compliance with the License.
  140. * You may obtain a copy of the License at
  141. *
  142. * http://www.apache.org/licenses/LICENSE-2.0
  143. *
  144. * Unless required by applicable law or agreed to in writing, software
  145. * distributed under the License is distributed on an "AS IS" BASIS,
  146. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  147. * See the License for the specific language governing permissions and
  148. * limitations under the License.
  149. */
  150. /** Formats an object as a JSON string, suitable for logging. */ var e;
  151. }
  152. /**
  153. * @license
  154. * Copyright 2017 Google LLC
  155. *
  156. * Licensed under the Apache License, Version 2.0 (the "License");
  157. * you may not use this file except in compliance with the License.
  158. * You may obtain a copy of the License at
  159. *
  160. * http://www.apache.org/licenses/LICENSE-2.0
  161. *
  162. * Unless required by applicable law or agreed to in writing, software
  163. * distributed under the License is distributed on an "AS IS" BASIS,
  164. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  165. * See the License for the specific language governing permissions and
  166. * limitations under the License.
  167. */
  168. /**
  169. * Unconditionally fails, throwing an Error with the given message.
  170. * Messages are stripped in production builds.
  171. *
  172. * Returns `never` and can be used in expressions:
  173. * @example
  174. * let futureVar = fail('not implemented yet');
  175. */ function q(t) {
  176. void 0 === t && (t = "Unexpected state");
  177. // Log the failure in addition to throw an exception, just in case the
  178. // exception is swallowed.
  179. var e = "FIRESTORE (".concat(k, ") INTERNAL ASSERTION FAILED: ") + t;
  180. // NOTE: We don't use FirestoreError here because these are internal failures
  181. // that cannot be handled by the user. (Also it would create a circular
  182. // dependency between the error and assert modules which doesn't work.)
  183. throw M(e), new Error(e)
  184. /**
  185. * Fails if the given assertion condition is false, throwing an Error with the
  186. * given message if it did.
  187. *
  188. * Messages are stripped in production builds.
  189. */;
  190. }
  191. function U(t, e) {
  192. t || q();
  193. }
  194. /**
  195. * Fails if the given assertion condition is false, throwing an Error with the
  196. * given message if it did.
  197. *
  198. * The code of callsites invoking this function are stripped out in production
  199. * builds. Any side-effects of code within the debugAssert() invocation will not
  200. * happen in this case.
  201. *
  202. * @internal
  203. */ function B(t, e) {
  204. t || q();
  205. }
  206. /**
  207. * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
  208. * instance of `T` before casting.
  209. */ function G(t,
  210. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  211. e) {
  212. return t;
  213. }
  214. /**
  215. * @license
  216. * Copyright 2017 Google LLC
  217. *
  218. * Licensed under the Apache License, Version 2.0 (the "License");
  219. * you may not use this file except in compliance with the License.
  220. * You may obtain a copy of the License at
  221. *
  222. * http://www.apache.org/licenses/LICENSE-2.0
  223. *
  224. * Unless required by applicable law or agreed to in writing, software
  225. * distributed under the License is distributed on an "AS IS" BASIS,
  226. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  227. * See the License for the specific language governing permissions and
  228. * limitations under the License.
  229. */ var K = {
  230. // Causes are copied from:
  231. // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  232. /** Not an error; returned on success. */
  233. OK: "ok",
  234. /** The operation was cancelled (typically by the caller). */
  235. CANCELLED: "cancelled",
  236. /** Unknown error or an error from a different error domain. */
  237. UNKNOWN: "unknown",
  238. /**
  239. * Client specified an invalid argument. Note that this differs from
  240. * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
  241. * problematic regardless of the state of the system (e.g., a malformed file
  242. * name).
  243. */
  244. INVALID_ARGUMENT: "invalid-argument",
  245. /**
  246. * Deadline expired before operation could complete. For operations that
  247. * change the state of the system, this error may be returned even if the
  248. * operation has completed successfully. For example, a successful response
  249. * from a server could have been delayed long enough for the deadline to
  250. * expire.
  251. */
  252. DEADLINE_EXCEEDED: "deadline-exceeded",
  253. /** Some requested entity (e.g., file or directory) was not found. */
  254. NOT_FOUND: "not-found",
  255. /**
  256. * Some entity that we attempted to create (e.g., file or directory) already
  257. * exists.
  258. */
  259. ALREADY_EXISTS: "already-exists",
  260. /**
  261. * The caller does not have permission to execute the specified operation.
  262. * PERMISSION_DENIED must not be used for rejections caused by exhausting
  263. * some resource (use RESOURCE_EXHAUSTED instead for those errors).
  264. * PERMISSION_DENIED must not be used if the caller can not be identified
  265. * (use UNAUTHENTICATED instead for those errors).
  266. */
  267. PERMISSION_DENIED: "permission-denied",
  268. /**
  269. * The request does not have valid authentication credentials for the
  270. * operation.
  271. */
  272. UNAUTHENTICATED: "unauthenticated",
  273. /**
  274. * Some resource has been exhausted, perhaps a per-user quota, or perhaps the
  275. * entire file system is out of space.
  276. */
  277. RESOURCE_EXHAUSTED: "resource-exhausted",
  278. /**
  279. * Operation was rejected because the system is not in a state required for
  280. * the operation's execution. For example, directory to be deleted may be
  281. * non-empty, an rmdir operation is applied to a non-directory, etc.
  282. *
  283. * A litmus test that may help a service implementor in deciding
  284. * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
  285. * (a) Use UNAVAILABLE if the client can retry just the failing call.
  286. * (b) Use ABORTED if the client should retry at a higher-level
  287. * (e.g., restarting a read-modify-write sequence).
  288. * (c) Use FAILED_PRECONDITION if the client should not retry until
  289. * the system state has been explicitly fixed. E.g., if an "rmdir"
  290. * fails because the directory is non-empty, FAILED_PRECONDITION
  291. * should be returned since the client should not retry unless
  292. * they have first fixed up the directory by deleting files from it.
  293. * (d) Use FAILED_PRECONDITION if the client performs conditional
  294. * REST Get/Update/Delete on a resource and the resource on the
  295. * server does not match the condition. E.g., conflicting
  296. * read-modify-write on the same resource.
  297. */
  298. FAILED_PRECONDITION: "failed-precondition",
  299. /**
  300. * The operation was aborted, typically due to a concurrency issue like
  301. * sequencer check failures, transaction aborts, etc.
  302. *
  303. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  304. * and UNAVAILABLE.
  305. */
  306. ABORTED: "aborted",
  307. /**
  308. * Operation was attempted past the valid range. E.g., seeking or reading
  309. * past end of file.
  310. *
  311. * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
  312. * if the system state changes. For example, a 32-bit file system will
  313. * generate INVALID_ARGUMENT if asked to read at an offset that is not in the
  314. * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
  315. * an offset past the current file size.
  316. *
  317. * There is a fair bit of overlap between FAILED_PRECONDITION and
  318. * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
  319. * when it applies so that callers who are iterating through a space can
  320. * easily look for an OUT_OF_RANGE error to detect when they are done.
  321. */
  322. OUT_OF_RANGE: "out-of-range",
  323. /** Operation is not implemented or not supported/enabled in this service. */
  324. UNIMPLEMENTED: "unimplemented",
  325. /**
  326. * Internal errors. Means some invariants expected by underlying System has
  327. * been broken. If you see one of these errors, Something is very broken.
  328. */
  329. INTERNAL: "internal",
  330. /**
  331. * The service is currently unavailable. This is a most likely a transient
  332. * condition and may be corrected by retrying with a backoff.
  333. *
  334. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  335. * and UNAVAILABLE.
  336. */
  337. UNAVAILABLE: "unavailable",
  338. /** Unrecoverable data loss or corruption. */
  339. DATA_LOSS: "data-loss"
  340. }, j = /** @class */ function(e) {
  341. /** @hideconstructor */
  342. function n(
  343. /**
  344. * The backend error code associated with this error.
  345. */
  346. t,
  347. /**
  348. * A custom error description.
  349. */
  350. n) {
  351. var r = this;
  352. return (r = e.call(this, t, n) || this).code = t, r.message = n,
  353. // HACK: We write a toString property directly because Error is not a real
  354. // class and so inheritance does not work correctly. We could alternatively
  355. // do the same "back-door inheritance" trick that FirebaseError does.
  356. r.toString = function() {
  357. return "".concat(r.name, ": [code=").concat(r.code, "]: ").concat(r.message);
  358. }, r;
  359. }
  360. return t(n, e), n;
  361. }(f), Q = function() {
  362. var t = this;
  363. this.promise = new Promise((function(e, n) {
  364. t.resolve = e, t.reject = n;
  365. }));
  366. }, z = function(t, e) {
  367. this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", "Bearer ".concat(t));
  368. }, W = /** @class */ function() {
  369. function t() {}
  370. return t.prototype.getToken = function() {
  371. return Promise.resolve(null);
  372. }, t.prototype.invalidateToken = function() {}, t.prototype.start = function(t, e) {
  373. // Fire with initial user.
  374. t.enqueueRetryable((function() {
  375. return e(N.UNAUTHENTICATED);
  376. }));
  377. }, t.prototype.shutdown = function() {}, t;
  378. }(), H = /** @class */ function() {
  379. function t(t) {
  380. this.token = t,
  381. /**
  382. * Stores the listener registered with setChangeListener()
  383. * This isn't actually necessary since the UID never changes, but we use this
  384. * to verify the listen contract is adhered to in tests.
  385. */
  386. this.changeListener = null;
  387. }
  388. return t.prototype.getToken = function() {
  389. return Promise.resolve(this.token);
  390. }, t.prototype.invalidateToken = function() {}, t.prototype.start = function(t, e) {
  391. var n = this;
  392. this.changeListener = e,
  393. // Fire with initial user.
  394. t.enqueueRetryable((function() {
  395. return e(n.token.user);
  396. }));
  397. }, t.prototype.shutdown = function() {
  398. this.changeListener = null;
  399. }, t;
  400. }(), Y = /** @class */ function() {
  401. function t(t) {
  402. this.t = t,
  403. /** Tracks the current User. */
  404. this.currentUser = N.UNAUTHENTICATED,
  405. /**
  406. * Counter used to detect if the token changed while a getToken request was
  407. * outstanding.
  408. */
  409. this.i = 0, this.forceRefresh = !1, this.auth = null;
  410. }
  411. return t.prototype.start = function(t, r) {
  412. var i = this, o = this.i, u = function(t) {
  413. return i.i !== o ? (o = i.i, r(t)) : Promise.resolve();
  414. }, a = new Q;
  415. this.o = function() {
  416. i.i++, i.currentUser = i.u(), a.resolve(), a = new Q, t.enqueueRetryable((function() {
  417. return u(i.currentUser);
  418. }));
  419. };
  420. var s = function() {
  421. var r = a;
  422. t.enqueueRetryable((function() {
  423. return e(i, void 0, void 0, (function() {
  424. return n(this, (function(t) {
  425. switch (t.label) {
  426. case 0:
  427. return [ 4 /*yield*/ , r.promise ];
  428. case 1:
  429. return t.sent(), [ 4 /*yield*/ , u(this.currentUser) ];
  430. case 2:
  431. return t.sent(), [ 2 /*return*/ ];
  432. }
  433. }));
  434. }));
  435. }));
  436. }, c = function(t) {
  437. V("FirebaseAuthCredentialsProvider", "Auth detected"), i.auth = t, i.auth.addAuthTokenListener(i.o),
  438. s();
  439. };
  440. this.t.onInit((function(t) {
  441. return c(t);
  442. })),
  443. // Our users can initialize Auth right after Firestore, so we give it
  444. // a chance to register itself with the component framework before we
  445. // determine whether to start up in unauthenticated mode.
  446. setTimeout((function() {
  447. if (!i.auth) {
  448. var t = i.t.getImmediate({
  449. optional: !0
  450. });
  451. t ? c(t) : (
  452. // If auth is still not available, proceed with `null` user
  453. V("FirebaseAuthCredentialsProvider", "Auth not yet detected"), a.resolve(), a = new Q);
  454. }
  455. }), 0), s();
  456. }, t.prototype.getToken = function() {
  457. var t = this, e = this.i, n = this.forceRefresh;
  458. // Take note of the current value of the tokenCounter so that this method
  459. // can fail (with an ABORTED error) if there is a token change while the
  460. // request is outstanding.
  461. return this.forceRefresh = !1, this.auth ? this.auth.getToken(n).then((function(n) {
  462. // Cancel the request since the token changed while the request was
  463. // outstanding so the response is potentially for a previous user (which
  464. // user, we can't be sure).
  465. return t.i !== e ? (V("FirebaseAuthCredentialsProvider", "getToken aborted due to token change."),
  466. t.getToken()) : n ? (U("string" == typeof n.accessToken), new z(n.accessToken, t.currentUser)) : null;
  467. })) : Promise.resolve(null);
  468. }, t.prototype.invalidateToken = function() {
  469. this.forceRefresh = !0;
  470. }, t.prototype.shutdown = function() {
  471. this.auth && this.auth.removeAuthTokenListener(this.o);
  472. },
  473. // Auth.getUid() can return null even with a user logged in. It is because
  474. // getUid() is synchronous, but the auth code populating Uid is asynchronous.
  475. // This method should only be called in the AuthTokenListener callback
  476. // to guarantee to get the actual user.
  477. t.prototype.u = function() {
  478. var t = this.auth && this.auth.getUid();
  479. return U(null === t || "string" == typeof t), new N(t);
  480. }, t;
  481. }(), X = /** @class */ function() {
  482. function t(t, e, n, r) {
  483. this.h = t, this.l = e, this.m = n, this.g = r, this.type = "FirstParty", this.user = N.FIRST_PARTY,
  484. this.p = new Map
  485. /** Gets an authorization token, using a provided factory function, or falling back to First Party GAPI. */;
  486. }
  487. return t.prototype.I = function() {
  488. return this.g ? this.g() : (
  489. // Make sure this really is a Gapi client.
  490. U(!("object" != typeof this.h || null === this.h || !this.h.auth || !this.h.auth.getAuthHeaderValueForFirstParty)),
  491. this.h.auth.getAuthHeaderValueForFirstParty([]));
  492. }, Object.defineProperty(t.prototype, "headers", {
  493. get: function() {
  494. this.p.set("X-Goog-AuthUser", this.l);
  495. // Use array notation to prevent minification
  496. var t = this.I();
  497. return t && this.p.set("Authorization", t), this.m && this.p.set("X-Goog-Iam-Authorization-Token", this.m),
  498. this.p;
  499. },
  500. enumerable: !1,
  501. configurable: !0
  502. }), t;
  503. }(), Z = /** @class */ function() {
  504. function t(t, e, n, r) {
  505. this.h = t, this.l = e, this.m = n, this.g = r;
  506. }
  507. return t.prototype.getToken = function() {
  508. return Promise.resolve(new X(this.h, this.l, this.m, this.g));
  509. }, t.prototype.start = function(t, e) {
  510. // Fire with initial uid.
  511. t.enqueueRetryable((function() {
  512. return e(N.FIRST_PARTY);
  513. }));
  514. }, t.prototype.shutdown = function() {}, t.prototype.invalidateToken = function() {},
  515. t;
  516. }(), J = function(t) {
  517. this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value);
  518. }, $ = /** @class */ function() {
  519. function t(t) {
  520. this.T = t, this.forceRefresh = !1, this.appCheck = null, this.A = null;
  521. }
  522. return t.prototype.start = function(t, e) {
  523. var n = this, r = function(t) {
  524. null != t.error && V("FirebaseAppCheckTokenProvider", "Error getting App Check token; using placeholder token instead. Error: ".concat(t.error.message));
  525. var r = t.token !== n.A;
  526. return n.A = t.token, V("FirebaseAppCheckTokenProvider", "Received ".concat(r ? "new" : "existing", " token.")),
  527. r ? e(t.token) : Promise.resolve();
  528. };
  529. this.o = function(e) {
  530. t.enqueueRetryable((function() {
  531. return r(e);
  532. }));
  533. };
  534. var i = function(t) {
  535. V("FirebaseAppCheckTokenProvider", "AppCheck detected"), n.appCheck = t, n.appCheck.addTokenListener(n.o);
  536. };
  537. this.T.onInit((function(t) {
  538. return i(t);
  539. })),
  540. // Our users can initialize AppCheck after Firestore, so we give it
  541. // a chance to register itself with the component framework.
  542. setTimeout((function() {
  543. if (!n.appCheck) {
  544. var t = n.T.getImmediate({
  545. optional: !0
  546. });
  547. t ? i(t) :
  548. // If AppCheck is still not available, proceed without it.
  549. V("FirebaseAppCheckTokenProvider", "AppCheck not yet detected");
  550. }
  551. }), 0);
  552. }, t.prototype.getToken = function() {
  553. var t = this, e = this.forceRefresh;
  554. return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(e).then((function(e) {
  555. return e ? (U("string" == typeof e.token), t.A = e.token, new J(e.token)) : null;
  556. })) : Promise.resolve(null);
  557. }, t.prototype.invalidateToken = function() {
  558. this.forceRefresh = !0;
  559. }, t.prototype.shutdown = function() {
  560. this.appCheck && this.appCheck.removeTokenListener(this.o);
  561. }, t;
  562. }(), tt = /** @class */ function() {
  563. function t() {}
  564. return t.prototype.getToken = function() {
  565. return Promise.resolve(new J(""));
  566. }, t.prototype.invalidateToken = function() {}, t.prototype.start = function(t, e) {},
  567. t.prototype.shutdown = function() {}, t;
  568. }();
  569. /** An error returned by a Firestore operation. */
  570. /**
  571. * Builds a CredentialsProvider depending on the type of
  572. * the credentials passed in.
  573. */
  574. /**
  575. * @license
  576. * Copyright 2020 Google LLC
  577. *
  578. * Licensed under the Apache License, Version 2.0 (the "License");
  579. * you may not use this file except in compliance with the License.
  580. * You may obtain a copy of the License at
  581. *
  582. * http://www.apache.org/licenses/LICENSE-2.0
  583. *
  584. * Unless required by applicable law or agreed to in writing, software
  585. * distributed under the License is distributed on an "AS IS" BASIS,
  586. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  587. * See the License for the specific language governing permissions and
  588. * limitations under the License.
  589. */
  590. /**
  591. * Generates `nBytes` of random bytes.
  592. *
  593. * If `nBytes < 0` , an error will be thrown.
  594. */
  595. function et(t) {
  596. // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.
  597. var e =
  598. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  599. "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);
  600. if (e && "function" == typeof e.getRandomValues) e.getRandomValues(n); else
  601. // Falls back to Math.random
  602. for (var r = 0; r < t; r++) n[r] = Math.floor(256 * Math.random());
  603. return n;
  604. }
  605. /**
  606. * @license
  607. * Copyright 2017 Google LLC
  608. *
  609. * Licensed under the Apache License, Version 2.0 (the "License");
  610. * you may not use this file except in compliance with the License.
  611. * You may obtain a copy of the License at
  612. *
  613. * http://www.apache.org/licenses/LICENSE-2.0
  614. *
  615. * Unless required by applicable law or agreed to in writing, software
  616. * distributed under the License is distributed on an "AS IS" BASIS,
  617. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  618. * See the License for the specific language governing permissions and
  619. * limitations under the License.
  620. */ var nt = /** @class */ function() {
  621. function t() {}
  622. return t.R = function() {
  623. for (
  624. // Alphanumeric characters
  625. var t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length, n = ""
  626. // The largest byte value that is a multiple of `char.length`.
  627. ; n.length < 20; ) for (var r = et(40), i = 0; i < r.length; ++i)
  628. // Only accept values that are [0, maxMultiple), this ensures they can
  629. // be evenly mapped to indices of `chars` via a modulo operation.
  630. n.length < 20 && r[i] < e && (n += t.charAt(r[i] % t.length));
  631. return n;
  632. }, t;
  633. }();
  634. function rt(t, e) {
  635. return t < e ? -1 : t > e ? 1 : 0;
  636. }
  637. /** Helper to compare arrays using isEqual(). */ function it(t, e, n) {
  638. return t.length === e.length && t.every((function(t, r) {
  639. return n(t, e[r]);
  640. }));
  641. }
  642. /**
  643. * Returns the immediate lexicographically-following string. This is useful to
  644. * construct an inclusive range for indexeddb iterators.
  645. */ function ot(t) {
  646. // Return the input string, with an additional NUL byte appended.
  647. return t + "\0";
  648. }
  649. /**
  650. * @license
  651. * Copyright 2017 Google LLC
  652. *
  653. * Licensed under the Apache License, Version 2.0 (the "License");
  654. * you may not use this file except in compliance with the License.
  655. * You may obtain a copy of the License at
  656. *
  657. * http://www.apache.org/licenses/LICENSE-2.0
  658. *
  659. * Unless required by applicable law or agreed to in writing, software
  660. * distributed under the License is distributed on an "AS IS" BASIS,
  661. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  662. * See the License for the specific language governing permissions and
  663. * limitations under the License.
  664. */
  665. // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
  666. /**
  667. * A `Timestamp` represents a point in time independent of any time zone or
  668. * calendar, represented as seconds and fractions of seconds at nanosecond
  669. * resolution in UTC Epoch time.
  670. *
  671. * It is encoded using the Proleptic Gregorian Calendar which extends the
  672. * Gregorian calendar backwards to year one. It is encoded assuming all minutes
  673. * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
  674. * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
  675. * 9999-12-31T23:59:59.999999999Z.
  676. *
  677. * For examples and further specifications, refer to the
  678. * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
  679. */ var ut = /** @class */ function() {
  680. /**
  681. * Creates a new timestamp.
  682. *
  683. * @param seconds - The number of seconds of UTC time since Unix epoch
  684. * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  685. * 9999-12-31T23:59:59Z inclusive.
  686. * @param nanoseconds - The non-negative fractions of a second at nanosecond
  687. * resolution. Negative second values with fractions must still have
  688. * non-negative nanoseconds values that count forward in time. Must be
  689. * from 0 to 999,999,999 inclusive.
  690. */
  691. function t(
  692. /**
  693. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  694. */
  695. t,
  696. /**
  697. * The fractions of a second at nanosecond resolution.*
  698. */
  699. e) {
  700. if (this.seconds = t, this.nanoseconds = e, e < 0) throw new j(K.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
  701. if (e >= 1e9) throw new j(K.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
  702. if (t < -62135596800) throw new j(K.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
  703. // This will break in the year 10,000.
  704. if (t >= 253402300800) throw new j(K.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
  705. }
  706. /**
  707. * Creates a new timestamp with the current date, with millisecond precision.
  708. *
  709. * @returns a new timestamp representing the current date.
  710. */ return t.now = function() {
  711. return t.fromMillis(Date.now());
  712. },
  713. /**
  714. * Creates a new timestamp from the given date.
  715. *
  716. * @param date - The date to initialize the `Timestamp` from.
  717. * @returns A new `Timestamp` representing the same point in time as the given
  718. * date.
  719. */
  720. t.fromDate = function(e) {
  721. return t.fromMillis(e.getTime());
  722. },
  723. /**
  724. * Creates a new timestamp from the given number of milliseconds.
  725. *
  726. * @param milliseconds - Number of milliseconds since Unix epoch
  727. * 1970-01-01T00:00:00Z.
  728. * @returns A new `Timestamp` representing the same point in time as the given
  729. * number of milliseconds.
  730. */
  731. t.fromMillis = function(e) {
  732. var n = Math.floor(e / 1e3);
  733. return new t(n, Math.floor(1e6 * (e - 1e3 * n)));
  734. },
  735. /**
  736. * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
  737. * causes a loss of precision since `Date` objects only support millisecond
  738. * precision.
  739. *
  740. * @returns JavaScript `Date` object representing the same point in time as
  741. * this `Timestamp`, with millisecond precision.
  742. */
  743. t.prototype.toDate = function() {
  744. return new Date(this.toMillis());
  745. },
  746. /**
  747. * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
  748. * epoch). This operation causes a loss of precision.
  749. *
  750. * @returns The point in time corresponding to this timestamp, represented as
  751. * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
  752. */
  753. t.prototype.toMillis = function() {
  754. return 1e3 * this.seconds + this.nanoseconds / 1e6;
  755. }, t.prototype._compareTo = function(t) {
  756. return this.seconds === t.seconds ? rt(this.nanoseconds, t.nanoseconds) : rt(this.seconds, t.seconds);
  757. },
  758. /**
  759. * Returns true if this `Timestamp` is equal to the provided one.
  760. *
  761. * @param other - The `Timestamp` to compare against.
  762. * @returns true if this `Timestamp` is equal to the provided one.
  763. */
  764. t.prototype.isEqual = function(t) {
  765. return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;
  766. },
  767. /** Returns a textual representation of this `Timestamp`. */ t.prototype.toString = function() {
  768. return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
  769. },
  770. /** Returns a JSON-serializable representation of this `Timestamp`. */ t.prototype.toJSON = function() {
  771. return {
  772. seconds: this.seconds,
  773. nanoseconds: this.nanoseconds
  774. };
  775. },
  776. /**
  777. * Converts this object to a primitive string, which allows `Timestamp` objects
  778. * to be compared using the `>`, `<=`, `>=` and `>` operators.
  779. */
  780. t.prototype.valueOf = function() {
  781. // This method returns a string of the form <seconds>.<nanoseconds> where
  782. // <seconds> is translated to have a non-negative value and both <seconds>
  783. // and <nanoseconds> are left-padded with zeroes to be a consistent length.
  784. // Strings with this format then have a lexiographical ordering that matches
  785. // the expected ordering. The <seconds> translation is done to avoid having
  786. // a leading negative sign (i.e. a leading '-' character) in its string
  787. // representation, which would affect its lexiographical ordering.
  788. var t = this.seconds - -62135596800;
  789. // Note: Up to 12 decimal digits are required to represent all valid
  790. // 'seconds' values.
  791. return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0");
  792. }, t;
  793. }(), at = /** @class */ function() {
  794. function t(t) {
  795. this.timestamp = t;
  796. }
  797. return t.fromTimestamp = function(e) {
  798. return new t(e);
  799. }, t.min = function() {
  800. return new t(new ut(0, 0));
  801. }, t.max = function() {
  802. return new t(new ut(253402300799, 999999999));
  803. }, t.prototype.compareTo = function(t) {
  804. return this.timestamp._compareTo(t.timestamp);
  805. }, t.prototype.isEqual = function(t) {
  806. return this.timestamp.isEqual(t.timestamp);
  807. },
  808. /** Returns a number representation of the version for use in spec tests. */ t.prototype.toMicroseconds = function() {
  809. // Convert to microseconds.
  810. return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
  811. }, t.prototype.toString = function() {
  812. return "SnapshotVersion(" + this.timestamp.toString() + ")";
  813. }, t.prototype.toTimestamp = function() {
  814. return this.timestamp;
  815. }, t;
  816. }(), st = /** @class */ function() {
  817. function t(t, e, n) {
  818. void 0 === e ? e = 0 : e > t.length && q(), void 0 === n ? n = t.length - e : n > t.length - e && q(),
  819. this.segments = t, this.offset = e, this.len = n;
  820. }
  821. return Object.defineProperty(t.prototype, "length", {
  822. get: function() {
  823. return this.len;
  824. },
  825. enumerable: !1,
  826. configurable: !0
  827. }), t.prototype.isEqual = function(e) {
  828. return 0 === t.comparator(this, e);
  829. }, t.prototype.child = function(e) {
  830. var n = this.segments.slice(this.offset, this.limit());
  831. return e instanceof t ? e.forEach((function(t) {
  832. n.push(t);
  833. })) : n.push(e), this.construct(n);
  834. },
  835. /** The index of one past the last segment of the path. */ t.prototype.limit = function() {
  836. return this.offset + this.length;
  837. }, t.prototype.popFirst = function(t) {
  838. return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);
  839. }, t.prototype.popLast = function() {
  840. return this.construct(this.segments, this.offset, this.length - 1);
  841. }, t.prototype.firstSegment = function() {
  842. return this.segments[this.offset];
  843. }, t.prototype.lastSegment = function() {
  844. return this.get(this.length - 1);
  845. }, t.prototype.get = function(t) {
  846. return this.segments[this.offset + t];
  847. }, t.prototype.isEmpty = function() {
  848. return 0 === this.length;
  849. }, t.prototype.isPrefixOf = function(t) {
  850. if (t.length < this.length) return !1;
  851. for (var e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  852. return !0;
  853. }, t.prototype.isImmediateParentOf = function(t) {
  854. if (this.length + 1 !== t.length) return !1;
  855. for (var e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  856. return !0;
  857. }, t.prototype.forEach = function(t) {
  858. for (var e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);
  859. }, t.prototype.toArray = function() {
  860. return this.segments.slice(this.offset, this.limit());
  861. }, t.comparator = function(t, e) {
  862. for (var n = Math.min(t.length, e.length), r = 0; r < n; r++) {
  863. var i = t.get(r), o = e.get(r);
  864. if (i < o) return -1;
  865. if (i > o) return 1;
  866. }
  867. return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;
  868. }, t;
  869. }(), ct = /** @class */ function(e) {
  870. function n() {
  871. return null !== e && e.apply(this, arguments) || this;
  872. }
  873. return t(n, e), n.prototype.construct = function(t, e, r) {
  874. return new n(t, e, r);
  875. }, n.prototype.canonicalString = function() {
  876. // NOTE: The client is ignorant of any path segments containing escape
  877. // sequences (e.g. __id123__) and just passes them through raw (they exist
  878. // for legacy reasons and should not be used frequently).
  879. return this.toArray().join("/");
  880. }, n.prototype.toString = function() {
  881. return this.canonicalString();
  882. },
  883. /**
  884. * Creates a resource path from the given slash-delimited string. If multiple
  885. * arguments are provided, all components are combined. Leading and trailing
  886. * slashes from all components are ignored.
  887. */
  888. n.fromString = function() {
  889. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  890. // NOTE: The client is ignorant of any path segments containing escape
  891. // sequences (e.g. __id123__) and just passes them through raw (they exist
  892. // for legacy reasons and should not be used frequently).
  893. for (var r = [], i = 0, o = t; i < o.length; i++) {
  894. var u = o[i];
  895. if (u.indexOf("//") >= 0) throw new j(K.INVALID_ARGUMENT, "Invalid segment (".concat(u, "). Paths must not contain // in them."));
  896. // Strip leading and traling slashed.
  897. r.push.apply(r, u.split("/").filter((function(t) {
  898. return t.length > 0;
  899. })));
  900. }
  901. return new n(r);
  902. }, n.emptyPath = function() {
  903. return new n([]);
  904. }, n;
  905. }(st), lt = /^[_a-zA-Z][_a-zA-Z0-9]*$/, ht = /** @class */ function(e) {
  906. function n() {
  907. return null !== e && e.apply(this, arguments) || this;
  908. }
  909. return t(n, e), n.prototype.construct = function(t, e, r) {
  910. return new n(t, e, r);
  911. },
  912. /**
  913. * Returns true if the string could be used as a segment in a field path
  914. * without escaping.
  915. */
  916. n.isValidIdentifier = function(t) {
  917. return lt.test(t);
  918. }, n.prototype.canonicalString = function() {
  919. return this.toArray().map((function(t) {
  920. return t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), n.isValidIdentifier(t) || (t = "`" + t + "`"),
  921. t;
  922. })).join(".");
  923. }, n.prototype.toString = function() {
  924. return this.canonicalString();
  925. },
  926. /**
  927. * Returns true if this field references the key of a document.
  928. */
  929. n.prototype.isKeyField = function() {
  930. return 1 === this.length && "__name__" === this.get(0);
  931. },
  932. /**
  933. * The field designating the key of a document.
  934. */
  935. n.keyField = function() {
  936. return new n([ "__name__" ]);
  937. },
  938. /**
  939. * Parses a field string from the given server-formatted string.
  940. *
  941. * - Splitting the empty string is not allowed (for now at least).
  942. * - Empty segments within the string (e.g. if there are two consecutive
  943. * separators) are not allowed.
  944. *
  945. * TODO(b/37244157): we should make this more strict. Right now, it allows
  946. * non-identifier path components, even if they aren't escaped.
  947. */
  948. n.fromServerFormat = function(t) {
  949. for (var e = [], r = "", i = 0, o = function() {
  950. if (0 === r.length) throw new j(K.INVALID_ARGUMENT, "Invalid field path (".concat(t, "). Paths must not be empty, begin with '.', end with '.', or contain '..'"));
  951. e.push(r), r = "";
  952. }, u = !1; i < t.length; ) {
  953. var a = t[i];
  954. if ("\\" === a) {
  955. if (i + 1 === t.length) throw new j(K.INVALID_ARGUMENT, "Path has trailing escape character: " + t);
  956. var s = t[i + 1];
  957. if ("\\" !== s && "." !== s && "`" !== s) throw new j(K.INVALID_ARGUMENT, "Path has invalid escape sequence: " + t);
  958. r += s, i += 2;
  959. } else "`" === a ? (u = !u, i++) : "." !== a || u ? (r += a, i++) : (o(), i++);
  960. }
  961. if (o(), u) throw new j(K.INVALID_ARGUMENT, "Unterminated ` in path: " + t);
  962. return new n(e);
  963. }, n.emptyPath = function() {
  964. return new n([]);
  965. }, n;
  966. }(st), ft = /** @class */ function() {
  967. function t(t) {
  968. this.path = t;
  969. }
  970. return t.fromPath = function(e) {
  971. return new t(ct.fromString(e));
  972. }, t.fromName = function(e) {
  973. return new t(ct.fromString(e).popFirst(5));
  974. }, t.empty = function() {
  975. return new t(ct.emptyPath());
  976. }, Object.defineProperty(t.prototype, "collectionGroup", {
  977. get: function() {
  978. return this.path.popLast().lastSegment();
  979. },
  980. enumerable: !1,
  981. configurable: !0
  982. }),
  983. /** Returns true if the document is in the specified collectionId. */ t.prototype.hasCollectionId = function(t) {
  984. return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;
  985. },
  986. /** Returns the collection group (i.e. the name of the parent collection) for this key. */ t.prototype.getCollectionGroup = function() {
  987. return this.path.get(this.path.length - 2);
  988. },
  989. /** Returns the fully qualified path to the parent collection. */ t.prototype.getCollectionPath = function() {
  990. return this.path.popLast();
  991. }, t.prototype.isEqual = function(t) {
  992. return null !== t && 0 === ct.comparator(this.path, t.path);
  993. }, t.prototype.toString = function() {
  994. return this.path.toString();
  995. }, t.comparator = function(t, e) {
  996. return ct.comparator(t.path, e.path);
  997. }, t.isDocumentKey = function(t) {
  998. return t.length % 2 == 0;
  999. },
  1000. /**
  1001. * Creates and returns a new document key with the given segments.
  1002. *
  1003. * @param segments - The segments of the path to the document
  1004. * @returns A new instance of DocumentKey
  1005. */
  1006. t.fromSegments = function(e) {
  1007. return new t(new ct(e.slice()));
  1008. }, t;
  1009. }(), dt = function(
  1010. /**
  1011. * The index ID. Returns -1 if the index ID is not available (e.g. the index
  1012. * has not yet been persisted).
  1013. */
  1014. t,
  1015. /** The collection ID this index applies to. */
  1016. e,
  1017. /** The field segments for this index. */
  1018. n,
  1019. /** Shows how up-to-date the index is for the current user. */
  1020. r) {
  1021. this.indexId = t, this.collectionGroup = e, this.fields = n, this.indexState = r;
  1022. };
  1023. /**
  1024. * @license
  1025. * Copyright 2017 Google LLC
  1026. *
  1027. * Licensed under the Apache License, Version 2.0 (the "License");
  1028. * you may not use this file except in compliance with the License.
  1029. * You may obtain a copy of the License at
  1030. *
  1031. * http://www.apache.org/licenses/LICENSE-2.0
  1032. *
  1033. * Unless required by applicable law or agreed to in writing, software
  1034. * distributed under the License is distributed on an "AS IS" BASIS,
  1035. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1036. * See the License for the specific language governing permissions and
  1037. * limitations under the License.
  1038. */
  1039. /**
  1040. * A version of a document in Firestore. This corresponds to the version
  1041. * timestamp, such as update_time or read_time.
  1042. */
  1043. /** An ID for an index that has not yet been added to persistence. */
  1044. /** Returns the ArrayContains/ArrayContainsAny segment for this index. */
  1045. function pt(t) {
  1046. return t.fields.find((function(t) {
  1047. return 2 /* IndexKind.CONTAINS */ === t.kind;
  1048. }));
  1049. }
  1050. /** Returns all directional (ascending/descending) segments for this index. */ function yt(t) {
  1051. return t.fields.filter((function(t) {
  1052. return 2 /* IndexKind.CONTAINS */ !== t.kind;
  1053. }));
  1054. }
  1055. /**
  1056. * Returns the order of the document key component for the given index.
  1057. *
  1058. * PORTING NOTE: This is only used in the Web IndexedDb implementation.
  1059. */
  1060. /**
  1061. * Compares indexes by collection group and segments. Ignores update time and
  1062. * index ID.
  1063. */ function vt(t, e) {
  1064. var n = rt(t.collectionGroup, e.collectionGroup);
  1065. if (0 !== n) return n;
  1066. for (var r = 0; r < Math.min(t.fields.length, e.fields.length); ++r) if (0 !== (n = gt(t.fields[r], e.fields[r]))) return n;
  1067. return rt(t.fields.length, e.fields.length);
  1068. }
  1069. /** Returns a debug representation of the field index */ dt.UNKNOWN_ID = -1;
  1070. /** An index component consisting of field path and index type. */
  1071. var mt = function(
  1072. /** The field path of the component. */
  1073. t,
  1074. /** The fields sorting order. */
  1075. e) {
  1076. this.fieldPath = t, this.kind = e;
  1077. };
  1078. function gt(t, e) {
  1079. var n = ht.comparator(t.fieldPath, e.fieldPath);
  1080. return 0 !== n ? n : rt(t.kind, e.kind);
  1081. }
  1082. /**
  1083. * Stores the "high water mark" that indicates how updated the Index is for the
  1084. * current user.
  1085. */ var wt = /** @class */ function() {
  1086. function t(
  1087. /**
  1088. * Indicates when the index was last updated (relative to other indexes).
  1089. */
  1090. t,
  1091. /** The the latest indexed read time, document and batch id. */
  1092. e) {
  1093. this.sequenceNumber = t, this.offset = e
  1094. /** The state of an index that has not yet been backfilled. */;
  1095. }
  1096. return t.empty = function() {
  1097. return new t(0, Tt.min());
  1098. }, t;
  1099. }();
  1100. /**
  1101. * Creates an offset that matches all documents with a read time higher than
  1102. * `readTime`.
  1103. */ function bt(t, e) {
  1104. // We want to create an offset that matches all documents with a read time
  1105. // greater than the provided read time. To do so, we technically need to
  1106. // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use
  1107. // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use
  1108. // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches
  1109. // all valid document IDs.
  1110. var n = t.toTimestamp().seconds, r = t.toTimestamp().nanoseconds + 1, i = at.fromTimestamp(1e9 === r ? new ut(n + 1, 0) : new ut(n, r));
  1111. return new Tt(i, ft.empty(), e);
  1112. }
  1113. /** Creates a new offset based on the provided document. */ function It(t) {
  1114. return new Tt(t.readTime, t.key, -1);
  1115. }
  1116. /**
  1117. * Stores the latest read time, document and batch ID that were processed for an
  1118. * index.
  1119. */ var Tt = /** @class */ function() {
  1120. function t(
  1121. /**
  1122. * The latest read time version that has been indexed by Firestore for this
  1123. * field index.
  1124. */
  1125. t,
  1126. /**
  1127. * The key of the last document that was indexed for this query. Use
  1128. * `DocumentKey.empty()` if no document has been indexed.
  1129. */
  1130. e,
  1131. /*
  1132. * The largest mutation batch id that's been processed by Firestore.
  1133. */
  1134. n) {
  1135. this.readTime = t, this.documentKey = e, this.largestBatchId = n
  1136. /** Returns an offset that sorts before all regular offsets. */;
  1137. }
  1138. return t.min = function() {
  1139. return new t(at.min(), ft.empty(), -1);
  1140. },
  1141. /** Returns an offset that sorts after all regular offsets. */ t.max = function() {
  1142. return new t(at.max(), ft.empty(), -1);
  1143. }, t;
  1144. }();
  1145. function Et(t, e) {
  1146. var n = t.readTime.compareTo(e.readTime);
  1147. return 0 !== n ? n : 0 !== (n = ft.comparator(t.documentKey, e.documentKey)) ? n : rt(t.largestBatchId, e.largestBatchId);
  1148. }
  1149. /**
  1150. * @license
  1151. * Copyright 2020 Google LLC
  1152. *
  1153. * Licensed under the Apache License, Version 2.0 (the "License");
  1154. * you may not use this file except in compliance with the License.
  1155. * You may obtain a copy of the License at
  1156. *
  1157. * http://www.apache.org/licenses/LICENSE-2.0
  1158. *
  1159. * Unless required by applicable law or agreed to in writing, software
  1160. * distributed under the License is distributed on an "AS IS" BASIS,
  1161. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1162. * See the License for the specific language governing permissions and
  1163. * limitations under the License.
  1164. */ var St = "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.", _t = /** @class */ function() {
  1165. function t() {
  1166. this.onCommittedListeners = [];
  1167. }
  1168. return t.prototype.addOnCommittedListener = function(t) {
  1169. this.onCommittedListeners.push(t);
  1170. }, t.prototype.raiseOnCommittedEvent = function() {
  1171. this.onCommittedListeners.forEach((function(t) {
  1172. return t();
  1173. }));
  1174. }, t;
  1175. }();
  1176. /**
  1177. * A base class representing a persistence transaction, encapsulating both the
  1178. * transaction's sequence numbers as well as a list of onCommitted listeners.
  1179. *
  1180. * When you call Persistence.runTransaction(), it will create a transaction and
  1181. * pass it to your callback. You then pass it to any method that operates
  1182. * on persistence.
  1183. */
  1184. /**
  1185. * @license
  1186. * Copyright 2017 Google LLC
  1187. *
  1188. * Licensed under the Apache License, Version 2.0 (the "License");
  1189. * you may not use this file except in compliance with the License.
  1190. * You may obtain a copy of the License at
  1191. *
  1192. * http://www.apache.org/licenses/LICENSE-2.0
  1193. *
  1194. * Unless required by applicable law or agreed to in writing, software
  1195. * distributed under the License is distributed on an "AS IS" BASIS,
  1196. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1197. * See the License for the specific language governing permissions and
  1198. * limitations under the License.
  1199. */
  1200. /**
  1201. * Verifies the error thrown by a LocalStore operation. If a LocalStore
  1202. * operation fails because the primary lease has been taken by another client,
  1203. * we ignore the error (the persistence layer will immediately call
  1204. * `applyPrimaryLease` to propagate the primary state change). All other errors
  1205. * are re-thrown.
  1206. *
  1207. * @param err - An error returned by a LocalStore operation.
  1208. * @returns A Promise that resolves after we recovered, or the original error.
  1209. */
  1210. function Dt(t) {
  1211. return e(this, void 0, void 0, (function() {
  1212. return n(this, (function(e) {
  1213. if (t.code !== K.FAILED_PRECONDITION || t.message !== St) throw t;
  1214. return V("LocalStore", "Unexpectedly lost primary lease"), [ 2 /*return*/ ];
  1215. }));
  1216. }));
  1217. }
  1218. /**
  1219. * @license
  1220. * Copyright 2017 Google LLC
  1221. *
  1222. * Licensed under the Apache License, Version 2.0 (the "License");
  1223. * you may not use this file except in compliance with the License.
  1224. * You may obtain a copy of the License at
  1225. *
  1226. * http://www.apache.org/licenses/LICENSE-2.0
  1227. *
  1228. * Unless required by applicable law or agreed to in writing, software
  1229. * distributed under the License is distributed on an "AS IS" BASIS,
  1230. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1231. * See the License for the specific language governing permissions and
  1232. * limitations under the License.
  1233. */
  1234. /**
  1235. * PersistencePromise is essentially a re-implementation of Promise except
  1236. * it has a .next() method instead of .then() and .next() and .catch() callbacks
  1237. * are executed synchronously when a PersistencePromise resolves rather than
  1238. * asynchronously (Promise implementations use setImmediate() or similar).
  1239. *
  1240. * This is necessary to interoperate with IndexedDB which will automatically
  1241. * commit transactions if control is returned to the event loop without
  1242. * synchronously initiating another operation on the transaction.
  1243. *
  1244. * NOTE: .then() and .catch() only allow a single consumer, unlike normal
  1245. * Promises.
  1246. */ var xt = /** @class */ function() {
  1247. function t(t) {
  1248. var e = this;
  1249. // NOTE: next/catchCallback will always point to our own wrapper functions,
  1250. // not the user's raw next() or catch() callbacks.
  1251. this.nextCallback = null, this.catchCallback = null,
  1252. // When the operation resolves, we'll set result or error and mark isDone.
  1253. this.result = void 0, this.error = void 0, this.isDone = !1,
  1254. // Set to true when .then() or .catch() are called and prevents additional
  1255. // chaining.
  1256. this.callbackAttached = !1, t((function(t) {
  1257. e.isDone = !0, e.result = t, e.nextCallback &&
  1258. // value should be defined unless T is Void, but we can't express
  1259. // that in the type system.
  1260. e.nextCallback(t);
  1261. }), (function(t) {
  1262. e.isDone = !0, e.error = t, e.catchCallback && e.catchCallback(t);
  1263. }));
  1264. }
  1265. return t.prototype.catch = function(t) {
  1266. return this.next(void 0, t);
  1267. }, t.prototype.next = function(e, n) {
  1268. var r = this;
  1269. return this.callbackAttached && q(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(n, this.error) : this.wrapSuccess(e, this.result) : new t((function(t, i) {
  1270. r.nextCallback = function(n) {
  1271. r.wrapSuccess(e, n).next(t, i);
  1272. }, r.catchCallback = function(e) {
  1273. r.wrapFailure(n, e).next(t, i);
  1274. };
  1275. }));
  1276. }, t.prototype.toPromise = function() {
  1277. var t = this;
  1278. return new Promise((function(e, n) {
  1279. t.next(e, n);
  1280. }));
  1281. }, t.prototype.wrapUserFunction = function(e) {
  1282. try {
  1283. var n = e();
  1284. return n instanceof t ? n : t.resolve(n);
  1285. } catch (e) {
  1286. return t.reject(e);
  1287. }
  1288. }, t.prototype.wrapSuccess = function(e, n) {
  1289. return e ? this.wrapUserFunction((function() {
  1290. return e(n);
  1291. })) : t.resolve(n);
  1292. }, t.prototype.wrapFailure = function(e, n) {
  1293. return e ? this.wrapUserFunction((function() {
  1294. return e(n);
  1295. })) : t.reject(n);
  1296. }, t.resolve = function(e) {
  1297. return new t((function(t, n) {
  1298. t(e);
  1299. }));
  1300. }, t.reject = function(e) {
  1301. return new t((function(t, n) {
  1302. n(e);
  1303. }));
  1304. }, t.waitFor = function(
  1305. // Accept all Promise types in waitFor().
  1306. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1307. e) {
  1308. return new t((function(t, n) {
  1309. var r = 0, i = 0, o = !1;
  1310. e.forEach((function(e) {
  1311. ++r, e.next((function() {
  1312. ++i, o && i === r && t();
  1313. }), (function(t) {
  1314. return n(t);
  1315. }));
  1316. })), o = !0, i === r && t();
  1317. }));
  1318. },
  1319. /**
  1320. * Given an array of predicate functions that asynchronously evaluate to a
  1321. * boolean, implements a short-circuiting `or` between the results. Predicates
  1322. * will be evaluated until one of them returns `true`, then stop. The final
  1323. * result will be whether any of them returned `true`.
  1324. */
  1325. t.or = function(e) {
  1326. for (var n = t.resolve(!1), r = function(e) {
  1327. n = n.next((function(n) {
  1328. return n ? t.resolve(n) : e();
  1329. }));
  1330. }, i = 0, o = e; i < o.length; i++) {
  1331. r(o[i]);
  1332. }
  1333. return n;
  1334. }, t.forEach = function(t, e) {
  1335. var n = this, r = [];
  1336. return t.forEach((function(t, i) {
  1337. r.push(e.call(n, t, i));
  1338. })), this.waitFor(r);
  1339. },
  1340. /**
  1341. * Concurrently map all array elements through asynchronous function.
  1342. */
  1343. t.mapArray = function(e, n) {
  1344. return new t((function(t, r) {
  1345. for (var i = e.length, o = new Array(i), u = 0, a = function(a) {
  1346. var s = a;
  1347. n(e[s]).next((function(e) {
  1348. o[s] = e, ++u === i && t(o);
  1349. }), (function(t) {
  1350. return r(t);
  1351. }));
  1352. }, s = 0; s < i; s++) a(s);
  1353. }));
  1354. },
  1355. /**
  1356. * An alternative to recursive PersistencePromise calls, that avoids
  1357. * potential memory problems from unbounded chains of promises.
  1358. *
  1359. * The `action` will be called repeatedly while `condition` is true.
  1360. */
  1361. t.doWhile = function(e, n) {
  1362. return new t((function(t, r) {
  1363. var i = function() {
  1364. !0 === e() ? n().next((function() {
  1365. i();
  1366. }), r) : t();
  1367. };
  1368. i();
  1369. }));
  1370. }, t;
  1371. }(), At = /** @class */ function() {
  1372. function t(t, e) {
  1373. var n = this;
  1374. this.action = t, this.transaction = e, this.aborted = !1,
  1375. /**
  1376. * A `Promise` that resolves with the result of the IndexedDb transaction.
  1377. */
  1378. this.P = new Q, this.transaction.oncomplete = function() {
  1379. n.P.resolve();
  1380. }, this.transaction.onabort = function() {
  1381. e.error ? n.P.reject(new kt(t, e.error)) : n.P.resolve();
  1382. }, this.transaction.onerror = function(e) {
  1383. var r = Mt(e.target.error);
  1384. n.P.reject(new kt(t, r));
  1385. };
  1386. }
  1387. return t.open = function(e, n, r, i) {
  1388. try {
  1389. return new t(n, e.transaction(i, r));
  1390. } catch (e) {
  1391. throw new kt(n, e);
  1392. }
  1393. }, Object.defineProperty(t.prototype, "v", {
  1394. get: function() {
  1395. return this.P.promise;
  1396. },
  1397. enumerable: !1,
  1398. configurable: !0
  1399. }), t.prototype.abort = function(t) {
  1400. t && this.P.reject(t), this.aborted || (V("SimpleDb", "Aborting transaction:", t ? t.message : "Client-initiated abort"),
  1401. this.aborted = !0, this.transaction.abort());
  1402. }, t.prototype.V = function() {
  1403. // If the browser supports V3 IndexedDB, we invoke commit() explicitly to
  1404. // speed up index DB processing if the event loop remains blocks.
  1405. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1406. var t = this.transaction;
  1407. this.aborted || "function" != typeof t.commit || t.commit();
  1408. },
  1409. /**
  1410. * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All
  1411. * operations performed on the SimpleDbStore happen within the context of this
  1412. * transaction and it cannot be used anymore once the transaction is
  1413. * completed.
  1414. *
  1415. * Note that we can't actually enforce that the KeyType and ValueType are
  1416. * correct, but they allow type safety through the rest of the consuming code.
  1417. */
  1418. t.prototype.store = function(t) {
  1419. var e = this.transaction.objectStore(t);
  1420. return new Ot(e);
  1421. }, t;
  1422. }(), Ct = /** @class */ function() {
  1423. /*
  1424. * Creates a new SimpleDb wrapper for IndexedDb database `name`.
  1425. *
  1426. * Note that `version` must not be a downgrade. IndexedDB does not support
  1427. * downgrading the schema version. We currently do not support any way to do
  1428. * versioning outside of IndexedDB's versioning mechanism, as only
  1429. * version-upgrade transactions are allowed to do things like create
  1430. * objectstores.
  1431. */
  1432. function t(e, n, r) {
  1433. this.name = e, this.version = n, this.S = r,
  1434. // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the
  1435. // bug we're checking for should exist in iOS >= 12.2 and < 13, but for
  1436. // whatever reason it's much harder to hit after 12.2 so we only proactively
  1437. // log on 12.2.
  1438. 12.2 === t.D(d()) && M("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.");
  1439. }
  1440. /** Deletes the specified database. */ return t.delete = function(t) {
  1441. return V("SimpleDb", "Removing database:", t), Rt(window.indexedDB.deleteDatabase(t)).toPromise();
  1442. },
  1443. /** Returns true if IndexedDB is available in the current environment. */ t.C = function() {
  1444. if (!v()) return !1;
  1445. if (t.N()) return !0;
  1446. // We extensively use indexed array values and compound keys,
  1447. // which IE and Edge do not support. However, they still have indexedDB
  1448. // defined on the window, so we need to check for them here and make sure
  1449. // to return that persistence is not enabled for those browsers.
  1450. // For tracking support of this feature, see here:
  1451. // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/
  1452. // Check the UA string to find out the browser.
  1453. var e = d(), n = t.D(e), r = 0 < n && n < 10, i = t.k(e), o = 0 < i && i < 4.5;
  1454. // IE 10
  1455. // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
  1456. // IE 11
  1457. // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
  1458. // Edge
  1459. // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,
  1460. // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
  1461. // iOS Safari: Disable for users running iOS version < 10.
  1462. return !(e.indexOf("MSIE ") > 0 || e.indexOf("Trident/") > 0 || e.indexOf("Edge/") > 0 || r || o);
  1463. },
  1464. /**
  1465. * Returns true if the backing IndexedDB store is the Node IndexedDBShim
  1466. * (see https://github.com/axemclion/IndexedDBShim).
  1467. */
  1468. t.N = function() {
  1469. var t;
  1470. return "undefined" != typeof process && "YES" === (null === (t = process.env) || void 0 === t ? void 0 : t.O);
  1471. },
  1472. /** Helper to get a typed SimpleDbStore from a transaction. */ t.M = function(t, e) {
  1473. return t.store(e);
  1474. },
  1475. // visible for testing
  1476. /** Parse User Agent to determine iOS version. Returns -1 if not found. */
  1477. t.D = function(t) {
  1478. var e = t.match(/i(?:phone|pad|pod) os ([\d_]+)/i), n = e ? e[1].split("_").slice(0, 2).join(".") : "-1";
  1479. return Number(n);
  1480. },
  1481. // visible for testing
  1482. /** Parse User Agent to determine Android version. Returns -1 if not found. */
  1483. t.k = function(t) {
  1484. var e = t.match(/Android ([\d.]+)/i), n = e ? e[1].split(".").slice(0, 2).join(".") : "-1";
  1485. return Number(n);
  1486. },
  1487. /**
  1488. * Opens the specified database, creating or upgrading it if necessary.
  1489. */
  1490. t.prototype.F = function(t) {
  1491. return e(this, void 0, void 0, (function() {
  1492. var e, r = this;
  1493. return n(this, (function(n) {
  1494. switch (n.label) {
  1495. case 0:
  1496. return this.db ? [ 3 /*break*/ , 2 ] : (V("SimpleDb", "Opening database:", this.name),
  1497. e = this, [ 4 /*yield*/ , new Promise((function(e, n) {
  1498. // TODO(mikelehen): Investigate browser compatibility.
  1499. // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
  1500. // suggests IE9 and older WebKit browsers handle upgrade
  1501. // differently. They expect setVersion, as described here:
  1502. // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion
  1503. var i = indexedDB.open(r.name, r.version);
  1504. i.onsuccess = function(t) {
  1505. var n = t.target.result;
  1506. e(n);
  1507. }, i.onblocked = function() {
  1508. n(new kt(t, "Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."));
  1509. }, i.onerror = function(e) {
  1510. var r = e.target.error;
  1511. "VersionError" === r.name ? n(new j(K.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.")) : "InvalidStateError" === r.name ? n(new j(K.FAILED_PRECONDITION, "Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: " + r)) : n(new kt(t, r));
  1512. }, i.onupgradeneeded = function(t) {
  1513. V("SimpleDb", 'Database "' + r.name + '" requires upgrade from version:', t.oldVersion);
  1514. var e = t.target.result;
  1515. r.S.$(e, i.transaction, t.oldVersion, r.version).next((function() {
  1516. V("SimpleDb", "Database upgrade to version " + r.version + " complete");
  1517. }));
  1518. };
  1519. })) ]);
  1520. case 1:
  1521. e.db = n.sent(), n.label = 2;
  1522. case 2:
  1523. return [ 2 /*return*/ , (this.B && (this.db.onversionchange = function(t) {
  1524. return r.B(t);
  1525. }), this.db) ];
  1526. }
  1527. }));
  1528. }));
  1529. }, t.prototype.L = function(t) {
  1530. this.B = t, this.db && (this.db.onversionchange = function(e) {
  1531. return t(e);
  1532. });
  1533. }, t.prototype.runTransaction = function(t, r, i, o) {
  1534. return e(this, void 0, void 0, (function() {
  1535. var e, u, a, s, c;
  1536. return n(this, (function(l) {
  1537. switch (l.label) {
  1538. case 0:
  1539. e = "readonly" === r, u = 0, a = function() {
  1540. var r, a, c, l, h, f;
  1541. return n(this, (function(n) {
  1542. switch (n.label) {
  1543. case 0:
  1544. ++u, n.label = 1;
  1545. case 1:
  1546. return n.trys.push([ 1, 4, , 5 ]), [ 4 /*yield*/ , s.F(t) ];
  1547. case 2:
  1548. // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to
  1549. // fire), but still return the original transactionFnResult back to the
  1550. // caller.
  1551. return s.db = n.sent(), r = At.open(s.db, t, e ? "readonly" : "readwrite", i), a = o(r).next((function(t) {
  1552. return r.V(), t;
  1553. })).catch((function(t) {
  1554. // Abort the transaction if there was an error.
  1555. return r.abort(t), xt.reject(t);
  1556. })).toPromise(), c = {}, a.catch((function() {})), [ 4 /*yield*/ , r.v ];
  1557. case 3:
  1558. return [ 2 /*return*/ , (c.value = (
  1559. // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to
  1560. // fire), but still return the original transactionFnResult back to the
  1561. // caller.
  1562. n.sent(), a), c) ];
  1563. case 4:
  1564. // TODO(schmidt-sebastian): We could probably be smarter about this and
  1565. // not retry exceptions that are likely unrecoverable (such as quota
  1566. // exceeded errors).
  1567. // Note: We cannot use an instanceof check for FirestoreException, since the
  1568. // exception is wrapped in a generic error by our async/await handling.
  1569. return l = n.sent(), f = "FirebaseError" !== (h = l).name && u < 3, V("SimpleDb", "Transaction failed with error:", h.message, "Retrying:", f),
  1570. s.close(), f ? [ 3 /*break*/ , 5 ] : [ 2 /*return*/ , {
  1571. value: Promise.reject(h)
  1572. } ];
  1573. case 5:
  1574. return [ 2 /*return*/ ];
  1575. }
  1576. }));
  1577. }, s = this, l.label = 1;
  1578. case 1:
  1579. return [ 5 /*yield**/ , a() ];
  1580. case 2:
  1581. if ("object" == typeof (c = l.sent())) return [ 2 /*return*/ , c.value ];
  1582. l.label = 3;
  1583. case 3:
  1584. return [ 3 /*break*/ , 1 ];
  1585. case 4:
  1586. return [ 2 /*return*/ ];
  1587. }
  1588. }));
  1589. }));
  1590. }, t.prototype.close = function() {
  1591. this.db && this.db.close(), this.db = void 0;
  1592. }, t;
  1593. }(), Nt = /** @class */ function() {
  1594. function t(t) {
  1595. this.q = t, this.U = !1, this.K = null;
  1596. }
  1597. return Object.defineProperty(t.prototype, "isDone", {
  1598. get: function() {
  1599. return this.U;
  1600. },
  1601. enumerable: !1,
  1602. configurable: !0
  1603. }), Object.defineProperty(t.prototype, "G", {
  1604. get: function() {
  1605. return this.K;
  1606. },
  1607. enumerable: !1,
  1608. configurable: !0
  1609. }), Object.defineProperty(t.prototype, "cursor", {
  1610. set: function(t) {
  1611. this.q = t;
  1612. },
  1613. enumerable: !1,
  1614. configurable: !0
  1615. }),
  1616. /**
  1617. * This function can be called to stop iteration at any point.
  1618. */
  1619. t.prototype.done = function() {
  1620. this.U = !0;
  1621. },
  1622. /**
  1623. * This function can be called to skip to that next key, which could be
  1624. * an index or a primary key.
  1625. */
  1626. t.prototype.j = function(t) {
  1627. this.K = t;
  1628. },
  1629. /**
  1630. * Delete the current cursor value from the object store.
  1631. *
  1632. * NOTE: You CANNOT do this with a keysOnly query.
  1633. */
  1634. t.prototype.delete = function() {
  1635. return Rt(this.q.delete());
  1636. }, t;
  1637. }(), kt = /** @class */ function(e) {
  1638. function n(t, n) {
  1639. var r = this;
  1640. return (r = e.call(this, K.UNAVAILABLE, "IndexedDB transaction '".concat(t, "' failed: ").concat(n)) || this).name = "IndexedDbTransactionError",
  1641. r;
  1642. }
  1643. return t(n, e), n;
  1644. }(j);
  1645. /**
  1646. * @license
  1647. * Copyright 2017 Google LLC
  1648. *
  1649. * Licensed under the Apache License, Version 2.0 (the "License");
  1650. * you may not use this file except in compliance with the License.
  1651. * You may obtain a copy of the License at
  1652. *
  1653. * http://www.apache.org/licenses/LICENSE-2.0
  1654. *
  1655. * Unless required by applicable law or agreed to in writing, software
  1656. * distributed under the License is distributed on an "AS IS" BASIS,
  1657. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1658. * See the License for the specific language governing permissions and
  1659. * limitations under the License.
  1660. */
  1661. // References to `window` are guarded by SimpleDb.isAvailable()
  1662. /* eslint-disable no-restricted-globals */
  1663. /**
  1664. * Wraps an IDBTransaction and exposes a store() method to get a handle to a
  1665. * specific object store.
  1666. */
  1667. /** Verifies whether `e` is an IndexedDbTransactionError. */ function Ft(t) {
  1668. // Use name equality, as instanceof checks on errors don't work with errors
  1669. // that wrap other errors.
  1670. return "IndexedDbTransactionError" === t.name;
  1671. }
  1672. /**
  1673. * A wrapper around an IDBObjectStore providing an API that:
  1674. *
  1675. * 1) Has generic KeyType / ValueType parameters to provide strongly-typed
  1676. * methods for acting against the object store.
  1677. * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every
  1678. * method return a PersistencePromise instead.
  1679. * 3) Provides a higher-level API to avoid needing to do excessive wrapping of
  1680. * intermediate IndexedDB types (IDBCursorWithValue, etc.)
  1681. */ var Ot = /** @class */ function() {
  1682. function t(t) {
  1683. this.store = t;
  1684. }
  1685. return t.prototype.put = function(t, e) {
  1686. var n;
  1687. return void 0 !== e ? (V("SimpleDb", "PUT", this.store.name, t, e), n = this.store.put(e, t)) : (V("SimpleDb", "PUT", this.store.name, "<auto-key>", t),
  1688. n = this.store.put(t)), Rt(n);
  1689. },
  1690. /**
  1691. * Adds a new value into an Object Store and returns the new key. Similar to
  1692. * IndexedDb's `add()`, this method will fail on primary key collisions.
  1693. *
  1694. * @param value - The object to write.
  1695. * @returns The key of the value to add.
  1696. */
  1697. t.prototype.add = function(t) {
  1698. return V("SimpleDb", "ADD", this.store.name, t, t), Rt(this.store.add(t));
  1699. },
  1700. /**
  1701. * Gets the object with the specified key from the specified store, or null
  1702. * if no object exists with the specified key.
  1703. *
  1704. * @key The key of the object to get.
  1705. * @returns The object with the specified key or null if no object exists.
  1706. */
  1707. t.prototype.get = function(t) {
  1708. var e = this;
  1709. // We're doing an unsafe cast to ValueType.
  1710. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1711. return Rt(this.store.get(t)).next((function(n) {
  1712. // Normalize nonexistence to null.
  1713. return void 0 === n && (n = null), V("SimpleDb", "GET", e.store.name, t, n), n;
  1714. }));
  1715. }, t.prototype.delete = function(t) {
  1716. return V("SimpleDb", "DELETE", this.store.name, t), Rt(this.store.delete(t));
  1717. },
  1718. /**
  1719. * If we ever need more of the count variants, we can add overloads. For now,
  1720. * all we need is to count everything in a store.
  1721. *
  1722. * Returns the number of rows in the store.
  1723. */
  1724. t.prototype.count = function() {
  1725. return V("SimpleDb", "COUNT", this.store.name), Rt(this.store.count());
  1726. }, t.prototype.W = function(t, e) {
  1727. var n = this.options(t, e);
  1728. // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly
  1729. // 20% faster. Unfortunately, getAll() does not support custom indices.
  1730. if (n.index || "function" != typeof this.store.getAll) {
  1731. var r = this.cursor(n), i = [];
  1732. return this.H(r, (function(t, e) {
  1733. i.push(e);
  1734. })).next((function() {
  1735. return i;
  1736. }));
  1737. }
  1738. var o = this.store.getAll(n.range);
  1739. return new xt((function(t, e) {
  1740. o.onerror = function(t) {
  1741. e(t.target.error);
  1742. }, o.onsuccess = function(e) {
  1743. t(e.target.result);
  1744. };
  1745. }));
  1746. },
  1747. /**
  1748. * Loads the first `count` elements from the provided index range. Loads all
  1749. * elements if no limit is provided.
  1750. */
  1751. t.prototype.J = function(t, e) {
  1752. var n = this.store.getAll(t, null === e ? void 0 : e);
  1753. return new xt((function(t, e) {
  1754. n.onerror = function(t) {
  1755. e(t.target.error);
  1756. }, n.onsuccess = function(e) {
  1757. t(e.target.result);
  1758. };
  1759. }));
  1760. }, t.prototype.Y = function(t, e) {
  1761. V("SimpleDb", "DELETE ALL", this.store.name);
  1762. var n = this.options(t, e);
  1763. n.X = !1;
  1764. var r = this.cursor(n);
  1765. return this.H(r, (function(t, e, n) {
  1766. return n.delete();
  1767. }));
  1768. }, t.prototype.Z = function(t, e) {
  1769. var n;
  1770. e ? n = t : (n = {}, e = t);
  1771. var r = this.cursor(n);
  1772. return this.H(r, e);
  1773. },
  1774. /**
  1775. * Iterates over a store, but waits for the given callback to complete for
  1776. * each entry before iterating the next entry. This allows the callback to do
  1777. * asynchronous work to determine if this iteration should continue.
  1778. *
  1779. * The provided callback should return `true` to continue iteration, and
  1780. * `false` otherwise.
  1781. */
  1782. t.prototype.tt = function(t) {
  1783. var e = this.cursor({});
  1784. return new xt((function(n, r) {
  1785. e.onerror = function(t) {
  1786. var e = Mt(t.target.error);
  1787. r(e);
  1788. }, e.onsuccess = function(e) {
  1789. var r = e.target.result;
  1790. r ? t(r.primaryKey, r.value).next((function(t) {
  1791. t ? r.continue() : n();
  1792. })) : n();
  1793. };
  1794. }));
  1795. }, t.prototype.H = function(t, e) {
  1796. var n = [];
  1797. return new xt((function(r, i) {
  1798. t.onerror = function(t) {
  1799. i(t.target.error);
  1800. }, t.onsuccess = function(t) {
  1801. var i = t.target.result;
  1802. if (i) {
  1803. var o = new Nt(i), u = e(i.primaryKey, i.value, o);
  1804. if (u instanceof xt) {
  1805. var a = u.catch((function(t) {
  1806. return o.done(), xt.reject(t);
  1807. }));
  1808. n.push(a);
  1809. }
  1810. o.isDone ? r() : null === o.G ? i.continue() : i.continue(o.G);
  1811. } else r();
  1812. };
  1813. })).next((function() {
  1814. return xt.waitFor(n);
  1815. }));
  1816. }, t.prototype.options = function(t, e) {
  1817. var n;
  1818. return void 0 !== t && ("string" == typeof t ? n = t : e = t), {
  1819. index: n,
  1820. range: e
  1821. };
  1822. }, t.prototype.cursor = function(t) {
  1823. var e = "next";
  1824. if (t.reverse && (e = "prev"), t.index) {
  1825. var n = this.store.index(t.index);
  1826. return t.X ? n.openKeyCursor(t.range, e) : n.openCursor(t.range, e);
  1827. }
  1828. return this.store.openCursor(t.range, e);
  1829. }, t;
  1830. }();
  1831. /**
  1832. * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror
  1833. * handlers to resolve / reject the PersistencePromise as appropriate.
  1834. */ function Rt(t) {
  1835. return new xt((function(e, n) {
  1836. t.onsuccess = function(t) {
  1837. var n = t.target.result;
  1838. e(n);
  1839. }, t.onerror = function(t) {
  1840. var e = Mt(t.target.error);
  1841. n(e);
  1842. };
  1843. }));
  1844. }
  1845. // Guard so we only report the error once.
  1846. var Vt = !1;
  1847. function Mt(t) {
  1848. var e = Ct.D(d());
  1849. if (e >= 12.2 && e < 13) {
  1850. var n = "An internal error was encountered in the Indexed Database server";
  1851. if (t.message.indexOf(n) >= 0) {
  1852. // Wrap error in a more descriptive one.
  1853. var r = new j("internal", "IOS_INDEXEDDB_BUG1: IndexedDb has thrown '".concat(n, "'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround."));
  1854. return Vt || (Vt = !0,
  1855. // Throw a global exception outside of this promise chain, for the user to
  1856. // potentially catch.
  1857. setTimeout((function() {
  1858. throw r;
  1859. }), 0)), r;
  1860. }
  1861. }
  1862. return t;
  1863. }
  1864. /** This class is responsible for the scheduling of Index Backfiller. */ var Lt = /** @class */ function() {
  1865. function t(t, e) {
  1866. this.asyncQueue = t, this.et = e, this.task = null;
  1867. }
  1868. return t.prototype.start = function() {
  1869. this.nt(15e3);
  1870. }, t.prototype.stop = function() {
  1871. this.task && (this.task.cancel(), this.task = null);
  1872. }, Object.defineProperty(t.prototype, "started", {
  1873. get: function() {
  1874. return null !== this.task;
  1875. },
  1876. enumerable: !1,
  1877. configurable: !0
  1878. }), t.prototype.nt = function(t) {
  1879. var r = this;
  1880. V("IndexBackiller", "Scheduled in ".concat(t, "ms")), this.task = this.asyncQueue.enqueueAfterDelay("index_backfill" /* TimerId.IndexBackfill */ , t, (function() {
  1881. return e(r, void 0, void 0, (function() {
  1882. var t, e, r, i;
  1883. return n(this, (function(n) {
  1884. switch (n.label) {
  1885. case 0:
  1886. this.task = null, n.label = 1;
  1887. case 1:
  1888. return n.trys.push([ 1, 3, , 7 ]), t = V, e = [ "IndexBackiller" ], r = "Documents written: ".concat,
  1889. [ 4 /*yield*/ , this.et.st() ];
  1890. case 2:
  1891. return t.apply(void 0, e.concat([ r.apply("Documents written: ", [ n.sent() ]) ])),
  1892. [ 3 /*break*/ , 7 ];
  1893. case 3:
  1894. return Ft(i = n.sent()) ? (V("IndexBackiller", "Ignoring IndexedDB error during index backfill: ", i),
  1895. [ 3 /*break*/ , 6 ]) : [ 3 /*break*/ , 4 ];
  1896. case 4:
  1897. return [ 4 /*yield*/ , Dt(i) ];
  1898. case 5:
  1899. n.sent(), n.label = 6;
  1900. case 6:
  1901. return [ 3 /*break*/ , 7 ];
  1902. case 7:
  1903. return [ 4 /*yield*/ , this.nt(6e4) ];
  1904. case 8:
  1905. return n.sent(), [ 2 /*return*/ ];
  1906. }
  1907. }));
  1908. }));
  1909. }));
  1910. }, t;
  1911. }(), Pt = /** @class */ function() {
  1912. function t(
  1913. /**
  1914. * LocalStore provides access to IndexManager and LocalDocumentView.
  1915. * These properties will update when the user changes. Consequently,
  1916. * making a local copy of IndexManager and LocalDocumentView will require
  1917. * updates over time. The simpler solution is to rely on LocalStore to have
  1918. * an up-to-date references to IndexManager and LocalDocumentStore.
  1919. */
  1920. t, e) {
  1921. this.localStore = t, this.persistence = e;
  1922. }
  1923. return t.prototype.st = function(t) {
  1924. return void 0 === t && (t = 50), e(this, void 0, void 0, (function() {
  1925. var e = this;
  1926. return n(this, (function(n) {
  1927. return [ 2 /*return*/ , this.persistence.runTransaction("Backfill Indexes", "readwrite-primary", (function(n) {
  1928. return e.it(n, t);
  1929. })) ];
  1930. }));
  1931. }));
  1932. },
  1933. /** Writes index entries until the cap is reached. Returns the number of documents processed. */ t.prototype.it = function(t, e) {
  1934. var n = this, r = new Set, i = e, o = !0;
  1935. return xt.doWhile((function() {
  1936. return !0 === o && i > 0;
  1937. }), (function() {
  1938. return n.localStore.indexManager.getNextCollectionGroupToUpdate(t).next((function(e) {
  1939. if (null !== e && !r.has(e)) return V("IndexBackiller", "Processing collection: ".concat(e)),
  1940. n.rt(t, e, i).next((function(t) {
  1941. i -= t, r.add(e);
  1942. }));
  1943. o = !1;
  1944. }));
  1945. })).next((function() {
  1946. return e - i;
  1947. }));
  1948. },
  1949. /**
  1950. * Writes entries for the provided collection group. Returns the number of documents processed.
  1951. */
  1952. t.prototype.rt = function(t, e, n) {
  1953. var r = this;
  1954. // Use the earliest offset of all field indexes to query the local cache.
  1955. return this.localStore.indexManager.getMinOffsetFromCollectionGroup(t, e).next((function(i) {
  1956. return r.localStore.localDocuments.getNextDocuments(t, e, i, n).next((function(n) {
  1957. var o = n.changes;
  1958. return r.localStore.indexManager.updateIndexEntries(t, o).next((function() {
  1959. return r.ot(i, n);
  1960. })).next((function(n) {
  1961. return V("IndexBackiller", "Updating offset: ".concat(n)), r.localStore.indexManager.updateCollectionGroup(t, e, n);
  1962. })).next((function() {
  1963. return o.size;
  1964. }));
  1965. }));
  1966. }));
  1967. },
  1968. /** Returns the next offset based on the provided documents. */ t.prototype.ot = function(t, e) {
  1969. var n = t;
  1970. return e.changes.forEach((function(t, e) {
  1971. var r = It(e);
  1972. Et(r, n) > 0 && (n = r);
  1973. })), new Tt(n.readTime, n.documentKey, Math.max(e.batchId, t.largestBatchId));
  1974. }, t;
  1975. }(), qt = /** @class */ function() {
  1976. function t(t, e) {
  1977. var n = this;
  1978. this.previousValue = t, e && (e.sequenceNumberHandler = function(t) {
  1979. return n.ut(t);
  1980. }, this.ct = function(t) {
  1981. return e.writeSequenceNumber(t);
  1982. });
  1983. }
  1984. return t.prototype.ut = function(t) {
  1985. return this.previousValue = Math.max(t, this.previousValue), this.previousValue;
  1986. }, t.prototype.next = function() {
  1987. var t = ++this.previousValue;
  1988. return this.ct && this.ct(t), t;
  1989. }, t;
  1990. }();
  1991. /** Implements the steps for backfilling indexes. */ qt.at = -1;
  1992. /**
  1993. * @license
  1994. * Copyright 2017 Google LLC
  1995. *
  1996. * Licensed under the Apache License, Version 2.0 (the "License");
  1997. * you may not use this file except in compliance with the License.
  1998. * You may obtain a copy of the License at
  1999. *
  2000. * http://www.apache.org/licenses/LICENSE-2.0
  2001. *
  2002. * Unless required by applicable law or agreed to in writing, software
  2003. * distributed under the License is distributed on an "AS IS" BASIS,
  2004. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2005. * See the License for the specific language governing permissions and
  2006. * limitations under the License.
  2007. */
  2008. var Ut =
  2009. /**
  2010. * Constructs a DatabaseInfo using the provided host, databaseId and
  2011. * persistenceKey.
  2012. *
  2013. * @param databaseId - The database to use.
  2014. * @param appId - The Firebase App Id.
  2015. * @param persistenceKey - A unique identifier for this Firestore's local
  2016. * storage (used in conjunction with the databaseId).
  2017. * @param host - The Firestore backend host to connect to.
  2018. * @param ssl - Whether to use SSL when connecting.
  2019. * @param forceLongPolling - Whether to use the forceLongPolling option
  2020. * when using WebChannel as the network transport.
  2021. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
  2022. * option when using WebChannel as the network transport.
  2023. * @param useFetchStreams Whether to use the Fetch API instead of
  2024. * XMLHTTPRequest
  2025. */
  2026. function(t, e, n, r, i, o, u, a) {
  2027. this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = r, this.ssl = i,
  2028. this.forceLongPolling = o, this.autoDetectLongPolling = u, this.useFetchStreams = a;
  2029. }, Bt = /** @class */ function() {
  2030. function t(t, e) {
  2031. this.projectId = t, this.database = e || "(default)";
  2032. }
  2033. return t.empty = function() {
  2034. return new t("", "");
  2035. }, Object.defineProperty(t.prototype, "isDefaultDatabase", {
  2036. get: function() {
  2037. return "(default)" === this.database;
  2038. },
  2039. enumerable: !1,
  2040. configurable: !0
  2041. }), t.prototype.isEqual = function(e) {
  2042. return e instanceof t && e.projectId === this.projectId && e.database === this.database;
  2043. }, t;
  2044. }();
  2045. /** The default database name for a project. */
  2046. /**
  2047. * Represents the database ID a Firestore client is associated with.
  2048. * @internal
  2049. */
  2050. /**
  2051. * @license
  2052. * Copyright 2017 Google LLC
  2053. *
  2054. * Licensed under the Apache License, Version 2.0 (the "License");
  2055. * you may not use this file except in compliance with the License.
  2056. * You may obtain a copy of the License at
  2057. *
  2058. * http://www.apache.org/licenses/LICENSE-2.0
  2059. *
  2060. * Unless required by applicable law or agreed to in writing, software
  2061. * distributed under the License is distributed on an "AS IS" BASIS,
  2062. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2063. * See the License for the specific language governing permissions and
  2064. * limitations under the License.
  2065. */
  2066. function Gt(t) {
  2067. var e = 0;
  2068. for (var n in t) Object.prototype.hasOwnProperty.call(t, n) && e++;
  2069. return e;
  2070. }
  2071. function Kt(t, e) {
  2072. for (var n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);
  2073. }
  2074. function jt(t) {
  2075. for (var e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;
  2076. return !0;
  2077. }
  2078. /**
  2079. * @license
  2080. * Copyright 2017 Google LLC
  2081. *
  2082. * Licensed under the Apache License, Version 2.0 (the "License");
  2083. * you may not use this file except in compliance with the License.
  2084. * You may obtain a copy of the License at
  2085. *
  2086. * http://www.apache.org/licenses/LICENSE-2.0
  2087. *
  2088. * Unless required by applicable law or agreed to in writing, software
  2089. * distributed under the License is distributed on an "AS IS" BASIS,
  2090. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2091. * See the License for the specific language governing permissions and
  2092. * limitations under the License.
  2093. */
  2094. /** Sentinel value that sorts before any Mutation Batch ID. */
  2095. /**
  2096. * Returns whether a variable is either undefined or null.
  2097. */ function Qt(t) {
  2098. return null == t;
  2099. }
  2100. /** Returns whether the value represents -0. */ function zt(t) {
  2101. // Detect if the value is -0.0. Based on polyfill from
  2102. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  2103. return 0 === t && 1 / t == -1 / 0;
  2104. }
  2105. /**
  2106. * Returns whether a value is an integer and in the safe integer range
  2107. * @param value - The value to test for being an integer and in the safe range
  2108. */ function Wt(t) {
  2109. return "number" == typeof t && Number.isInteger(t) && !zt(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;
  2110. }
  2111. /**
  2112. * @license
  2113. * Copyright 2020 Google LLC
  2114. *
  2115. * Licensed under the Apache License, Version 2.0 (the "License");
  2116. * you may not use this file except in compliance with the License.
  2117. * You may obtain a copy of the License at
  2118. *
  2119. * http://www.apache.org/licenses/LICENSE-2.0
  2120. *
  2121. * Unless required by applicable law or agreed to in writing, software
  2122. * distributed under the License is distributed on an "AS IS" BASIS,
  2123. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2124. * See the License for the specific language governing permissions and
  2125. * limitations under the License.
  2126. */
  2127. /** Converts a Base64 encoded string to a binary string. */
  2128. /** True if and only if the Base64 conversion functions are available. */ function Ht() {
  2129. return "undefined" != typeof atob;
  2130. }
  2131. /**
  2132. * @license
  2133. * Copyright 2020 Google LLC
  2134. *
  2135. * Licensed under the Apache License, Version 2.0 (the "License");
  2136. * you may not use this file except in compliance with the License.
  2137. * You may obtain a copy of the License at
  2138. *
  2139. * http://www.apache.org/licenses/LICENSE-2.0
  2140. *
  2141. * Unless required by applicable law or agreed to in writing, software
  2142. * distributed under the License is distributed on an "AS IS" BASIS,
  2143. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2144. * See the License for the specific language governing permissions and
  2145. * limitations under the License.
  2146. */
  2147. /**
  2148. * Immutable class that represents a "proto" byte string.
  2149. *
  2150. * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
  2151. * sent on the wire. This class abstracts away this differentiation by holding
  2152. * the proto byte string in a common class that must be converted into a string
  2153. * before being sent as a proto.
  2154. * @internal
  2155. */ var Yt = /** @class */ function() {
  2156. function t(t) {
  2157. this.binaryString = t;
  2158. }
  2159. return t.fromBase64String = function(e) {
  2160. return new t(atob(e));
  2161. }, t.fromUint8Array = function(e) {
  2162. // TODO(indexing); Remove the copy of the byte string here as this method
  2163. // is frequently called during indexing.
  2164. var n =
  2165. /**
  2166. * Helper function to convert an Uint8array to a binary string.
  2167. */
  2168. function(t) {
  2169. for (var e = "", n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]);
  2170. return e;
  2171. }(e);
  2172. return new t(n);
  2173. }, t.prototype[Symbol.iterator] = function() {
  2174. var t = this, e = 0;
  2175. return {
  2176. next: function() {
  2177. return e < t.binaryString.length ? {
  2178. value: t.binaryString.charCodeAt(e++),
  2179. done: !1
  2180. } : {
  2181. value: void 0,
  2182. done: !0
  2183. };
  2184. }
  2185. };
  2186. }, t.prototype.toBase64 = function() {
  2187. return t = this.binaryString, btoa(t);
  2188. /** Converts a binary string to a Base64 encoded string. */ var t;
  2189. }, t.prototype.toUint8Array = function() {
  2190. return function(t) {
  2191. for (var e = new Uint8Array(t.length), n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);
  2192. return e;
  2193. }(this.binaryString);
  2194. }, t.prototype.approximateByteSize = function() {
  2195. return 2 * this.binaryString.length;
  2196. }, t.prototype.compareTo = function(t) {
  2197. return rt(this.binaryString, t.binaryString);
  2198. }, t.prototype.isEqual = function(t) {
  2199. return this.binaryString === t.binaryString;
  2200. }, t;
  2201. }();
  2202. Yt.EMPTY_BYTE_STRING = new Yt("");
  2203. var Xt = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
  2204. /**
  2205. * Converts the possible Proto values for a timestamp value into a "seconds and
  2206. * nanos" representation.
  2207. */ function Zt(t) {
  2208. // The json interface (for the browser) will return an iso timestamp string,
  2209. // while the proto js library (for node) will return a
  2210. // google.protobuf.Timestamp instance.
  2211. if (U(!!t), "string" == typeof t) {
  2212. // The date string can have higher precision (nanos) than the Date class
  2213. // (millis), so we do some custom parsing here.
  2214. // Parse the nanos right out of the string.
  2215. var e = 0, n = Xt.exec(t);
  2216. if (U(!!n), n[1]) {
  2217. // Pad the fraction out to 9 digits (nanos).
  2218. var r = n[1];
  2219. r = (r + "000000000").substr(0, 9), e = Number(r);
  2220. }
  2221. // Parse the date to get the seconds.
  2222. var i = new Date(t);
  2223. return {
  2224. seconds: Math.floor(i.getTime() / 1e3),
  2225. nanos: e
  2226. };
  2227. }
  2228. return {
  2229. seconds: Jt(t.seconds),
  2230. nanos: Jt(t.nanos)
  2231. };
  2232. }
  2233. /**
  2234. * Converts the possible Proto types for numbers into a JavaScript number.
  2235. * Returns 0 if the value is not numeric.
  2236. */ function Jt(t) {
  2237. // TODO(bjornick): Handle int64 greater than 53 bits.
  2238. return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0;
  2239. }
  2240. /** Converts the possible Proto types for Blobs into a ByteString. */ function $t(t) {
  2241. return "string" == typeof t ? Yt.fromBase64String(t) : Yt.fromUint8Array(t);
  2242. }
  2243. /**
  2244. * @license
  2245. * Copyright 2020 Google LLC
  2246. *
  2247. * Licensed under the Apache License, Version 2.0 (the "License");
  2248. * you may not use this file except in compliance with the License.
  2249. * You may obtain a copy of the License at
  2250. *
  2251. * http://www.apache.org/licenses/LICENSE-2.0
  2252. *
  2253. * Unless required by applicable law or agreed to in writing, software
  2254. * distributed under the License is distributed on an "AS IS" BASIS,
  2255. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2256. * See the License for the specific language governing permissions and
  2257. * limitations under the License.
  2258. */
  2259. /**
  2260. * Represents a locally-applied ServerTimestamp.
  2261. *
  2262. * Server Timestamps are backed by MapValues that contain an internal field
  2263. * `__type__` with a value of `server_timestamp`. The previous value and local
  2264. * write time are stored in its `__previous_value__` and `__local_write_time__`
  2265. * fields respectively.
  2266. *
  2267. * Notes:
  2268. * - ServerTimestampValue instances are created as the result of applying a
  2269. * transform. They can only exist in the local view of a document. Therefore
  2270. * they do not need to be parsed or serialized.
  2271. * - When evaluated locally (e.g. for snapshot.data()), they by default
  2272. * evaluate to `null`. This behavior can be configured by passing custom
  2273. * FieldValueOptions to value().
  2274. * - With respect to other ServerTimestampValues, they sort by their
  2275. * localWriteTime.
  2276. */ function te(t) {
  2277. var e, n;
  2278. return "server_timestamp" === (null === (n = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue);
  2279. }
  2280. /**
  2281. * Creates a new ServerTimestamp proto value (using the internal format).
  2282. */
  2283. /**
  2284. * Returns the value of the field before this ServerTimestamp was set.
  2285. *
  2286. * Preserving the previous values allows the user to display the last resoled
  2287. * value until the backend responds with the timestamp.
  2288. */ function ee(t) {
  2289. var e = t.mapValue.fields.__previous_value__;
  2290. return te(e) ? ee(e) : e;
  2291. }
  2292. /**
  2293. * Returns the local time at which this timestamp was first set.
  2294. */ function ne(t) {
  2295. var e = Zt(t.mapValue.fields.__local_write_time__.timestampValue);
  2296. return new ut(e.seconds, e.nanos);
  2297. }
  2298. /**
  2299. * @license
  2300. * Copyright 2020 Google LLC
  2301. *
  2302. * Licensed under the Apache License, Version 2.0 (the "License");
  2303. * you may not use this file except in compliance with the License.
  2304. * You may obtain a copy of the License at
  2305. *
  2306. * http://www.apache.org/licenses/LICENSE-2.0
  2307. *
  2308. * Unless required by applicable law or agreed to in writing, software
  2309. * distributed under the License is distributed on an "AS IS" BASIS,
  2310. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2311. * See the License for the specific language governing permissions and
  2312. * limitations under the License.
  2313. */ var re = {
  2314. mapValue: {
  2315. fields: {
  2316. __type__: {
  2317. stringValue: "__max__"
  2318. }
  2319. }
  2320. }
  2321. }, ie = {
  2322. nullValue: "NULL_VALUE"
  2323. };
  2324. /** Extracts the backend's type order for the provided value. */ function oe(t) {
  2325. return "nullValue" in t ? 0 /* TypeOrder.NullValue */ : "booleanValue" in t ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in t ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in t ? 5 /* TypeOrder.StringValue */ : "bytesValue" in t ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in t ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in t ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in t ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in t ? te(t) ? 4 /* TypeOrder.ServerTimestampValue */ : we(t) ? 9007199254740991 /* TypeOrder.MaxValue */ : 10 /* TypeOrder.ObjectValue */ : q();
  2326. }
  2327. /** Tests `left` and `right` for equality based on the backend semantics. */ function ue(t, e) {
  2328. if (t === e) return !0;
  2329. var n = oe(t);
  2330. if (n !== oe(e)) return !1;
  2331. switch (n) {
  2332. case 0 /* TypeOrder.NullValue */ :
  2333. case 9007199254740991 /* TypeOrder.MaxValue */ :
  2334. return !0;
  2335. case 1 /* TypeOrder.BooleanValue */ :
  2336. return t.booleanValue === e.booleanValue;
  2337. case 4 /* TypeOrder.ServerTimestampValue */ :
  2338. return ne(t).isEqual(ne(e));
  2339. case 3 /* TypeOrder.TimestampValue */ :
  2340. return function(t, e) {
  2341. if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length)
  2342. // Use string equality for ISO 8601 timestamps
  2343. return t.timestampValue === e.timestampValue;
  2344. var n = Zt(t.timestampValue), r = Zt(e.timestampValue);
  2345. return n.seconds === r.seconds && n.nanos === r.nanos;
  2346. }(t, e);
  2347. case 5 /* TypeOrder.StringValue */ :
  2348. return t.stringValue === e.stringValue;
  2349. case 6 /* TypeOrder.BlobValue */ :
  2350. return function(t, e) {
  2351. return $t(t.bytesValue).isEqual($t(e.bytesValue));
  2352. }(t, e);
  2353. case 7 /* TypeOrder.RefValue */ :
  2354. return t.referenceValue === e.referenceValue;
  2355. case 8 /* TypeOrder.GeoPointValue */ :
  2356. return function(t, e) {
  2357. return Jt(t.geoPointValue.latitude) === Jt(e.geoPointValue.latitude) && Jt(t.geoPointValue.longitude) === Jt(e.geoPointValue.longitude);
  2358. }(t, e);
  2359. case 2 /* TypeOrder.NumberValue */ :
  2360. return function(t, e) {
  2361. if ("integerValue" in t && "integerValue" in e) return Jt(t.integerValue) === Jt(e.integerValue);
  2362. if ("doubleValue" in t && "doubleValue" in e) {
  2363. var n = Jt(t.doubleValue), r = Jt(e.doubleValue);
  2364. return n === r ? zt(n) === zt(r) : isNaN(n) && isNaN(r);
  2365. }
  2366. return !1;
  2367. }(t, e);
  2368. case 9 /* TypeOrder.ArrayValue */ :
  2369. return it(t.arrayValue.values || [], e.arrayValue.values || [], ue);
  2370. case 10 /* TypeOrder.ObjectValue */ :
  2371. return function(t, e) {
  2372. var n = t.mapValue.fields || {}, r = e.mapValue.fields || {};
  2373. if (Gt(n) !== Gt(r)) return !1;
  2374. for (var i in n) if (n.hasOwnProperty(i) && (void 0 === r[i] || !ue(n[i], r[i]))) return !1;
  2375. return !0;
  2376. }(t, e);
  2377. default:
  2378. return q();
  2379. }
  2380. }
  2381. function ae(t, e) {
  2382. return void 0 !== (t.values || []).find((function(t) {
  2383. return ue(t, e);
  2384. }));
  2385. }
  2386. function se(t, e) {
  2387. if (t === e) return 0;
  2388. var n = oe(t), r = oe(e);
  2389. if (n !== r) return rt(n, r);
  2390. switch (n) {
  2391. case 0 /* TypeOrder.NullValue */ :
  2392. case 9007199254740991 /* TypeOrder.MaxValue */ :
  2393. return 0;
  2394. case 1 /* TypeOrder.BooleanValue */ :
  2395. return rt(t.booleanValue, e.booleanValue);
  2396. case 2 /* TypeOrder.NumberValue */ :
  2397. return function(t, e) {
  2398. var n = Jt(t.integerValue || t.doubleValue), r = Jt(e.integerValue || e.doubleValue);
  2399. return n < r ? -1 : n > r ? 1 : n === r ? 0 :
  2400. // one or both are NaN.
  2401. isNaN(n) ? isNaN(r) ? 0 : -1 : 1;
  2402. }(t, e);
  2403. case 3 /* TypeOrder.TimestampValue */ :
  2404. return ce(t.timestampValue, e.timestampValue);
  2405. case 4 /* TypeOrder.ServerTimestampValue */ :
  2406. return ce(ne(t), ne(e));
  2407. case 5 /* TypeOrder.StringValue */ :
  2408. return rt(t.stringValue, e.stringValue);
  2409. case 6 /* TypeOrder.BlobValue */ :
  2410. return function(t, e) {
  2411. var n = $t(t), r = $t(e);
  2412. return n.compareTo(r);
  2413. }(t.bytesValue, e.bytesValue);
  2414. case 7 /* TypeOrder.RefValue */ :
  2415. return function(t, e) {
  2416. for (var n = t.split("/"), r = e.split("/"), i = 0; i < n.length && i < r.length; i++) {
  2417. var o = rt(n[i], r[i]);
  2418. if (0 !== o) return o;
  2419. }
  2420. return rt(n.length, r.length);
  2421. }(t.referenceValue, e.referenceValue);
  2422. case 8 /* TypeOrder.GeoPointValue */ :
  2423. return function(t, e) {
  2424. var n = rt(Jt(t.latitude), Jt(e.latitude));
  2425. return 0 !== n ? n : rt(Jt(t.longitude), Jt(e.longitude));
  2426. }(t.geoPointValue, e.geoPointValue);
  2427. case 9 /* TypeOrder.ArrayValue */ :
  2428. return function(t, e) {
  2429. for (var n = t.values || [], r = e.values || [], i = 0; i < n.length && i < r.length; ++i) {
  2430. var o = se(n[i], r[i]);
  2431. if (o) return o;
  2432. }
  2433. return rt(n.length, r.length);
  2434. }(t.arrayValue, e.arrayValue);
  2435. case 10 /* TypeOrder.ObjectValue */ :
  2436. return function(t, e) {
  2437. if (t === re.mapValue && e === re.mapValue) return 0;
  2438. if (t === re.mapValue) return 1;
  2439. if (e === re.mapValue) return -1;
  2440. var n = t.fields || {}, r = Object.keys(n), i = e.fields || {}, o = Object.keys(i);
  2441. // Even though MapValues are likely sorted correctly based on their insertion
  2442. // order (e.g. when received from the backend), local modifications can bring
  2443. // elements out of order. We need to re-sort the elements to ensure that
  2444. // canonical IDs are independent of insertion order.
  2445. r.sort(), o.sort();
  2446. for (var u = 0; u < r.length && u < o.length; ++u) {
  2447. var a = rt(r[u], o[u]);
  2448. if (0 !== a) return a;
  2449. var s = se(n[r[u]], i[o[u]]);
  2450. if (0 !== s) return s;
  2451. }
  2452. return rt(r.length, o.length);
  2453. }(t.mapValue, e.mapValue);
  2454. default:
  2455. throw q();
  2456. }
  2457. }
  2458. function ce(t, e) {
  2459. if ("string" == typeof t && "string" == typeof e && t.length === e.length) return rt(t, e);
  2460. var n = Zt(t), r = Zt(e), i = rt(n.seconds, r.seconds);
  2461. return 0 !== i ? i : rt(n.nanos, r.nanos);
  2462. }
  2463. function le(t) {
  2464. return he(t);
  2465. }
  2466. function he(t) {
  2467. 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) {
  2468. var e = Zt(t);
  2469. return "time(".concat(e.seconds, ",").concat(e.nanos, ")");
  2470. }(t.timestampValue) : "stringValue" in t ? t.stringValue : "bytesValue" in t ? $t(t.bytesValue).toBase64() : "referenceValue" in t ? (n = t.referenceValue,
  2471. ft.fromName(n).toString()) : "geoPointValue" in t ? "geo(".concat((e = t.geoPointValue).latitude, ",").concat(e.longitude, ")") : "arrayValue" in t ? function(t) {
  2472. for (var e = "[", n = !0, r = 0, i = t.values || []; r < i.length; r++) {
  2473. n ? n = !1 : e += ",", e += he(i[r]);
  2474. }
  2475. return e + "]";
  2476. }(t.arrayValue) : "mapValue" in t ? function(t) {
  2477. for (
  2478. // Iteration order in JavaScript is not guaranteed. To ensure that we generate
  2479. // matching canonical IDs for identical maps, we need to sort the keys.
  2480. var e = "{", n = !0, r = 0, i = Object.keys(t.fields || {}).sort(); r < i.length; r++) {
  2481. var o = i[r];
  2482. n ? n = !1 : e += ",", e += "".concat(o, ":").concat(he(t.fields[o]));
  2483. }
  2484. return e + "}";
  2485. }(t.mapValue) : q();
  2486. var e, n;
  2487. }
  2488. function fe(t, e) {
  2489. return {
  2490. referenceValue: "projects/".concat(t.projectId, "/databases/").concat(t.database, "/documents/").concat(e.path.canonicalString())
  2491. };
  2492. }
  2493. /** Returns true if `value` is an IntegerValue . */ function de(t) {
  2494. return !!t && "integerValue" in t;
  2495. }
  2496. /** Returns true if `value` is a DoubleValue. */
  2497. /** Returns true if `value` is an ArrayValue. */ function pe(t) {
  2498. return !!t && "arrayValue" in t;
  2499. }
  2500. /** Returns true if `value` is a NullValue. */ function ye(t) {
  2501. return !!t && "nullValue" in t;
  2502. }
  2503. /** Returns true if `value` is NaN. */ function ve(t) {
  2504. return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue));
  2505. }
  2506. /** Returns true if `value` is a MapValue. */ function me(t) {
  2507. return !!t && "mapValue" in t;
  2508. }
  2509. /** Creates a deep copy of `source`. */ function ge(t) {
  2510. if (t.geoPointValue) return {
  2511. geoPointValue: Object.assign({}, t.geoPointValue)
  2512. };
  2513. if (t.timestampValue && "object" == typeof t.timestampValue) return {
  2514. timestampValue: Object.assign({}, t.timestampValue)
  2515. };
  2516. if (t.mapValue) {
  2517. var e = {
  2518. mapValue: {
  2519. fields: {}
  2520. }
  2521. };
  2522. return Kt(t.mapValue.fields, (function(t, n) {
  2523. return e.mapValue.fields[t] = ge(n);
  2524. })), e;
  2525. }
  2526. if (t.arrayValue) {
  2527. for (var n = {
  2528. arrayValue: {
  2529. values: []
  2530. }
  2531. }, r = 0; r < (t.arrayValue.values || []).length; ++r) n.arrayValue.values[r] = ge(t.arrayValue.values[r]);
  2532. return n;
  2533. }
  2534. return Object.assign({}, t);
  2535. }
  2536. /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function we(t) {
  2537. return "__max__" === (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue;
  2538. }
  2539. /** Returns the lowest value for the given value type (inclusive). */ function be(t) {
  2540. return "nullValue" in t ? ie : "booleanValue" in t ? {
  2541. booleanValue: !1
  2542. } : "integerValue" in t || "doubleValue" in t ? {
  2543. doubleValue: NaN
  2544. } : "timestampValue" in t ? {
  2545. timestampValue: {
  2546. seconds: Number.MIN_SAFE_INTEGER
  2547. }
  2548. } : "stringValue" in t ? {
  2549. stringValue: ""
  2550. } : "bytesValue" in t ? {
  2551. bytesValue: ""
  2552. } : "referenceValue" in t ? fe(Bt.empty(), ft.empty()) : "geoPointValue" in t ? {
  2553. geoPointValue: {
  2554. latitude: -90,
  2555. longitude: -180
  2556. }
  2557. } : "arrayValue" in t ? {
  2558. arrayValue: {}
  2559. } : "mapValue" in t ? {
  2560. mapValue: {}
  2561. } : q();
  2562. }
  2563. /** Returns the largest value for the given value type (exclusive). */ function Ie(t) {
  2564. return "nullValue" in t ? {
  2565. booleanValue: !1
  2566. } : "booleanValue" in t ? {
  2567. doubleValue: NaN
  2568. } : "integerValue" in t || "doubleValue" in t ? {
  2569. timestampValue: {
  2570. seconds: Number.MIN_SAFE_INTEGER
  2571. }
  2572. } : "timestampValue" in t ? {
  2573. stringValue: ""
  2574. } : "stringValue" in t ? {
  2575. bytesValue: ""
  2576. } : "bytesValue" in t ? fe(Bt.empty(), ft.empty()) : "referenceValue" in t ? {
  2577. geoPointValue: {
  2578. latitude: -90,
  2579. longitude: -180
  2580. }
  2581. } : "geoPointValue" in t ? {
  2582. arrayValue: {}
  2583. } : "arrayValue" in t ? {
  2584. mapValue: {}
  2585. } : "mapValue" in t ? re : q();
  2586. }
  2587. function Te(t, e) {
  2588. var n = se(t.value, e.value);
  2589. return 0 !== n ? n : t.inclusive && !e.inclusive ? -1 : !t.inclusive && e.inclusive ? 1 : 0;
  2590. }
  2591. function Ee(t, e) {
  2592. var n = se(t.value, e.value);
  2593. return 0 !== n ? n : t.inclusive && !e.inclusive ? 1 : !t.inclusive && e.inclusive ? -1 : 0;
  2594. }
  2595. /**
  2596. * @license
  2597. * Copyright 2022 Google LLC
  2598. *
  2599. * Licensed under the Apache License, Version 2.0 (the "License");
  2600. * you may not use this file except in compliance with the License.
  2601. * You may obtain a copy of the License at
  2602. *
  2603. * http://www.apache.org/licenses/LICENSE-2.0
  2604. *
  2605. * Unless required by applicable law or agreed to in writing, software
  2606. * distributed under the License is distributed on an "AS IS" BASIS,
  2607. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2608. * See the License for the specific language governing permissions and
  2609. * limitations under the License.
  2610. */
  2611. /**
  2612. * Represents a bound of a query.
  2613. *
  2614. * The bound is specified with the given components representing a position and
  2615. * whether it's just before or just after the position (relative to whatever the
  2616. * query order is).
  2617. *
  2618. * The position represents a logical index position for a query. It's a prefix
  2619. * of values for the (potentially implicit) order by clauses of a query.
  2620. *
  2621. * Bound provides a function to determine whether a document comes before or
  2622. * after a bound. This is influenced by whether the position is just before or
  2623. * just after the provided values.
  2624. */ var Se = function(t, e) {
  2625. this.position = t, this.inclusive = e;
  2626. };
  2627. function _e(t, e, n) {
  2628. for (var r = 0, i = 0; i < t.position.length; i++) {
  2629. var o = e[i], u = t.position[i];
  2630. if (r = o.field.isKeyField() ? ft.comparator(ft.fromName(u.referenceValue), n.key) : se(u, n.data.field(o.field)),
  2631. "desc" /* Direction.DESCENDING */ === o.dir && (r *= -1), 0 !== r) break;
  2632. }
  2633. return r;
  2634. }
  2635. /**
  2636. * Returns true if a document sorts after a bound using the provided sort
  2637. * order.
  2638. */ function De(t, e) {
  2639. if (null === t) return null === e;
  2640. if (null === e) return !1;
  2641. if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1;
  2642. for (var n = 0; n < t.position.length; n++) if (!ue(t.position[n], e.position[n])) return !1;
  2643. return !0;
  2644. }
  2645. /**
  2646. * @license
  2647. * Copyright 2022 Google LLC
  2648. *
  2649. * Licensed under the Apache License, Version 2.0 (the "License");
  2650. * you may not use this file except in compliance with the License.
  2651. * You may obtain a copy of the License at
  2652. *
  2653. * http://www.apache.org/licenses/LICENSE-2.0
  2654. *
  2655. * Unless required by applicable law or agreed to in writing, software
  2656. * distributed under the License is distributed on an "AS IS" BASIS,
  2657. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2658. * See the License for the specific language governing permissions and
  2659. * limitations under the License.
  2660. */ var xe = function() {}, Ae = /** @class */ function(e) {
  2661. function n(t, n, r) {
  2662. var i = this;
  2663. return (i = e.call(this) || this).field = t, i.op = n, i.value = r, i;
  2664. }
  2665. /**
  2666. * Creates a filter based on the provided arguments.
  2667. */ return t(n, e), n.create = function(t, e, r) {
  2668. return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, r) : new Pe(t, e, r) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new Ge(t, r) : "in" /* Operator.IN */ === e ? new Ke(t, r) : "not-in" /* Operator.NOT_IN */ === e ? new je(t, r) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new Qe(t, r) : new n(t, e, r);
  2669. }, n.createKeyFieldInFilter = function(t, e, n) {
  2670. return "in" /* Operator.IN */ === e ? new qe(t, n) : new Ue(t, n);
  2671. }, n.prototype.matches = function(t) {
  2672. var e = t.data.field(this.field);
  2673. // Types do not have to match in NOT_EQUAL filters.
  2674. return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && this.matchesComparison(se(e, this.value)) : null !== e && oe(this.value) === oe(e) && this.matchesComparison(se(e, this.value));
  2675. // Only compare types with matching backend order (such as double and int).
  2676. }, n.prototype.matchesComparison = function(t) {
  2677. switch (this.op) {
  2678. case "<" /* Operator.LESS_THAN */ :
  2679. return t < 0;
  2680. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  2681. return t <= 0;
  2682. case "==" /* Operator.EQUAL */ :
  2683. return 0 === t;
  2684. case "!=" /* Operator.NOT_EQUAL */ :
  2685. return 0 !== t;
  2686. case ">" /* Operator.GREATER_THAN */ :
  2687. return t > 0;
  2688. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  2689. return t >= 0;
  2690. default:
  2691. return q();
  2692. }
  2693. }, n.prototype.isInequality = function() {
  2694. return [ "<" /* Operator.LESS_THAN */ , "<=" /* Operator.LESS_THAN_OR_EQUAL */ , ">" /* Operator.GREATER_THAN */ , ">=" /* Operator.GREATER_THAN_OR_EQUAL */ , "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0;
  2695. }, n.prototype.getFlattenedFilters = function() {
  2696. return [ this ];
  2697. }, n.prototype.getFilters = function() {
  2698. return [ this ];
  2699. }, n.prototype.getFirstInequalityField = function() {
  2700. return this.isInequality() ? this.field : null;
  2701. }, n;
  2702. }(xe), Ce = /** @class */ function(e) {
  2703. function n(t, n) {
  2704. var r = this;
  2705. return (r = e.call(this) || this).filters = t, r.op = n, r.ht = null, r;
  2706. }
  2707. /**
  2708. * Creates a filter based on the provided arguments.
  2709. */ return t(n, e), n.create = function(t, e) {
  2710. return new n(t, e);
  2711. }, n.prototype.matches = function(t) {
  2712. return Ne(this) ? void 0 === this.filters.find((function(e) {
  2713. return !e.matches(t);
  2714. })) : void 0 !== this.filters.find((function(e) {
  2715. return e.matches(t);
  2716. }));
  2717. }, n.prototype.getFlattenedFilters = function() {
  2718. return null !== this.ht || (this.ht = this.filters.reduce((function(t, e) {
  2719. return t.concat(e.getFlattenedFilters());
  2720. }), [])), this.ht;
  2721. },
  2722. // Returns a mutable copy of `this.filters`
  2723. n.prototype.getFilters = function() {
  2724. return Object.assign([], this.filters);
  2725. }, n.prototype.getFirstInequalityField = function() {
  2726. var t = this.lt((function(t) {
  2727. return t.isInequality();
  2728. }));
  2729. return null !== t ? t.field : null;
  2730. },
  2731. // Performs a depth-first search to find and return the first FieldFilter in the composite filter
  2732. // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the
  2733. // predicate.
  2734. n.prototype.lt = function(t) {
  2735. for (var e = 0, n = this.getFlattenedFilters(); e < n.length; e++) {
  2736. var r = n[e];
  2737. if (t(r)) return r;
  2738. }
  2739. return null;
  2740. }, n;
  2741. }(xe);
  2742. function Ne(t) {
  2743. return "and" /* CompositeOperator.AND */ === t.op;
  2744. }
  2745. function ke(t) {
  2746. return "or" /* CompositeOperator.OR */ === t.op;
  2747. }
  2748. /**
  2749. * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.
  2750. */ function Fe(t) {
  2751. return Oe(t) && Ne(t);
  2752. }
  2753. /**
  2754. * Returns true if this filter does not contain any composite filters. Returns false otherwise.
  2755. */ function Oe(t) {
  2756. for (var e = 0, n = t.filters; e < n.length; e++) {
  2757. if (n[e] instanceof Ce) return !1;
  2758. }
  2759. return !0;
  2760. }
  2761. function Re(t) {
  2762. if (t instanceof Ae)
  2763. // TODO(b/29183165): Technically, this won't be unique if two values have
  2764. // the same description, such as the int 3 and the string "3". So we should
  2765. // add the types in here somehow, too.
  2766. return t.field.canonicalString() + t.op.toString() + le(t.value);
  2767. if (Fe(t))
  2768. // Older SDK versions use an implicit AND operation between their filters.
  2769. // In the new SDK versions, the developer may use an explicit AND filter.
  2770. // To stay consistent with the old usages, we add a special case to ensure
  2771. // the canonical ID for these two are the same. For example:
  2772. // `col.whereEquals("a", 1).whereEquals("b", 2)` should have the same
  2773. // canonical ID as `col.where(and(equals("a",1), equals("b",2)))`.
  2774. return t.filters.map((function(t) {
  2775. return Re(t);
  2776. })).join(",");
  2777. // filter instanceof CompositeFilter
  2778. var e = t.filters.map((function(t) {
  2779. return Re(t);
  2780. })).join(",");
  2781. return "".concat(t.op, "(").concat(e, ")");
  2782. }
  2783. function Ve(t, e) {
  2784. return t instanceof Ae ? function(t, e) {
  2785. return e instanceof Ae && t.op === e.op && t.field.isEqual(e.field) && ue(t.value, e.value);
  2786. }(t, e) : t instanceof Ce ? function(t, e) {
  2787. return e instanceof Ce && t.op === e.op && t.filters.length === e.filters.length && t.filters.reduce((function(t, n, r) {
  2788. return t && Ve(n, e.filters[r]);
  2789. }), !0);
  2790. }(t, e) : void q();
  2791. }
  2792. function Me(t, e) {
  2793. var n = t.filters.concat(e);
  2794. return Ce.create(n, t.op);
  2795. }
  2796. /** Returns a debug description for `filter`. */ function Le(t) {
  2797. return t instanceof Ae ? function(t) {
  2798. return "".concat(t.field.canonicalString(), " ").concat(t.op, " ").concat(le(t.value));
  2799. }(t) : t instanceof Ce ? function(t) {
  2800. return t.op.toString() + " {" + t.getFilters().map(Le).join(" ,") + "}";
  2801. }(t) : "Filter";
  2802. }
  2803. var Pe = /** @class */ function(e) {
  2804. function n(t, n, r) {
  2805. var i = this;
  2806. return (i = e.call(this, t, n, r) || this).key = ft.fromName(r.referenceValue),
  2807. i;
  2808. }
  2809. return t(n, e), n.prototype.matches = function(t) {
  2810. var e = ft.comparator(t.key, this.key);
  2811. return this.matchesComparison(e);
  2812. }, n;
  2813. }(Ae), qe = /** @class */ function(e) {
  2814. function n(t, n) {
  2815. var r = this;
  2816. return (r = e.call(this, t, "in" /* Operator.IN */ , n) || this).keys = Be("in" /* Operator.IN */ , n),
  2817. r;
  2818. }
  2819. return t(n, e), n.prototype.matches = function(t) {
  2820. return this.keys.some((function(e) {
  2821. return e.isEqual(t.key);
  2822. }));
  2823. }, n;
  2824. }(Ae), Ue = /** @class */ function(e) {
  2825. function n(t, n) {
  2826. var r = this;
  2827. return (r = e.call(this, t, "not-in" /* Operator.NOT_IN */ , n) || this).keys = Be("not-in" /* Operator.NOT_IN */ , n),
  2828. r;
  2829. }
  2830. return t(n, e), n.prototype.matches = function(t) {
  2831. return !this.keys.some((function(e) {
  2832. return e.isEqual(t.key);
  2833. }));
  2834. }, n;
  2835. }(Ae);
  2836. /** Filter that matches on key fields within an array. */ function Be(t, e) {
  2837. var n;
  2838. return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((function(t) {
  2839. return ft.fromName(t.referenceValue);
  2840. }));
  2841. }
  2842. /** A Filter that implements the array-contains operator. */ var Ge = /** @class */ function(e) {
  2843. function n(t, n) {
  2844. return e.call(this, t, "array-contains" /* Operator.ARRAY_CONTAINS */ , n) || this;
  2845. }
  2846. return t(n, e), n.prototype.matches = function(t) {
  2847. var e = t.data.field(this.field);
  2848. return pe(e) && ae(e.arrayValue, this.value);
  2849. }, n;
  2850. }(Ae), Ke = /** @class */ function(e) {
  2851. function n(t, n) {
  2852. return e.call(this, t, "in" /* Operator.IN */ , n) || this;
  2853. }
  2854. return t(n, e), n.prototype.matches = function(t) {
  2855. var e = t.data.field(this.field);
  2856. return null !== e && ae(this.value.arrayValue, e);
  2857. }, n;
  2858. }(Ae), je = /** @class */ function(e) {
  2859. function n(t, n) {
  2860. return e.call(this, t, "not-in" /* Operator.NOT_IN */ , n) || this;
  2861. }
  2862. return t(n, e), n.prototype.matches = function(t) {
  2863. if (ae(this.value.arrayValue, {
  2864. nullValue: "NULL_VALUE"
  2865. })) return !1;
  2866. var e = t.data.field(this.field);
  2867. return null !== e && !ae(this.value.arrayValue, e);
  2868. }, n;
  2869. }(Ae), Qe = /** @class */ function(e) {
  2870. function n(t, n) {
  2871. return e.call(this, t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , n) || this;
  2872. }
  2873. return t(n, e), n.prototype.matches = function(t) {
  2874. var e = this, n = t.data.field(this.field);
  2875. return !(!pe(n) || !n.arrayValue.values) && n.arrayValue.values.some((function(t) {
  2876. return ae(e.value.arrayValue, t);
  2877. }));
  2878. }, n;
  2879. }(Ae), ze = function(t, e /* Direction.ASCENDING */) {
  2880. void 0 === e && (e = "asc"), this.field = t, this.dir = e;
  2881. };
  2882. /** A Filter that implements the IN operator. */ function We(t, e) {
  2883. return t.dir === e.dir && t.field.isEqual(e.field);
  2884. }
  2885. /**
  2886. * @license
  2887. * Copyright 2017 Google LLC
  2888. *
  2889. * Licensed under the Apache License, Version 2.0 (the "License");
  2890. * you may not use this file except in compliance with the License.
  2891. * You may obtain a copy of the License at
  2892. *
  2893. * http://www.apache.org/licenses/LICENSE-2.0
  2894. *
  2895. * Unless required by applicable law or agreed to in writing, software
  2896. * distributed under the License is distributed on an "AS IS" BASIS,
  2897. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2898. * See the License for the specific language governing permissions and
  2899. * limitations under the License.
  2900. */
  2901. // An immutable sorted map implementation, based on a Left-leaning Red-Black
  2902. // tree.
  2903. var He = /** @class */ function() {
  2904. function t(t, e) {
  2905. this.comparator = t, this.root = e || Xe.EMPTY;
  2906. }
  2907. // Returns a copy of the map, with the specified key/value added or replaced.
  2908. return t.prototype.insert = function(e, n) {
  2909. return new t(this.comparator, this.root.insert(e, n, this.comparator).copy(null, null, Xe.BLACK, null, null));
  2910. },
  2911. // Returns a copy of the map, with the specified key removed.
  2912. t.prototype.remove = function(e) {
  2913. return new t(this.comparator, this.root.remove(e, this.comparator).copy(null, null, Xe.BLACK, null, null));
  2914. },
  2915. // Returns the value of the node with the given key, or null.
  2916. t.prototype.get = function(t) {
  2917. for (var e = this.root; !e.isEmpty(); ) {
  2918. var n = this.comparator(t, e.key);
  2919. if (0 === n) return e.value;
  2920. n < 0 ? e = e.left : n > 0 && (e = e.right);
  2921. }
  2922. return null;
  2923. },
  2924. // Returns the index of the element in this sorted map, or -1 if it doesn't
  2925. // exist.
  2926. t.prototype.indexOf = function(t) {
  2927. for (
  2928. // Number of nodes that were pruned when descending right
  2929. var e = 0, n = this.root; !n.isEmpty(); ) {
  2930. var r = this.comparator(t, n.key);
  2931. if (0 === r) return e + n.left.size;
  2932. r < 0 ? n = n.left : (
  2933. // Count all nodes left of the node plus the node itself
  2934. e += n.left.size + 1, n = n.right);
  2935. }
  2936. // Node not found
  2937. return -1;
  2938. }, t.prototype.isEmpty = function() {
  2939. return this.root.isEmpty();
  2940. }, Object.defineProperty(t.prototype, "size", {
  2941. // Returns the total number of nodes in the map.
  2942. get: function() {
  2943. return this.root.size;
  2944. },
  2945. enumerable: !1,
  2946. configurable: !0
  2947. }),
  2948. // Returns the minimum key in the map.
  2949. t.prototype.minKey = function() {
  2950. return this.root.minKey();
  2951. },
  2952. // Returns the maximum key in the map.
  2953. t.prototype.maxKey = function() {
  2954. return this.root.maxKey();
  2955. },
  2956. // Traverses the map in key order and calls the specified action function
  2957. // for each key/value pair. If action returns true, traversal is aborted.
  2958. // Returns the first truthy value returned by action, or the last falsey
  2959. // value returned by action.
  2960. t.prototype.inorderTraversal = function(t) {
  2961. return this.root.inorderTraversal(t);
  2962. }, t.prototype.forEach = function(t) {
  2963. this.inorderTraversal((function(e, n) {
  2964. return t(e, n), !1;
  2965. }));
  2966. }, t.prototype.toString = function() {
  2967. var t = [];
  2968. return this.inorderTraversal((function(e, n) {
  2969. return t.push("".concat(e, ":").concat(n)), !1;
  2970. })), "{".concat(t.join(", "), "}");
  2971. },
  2972. // Traverses the map in reverse key order and calls the specified action
  2973. // function for each key/value pair. If action returns true, traversal is
  2974. // aborted.
  2975. // Returns the first truthy value returned by action, or the last falsey
  2976. // value returned by action.
  2977. t.prototype.reverseTraversal = function(t) {
  2978. return this.root.reverseTraversal(t);
  2979. },
  2980. // Returns an iterator over the SortedMap.
  2981. t.prototype.getIterator = function() {
  2982. return new Ye(this.root, null, this.comparator, !1);
  2983. }, t.prototype.getIteratorFrom = function(t) {
  2984. return new Ye(this.root, t, this.comparator, !1);
  2985. }, t.prototype.getReverseIterator = function() {
  2986. return new Ye(this.root, null, this.comparator, !0);
  2987. }, t.prototype.getReverseIteratorFrom = function(t) {
  2988. return new Ye(this.root, t, this.comparator, !0);
  2989. }, t;
  2990. }(), Ye = /** @class */ function() {
  2991. function t(t, e, n, r) {
  2992. this.isReverse = r, this.nodeStack = [];
  2993. for (var i = 1; !t.isEmpty(); ) if (i = e ? n(t.key, e) : 1,
  2994. // flip the comparison if we're going in reverse
  2995. e && r && (i *= -1), i < 0)
  2996. // This node is less than our start key. ignore it
  2997. t = this.isReverse ? t.left : t.right; else {
  2998. if (0 === i) {
  2999. // This node is exactly equal to our start key. Push it on the stack,
  3000. // but stop iterating;
  3001. this.nodeStack.push(t);
  3002. break;
  3003. }
  3004. // This node is greater than our start key, add it to the stack and move
  3005. // to the next one
  3006. this.nodeStack.push(t), t = this.isReverse ? t.right : t.left;
  3007. }
  3008. }
  3009. return t.prototype.getNext = function() {
  3010. var t = this.nodeStack.pop(), e = {
  3011. key: t.key,
  3012. value: t.value
  3013. };
  3014. if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t),
  3015. t = t.left;
  3016. return e;
  3017. }, t.prototype.hasNext = function() {
  3018. return this.nodeStack.length > 0;
  3019. }, t.prototype.peek = function() {
  3020. if (0 === this.nodeStack.length) return null;
  3021. var t = this.nodeStack[this.nodeStack.length - 1];
  3022. return {
  3023. key: t.key,
  3024. value: t.value
  3025. };
  3026. }, t;
  3027. }(), Xe = /** @class */ function() {
  3028. function t(e, n, r, i, o) {
  3029. this.key = e, this.value = n, this.color = null != r ? r : t.RED, this.left = null != i ? i : t.EMPTY,
  3030. this.right = null != o ? o : t.EMPTY, this.size = this.left.size + 1 + this.right.size;
  3031. }
  3032. // Returns a copy of the current node, optionally replacing pieces of it.
  3033. return t.prototype.copy = function(e, n, r, i, o) {
  3034. return new t(null != e ? e : this.key, null != n ? n : this.value, null != r ? r : this.color, null != i ? i : this.left, null != o ? o : this.right);
  3035. }, t.prototype.isEmpty = function() {
  3036. return !1;
  3037. },
  3038. // Traverses the tree in key order and calls the specified action function
  3039. // for each node. If action returns true, traversal is aborted.
  3040. // Returns the first truthy value returned by action, or the last falsey
  3041. // value returned by action.
  3042. t.prototype.inorderTraversal = function(t) {
  3043. return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t);
  3044. },
  3045. // Traverses the tree in reverse key order and calls the specified action
  3046. // function for each node. If action returns true, traversal is aborted.
  3047. // Returns the first truthy value returned by action, or the last falsey
  3048. // value returned by action.
  3049. t.prototype.reverseTraversal = function(t) {
  3050. return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t);
  3051. },
  3052. // Returns the minimum node in the tree.
  3053. t.prototype.min = function() {
  3054. return this.left.isEmpty() ? this : this.left.min();
  3055. },
  3056. // Returns the maximum key in the tree.
  3057. t.prototype.minKey = function() {
  3058. return this.min().key;
  3059. },
  3060. // Returns the maximum key in the tree.
  3061. t.prototype.maxKey = function() {
  3062. return this.right.isEmpty() ? this.key : this.right.maxKey();
  3063. },
  3064. // Returns new tree, with the key/value added.
  3065. t.prototype.insert = function(t, e, n) {
  3066. var r = this, i = n(t, r.key);
  3067. return (r = i < 0 ? r.copy(null, null, null, r.left.insert(t, e, n), null) : 0 === i ? r.copy(null, e, null, null, null) : r.copy(null, null, null, null, r.right.insert(t, e, n))).fixUp();
  3068. }, t.prototype.removeMin = function() {
  3069. if (this.left.isEmpty()) return t.EMPTY;
  3070. var e = this;
  3071. return e.left.isRed() || e.left.left.isRed() || (e = e.moveRedLeft()), (e = e.copy(null, null, null, e.left.removeMin(), null)).fixUp();
  3072. },
  3073. // Returns new tree, with the specified item removed.
  3074. t.prototype.remove = function(e, n) {
  3075. var r, i = this;
  3076. if (n(e, i.key) < 0) i.left.isEmpty() || i.left.isRed() || i.left.left.isRed() || (i = i.moveRedLeft()),
  3077. i = i.copy(null, null, null, i.left.remove(e, n), null); else {
  3078. if (i.left.isRed() && (i = i.rotateRight()), i.right.isEmpty() || i.right.isRed() || i.right.left.isRed() || (i = i.moveRedRight()),
  3079. 0 === n(e, i.key)) {
  3080. if (i.right.isEmpty()) return t.EMPTY;
  3081. r = i.right.min(), i = i.copy(r.key, r.value, null, null, i.right.removeMin());
  3082. }
  3083. i = i.copy(null, null, null, null, i.right.remove(e, n));
  3084. }
  3085. return i.fixUp();
  3086. }, t.prototype.isRed = function() {
  3087. return this.color;
  3088. },
  3089. // Returns new tree after performing any needed rotations.
  3090. t.prototype.fixUp = function() {
  3091. var t = this;
  3092. return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()),
  3093. t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t;
  3094. }, t.prototype.moveRedLeft = function() {
  3095. var t = this.colorFlip();
  3096. return t.right.left.isRed() && (t = (t = (t = t.copy(null, null, null, null, t.right.rotateRight())).rotateLeft()).colorFlip()),
  3097. t;
  3098. }, t.prototype.moveRedRight = function() {
  3099. var t = this.colorFlip();
  3100. return t.left.left.isRed() && (t = (t = t.rotateRight()).colorFlip()), t;
  3101. }, t.prototype.rotateLeft = function() {
  3102. var e = this.copy(null, null, t.RED, null, this.right.left);
  3103. return this.right.copy(null, null, this.color, e, null);
  3104. }, t.prototype.rotateRight = function() {
  3105. var e = this.copy(null, null, t.RED, this.left.right, null);
  3106. return this.left.copy(null, null, this.color, null, e);
  3107. }, t.prototype.colorFlip = function() {
  3108. var t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);
  3109. return this.copy(null, null, !this.color, t, e);
  3110. },
  3111. // For testing.
  3112. t.prototype.checkMaxDepth = function() {
  3113. var t = this.check();
  3114. return Math.pow(2, t) <= this.size + 1;
  3115. },
  3116. // In a balanced RB tree, the black-depth (number of black nodes) from root to
  3117. // leaves is equal on both sides. This function verifies that or asserts.
  3118. t.prototype.check = function() {
  3119. if (this.isRed() && this.left.isRed()) throw q();
  3120. if (this.right.isRed()) throw q();
  3121. var t = this.left.check();
  3122. if (t !== this.right.check()) throw q();
  3123. return t + (this.isRed() ? 0 : 1);
  3124. }, t;
  3125. }();
  3126. // end SortedMap
  3127. // An iterator over an LLRBNode.
  3128. // end LLRBNode
  3129. // Empty node is shared between all LLRB trees.
  3130. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3131. Xe.EMPTY = null, Xe.RED = !0, Xe.BLACK = !1,
  3132. // end LLRBEmptyNode
  3133. Xe.EMPTY = new (/** @class */ function() {
  3134. function t() {
  3135. this.size = 0;
  3136. }
  3137. return Object.defineProperty(t.prototype, "key", {
  3138. get: function() {
  3139. throw q();
  3140. },
  3141. enumerable: !1,
  3142. configurable: !0
  3143. }), Object.defineProperty(t.prototype, "value", {
  3144. get: function() {
  3145. throw q();
  3146. },
  3147. enumerable: !1,
  3148. configurable: !0
  3149. }), Object.defineProperty(t.prototype, "color", {
  3150. get: function() {
  3151. throw q();
  3152. },
  3153. enumerable: !1,
  3154. configurable: !0
  3155. }), Object.defineProperty(t.prototype, "left", {
  3156. get: function() {
  3157. throw q();
  3158. },
  3159. enumerable: !1,
  3160. configurable: !0
  3161. }), Object.defineProperty(t.prototype, "right", {
  3162. get: function() {
  3163. throw q();
  3164. },
  3165. enumerable: !1,
  3166. configurable: !0
  3167. }),
  3168. // Returns a copy of the current node.
  3169. t.prototype.copy = function(t, e, n, r, i) {
  3170. return this;
  3171. },
  3172. // Returns a copy of the tree, with the specified key/value added.
  3173. t.prototype.insert = function(t, e, n) {
  3174. return new Xe(t, e);
  3175. },
  3176. // Returns a copy of the tree, with the specified key removed.
  3177. t.prototype.remove = function(t, e) {
  3178. return this;
  3179. }, t.prototype.isEmpty = function() {
  3180. return !0;
  3181. }, t.prototype.inorderTraversal = function(t) {
  3182. return !1;
  3183. }, t.prototype.reverseTraversal = function(t) {
  3184. return !1;
  3185. }, t.prototype.minKey = function() {
  3186. return null;
  3187. }, t.prototype.maxKey = function() {
  3188. return null;
  3189. }, t.prototype.isRed = function() {
  3190. return !1;
  3191. },
  3192. // For testing.
  3193. t.prototype.checkMaxDepth = function() {
  3194. return !0;
  3195. }, t.prototype.check = function() {
  3196. return 0;
  3197. }, t;
  3198. }());
  3199. /**
  3200. * @license
  3201. * Copyright 2017 Google LLC
  3202. *
  3203. * Licensed under the Apache License, Version 2.0 (the "License");
  3204. * you may not use this file except in compliance with the License.
  3205. * You may obtain a copy of the License at
  3206. *
  3207. * http://www.apache.org/licenses/LICENSE-2.0
  3208. *
  3209. * Unless required by applicable law or agreed to in writing, software
  3210. * distributed under the License is distributed on an "AS IS" BASIS,
  3211. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3212. * See the License for the specific language governing permissions and
  3213. * limitations under the License.
  3214. */
  3215. /**
  3216. * SortedSet is an immutable (copy-on-write) collection that holds elements
  3217. * in order specified by the provided comparator.
  3218. *
  3219. * NOTE: if provided comparator returns 0 for two elements, we consider them to
  3220. * be equal!
  3221. */
  3222. var Ze = /** @class */ function() {
  3223. function t(t) {
  3224. this.comparator = t, this.data = new He(this.comparator);
  3225. }
  3226. return t.prototype.has = function(t) {
  3227. return null !== this.data.get(t);
  3228. }, t.prototype.first = function() {
  3229. return this.data.minKey();
  3230. }, t.prototype.last = function() {
  3231. return this.data.maxKey();
  3232. }, Object.defineProperty(t.prototype, "size", {
  3233. get: function() {
  3234. return this.data.size;
  3235. },
  3236. enumerable: !1,
  3237. configurable: !0
  3238. }), t.prototype.indexOf = function(t) {
  3239. return this.data.indexOf(t);
  3240. },
  3241. /** Iterates elements in order defined by "comparator" */ t.prototype.forEach = function(t) {
  3242. this.data.inorderTraversal((function(e, n) {
  3243. return t(e), !1;
  3244. }));
  3245. },
  3246. /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */ t.prototype.forEachInRange = function(t, e) {
  3247. for (var n = this.data.getIteratorFrom(t[0]); n.hasNext(); ) {
  3248. var r = n.getNext();
  3249. if (this.comparator(r.key, t[1]) >= 0) return;
  3250. e(r.key);
  3251. }
  3252. },
  3253. /**
  3254. * Iterates over `elem`s such that: start &lt;= elem until false is returned.
  3255. */
  3256. t.prototype.forEachWhile = function(t, e) {
  3257. var n;
  3258. for (n = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); n.hasNext(); ) if (!t(n.getNext().key)) return;
  3259. },
  3260. /** Finds the least element greater than or equal to `elem`. */ t.prototype.firstAfterOrEqual = function(t) {
  3261. var e = this.data.getIteratorFrom(t);
  3262. return e.hasNext() ? e.getNext().key : null;
  3263. }, t.prototype.getIterator = function() {
  3264. return new Je(this.data.getIterator());
  3265. }, t.prototype.getIteratorFrom = function(t) {
  3266. return new Je(this.data.getIteratorFrom(t));
  3267. },
  3268. /** Inserts or updates an element */ t.prototype.add = function(t) {
  3269. return this.copy(this.data.remove(t).insert(t, !0));
  3270. },
  3271. /** Deletes an element */ t.prototype.delete = function(t) {
  3272. return this.has(t) ? this.copy(this.data.remove(t)) : this;
  3273. }, t.prototype.isEmpty = function() {
  3274. return this.data.isEmpty();
  3275. }, t.prototype.unionWith = function(t) {
  3276. var e = this;
  3277. // Make sure `result` always refers to the larger one of the two sets.
  3278. return e.size < t.size && (e = t, t = this), t.forEach((function(t) {
  3279. e = e.add(t);
  3280. })), e;
  3281. }, t.prototype.isEqual = function(e) {
  3282. if (!(e instanceof t)) return !1;
  3283. if (this.size !== e.size) return !1;
  3284. for (var n = this.data.getIterator(), r = e.data.getIterator(); n.hasNext(); ) {
  3285. var i = n.getNext().key, o = r.getNext().key;
  3286. if (0 !== this.comparator(i, o)) return !1;
  3287. }
  3288. return !0;
  3289. }, t.prototype.toArray = function() {
  3290. var t = [];
  3291. return this.forEach((function(e) {
  3292. t.push(e);
  3293. })), t;
  3294. }, t.prototype.toString = function() {
  3295. var t = [];
  3296. return this.forEach((function(e) {
  3297. return t.push(e);
  3298. })), "SortedSet(" + t.toString() + ")";
  3299. }, t.prototype.copy = function(e) {
  3300. var n = new t(this.comparator);
  3301. return n.data = e, n;
  3302. }, t;
  3303. }(), Je = /** @class */ function() {
  3304. function t(t) {
  3305. this.iter = t;
  3306. }
  3307. return t.prototype.getNext = function() {
  3308. return this.iter.getNext().key;
  3309. }, t.prototype.hasNext = function() {
  3310. return this.iter.hasNext();
  3311. }, t;
  3312. }();
  3313. /**
  3314. * Compares two sorted sets for equality using their natural ordering. The
  3315. * method computes the intersection and invokes `onAdd` for every element that
  3316. * is in `after` but not `before`. `onRemove` is invoked for every element in
  3317. * `before` but missing from `after`.
  3318. *
  3319. * The method creates a copy of both `before` and `after` and runs in O(n log
  3320. * n), where n is the size of the two lists.
  3321. *
  3322. * @param before - The elements that exist in the original set.
  3323. * @param after - The elements to diff against the original set.
  3324. * @param comparator - The comparator for the elements in before and after.
  3325. * @param onAdd - A function to invoke for every element that is part of `
  3326. * after` but not `before`.
  3327. * @param onRemove - A function to invoke for every element that is part of
  3328. * `before` but not `after`.
  3329. */
  3330. /**
  3331. * Returns the next element from the iterator or `undefined` if none available.
  3332. */
  3333. function $e(t) {
  3334. return t.hasNext() ? t.getNext() : void 0;
  3335. }
  3336. /**
  3337. * @license
  3338. * Copyright 2020 Google LLC
  3339. *
  3340. * Licensed under the Apache License, Version 2.0 (the "License");
  3341. * you may not use this file except in compliance with the License.
  3342. * You may obtain a copy of the License at
  3343. *
  3344. * http://www.apache.org/licenses/LICENSE-2.0
  3345. *
  3346. * Unless required by applicable law or agreed to in writing, software
  3347. * distributed under the License is distributed on an "AS IS" BASIS,
  3348. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3349. * See the License for the specific language governing permissions and
  3350. * limitations under the License.
  3351. */
  3352. /**
  3353. * Provides a set of fields that can be used to partially patch a document.
  3354. * FieldMask is used in conjunction with ObjectValue.
  3355. * Examples:
  3356. * foo - Overwrites foo entirely with the provided value. If foo is not
  3357. * present in the companion ObjectValue, the field is deleted.
  3358. * foo.bar - Overwrites only the field bar of the object foo.
  3359. * If foo is not an object, foo is replaced with an object
  3360. * containing foo
  3361. */ var tn = /** @class */ function() {
  3362. function t(t) {
  3363. this.fields = t,
  3364. // TODO(dimond): validation of FieldMask
  3365. // Sort the field mask to support `FieldMask.isEqual()` and assert below.
  3366. t.sort(ht.comparator);
  3367. }
  3368. return t.empty = function() {
  3369. return new t([]);
  3370. },
  3371. /**
  3372. * Returns a new FieldMask object that is the result of adding all the given
  3373. * fields paths to this field mask.
  3374. */
  3375. t.prototype.unionWith = function(e) {
  3376. for (var n = new Ze(ht.comparator), r = 0, i = this.fields; r < i.length; r++) {
  3377. var o = i[r];
  3378. n = n.add(o);
  3379. }
  3380. for (var u = 0, a = e; u < a.length; u++) {
  3381. var s = a[u];
  3382. n = n.add(s);
  3383. }
  3384. return new t(n.toArray());
  3385. },
  3386. /**
  3387. * Verifies that `fieldPath` is included by at least one field in this field
  3388. * mask.
  3389. *
  3390. * This is an O(n) operation, where `n` is the size of the field mask.
  3391. */
  3392. t.prototype.covers = function(t) {
  3393. for (var e = 0, n = this.fields; e < n.length; e++) {
  3394. if (n[e].isPrefixOf(t)) return !0;
  3395. }
  3396. return !1;
  3397. }, t.prototype.isEqual = function(t) {
  3398. return it(this.fields, t.fields, (function(t, e) {
  3399. return t.isEqual(e);
  3400. }));
  3401. }, t;
  3402. }(), en = /** @class */ function() {
  3403. function t(t) {
  3404. this.value = t;
  3405. }
  3406. return t.empty = function() {
  3407. return new t({
  3408. mapValue: {}
  3409. });
  3410. },
  3411. /**
  3412. * Returns the value at the given path or null.
  3413. *
  3414. * @param path - the path to search
  3415. * @returns The value at the path or null if the path is not set.
  3416. */
  3417. t.prototype.field = function(t) {
  3418. if (t.isEmpty()) return this.value;
  3419. for (var e = this.value, n = 0; n < t.length - 1; ++n) if (!me(e = (e.mapValue.fields || {})[t.get(n)])) return null;
  3420. return (e = (e.mapValue.fields || {})[t.lastSegment()]) || null;
  3421. },
  3422. /**
  3423. * Sets the field to the provided value.
  3424. *
  3425. * @param path - The field path to set.
  3426. * @param value - The value to set.
  3427. */
  3428. t.prototype.set = function(t, e) {
  3429. this.getFieldsMap(t.popLast())[t.lastSegment()] = ge(e);
  3430. },
  3431. /**
  3432. * Sets the provided fields to the provided values.
  3433. *
  3434. * @param data - A map of fields to values (or null for deletes).
  3435. */
  3436. t.prototype.setAll = function(t) {
  3437. var e = this, n = ht.emptyPath(), r = {}, i = [];
  3438. t.forEach((function(t, o) {
  3439. if (!n.isImmediateParentOf(o)) {
  3440. // Insert the accumulated changes at this parent location
  3441. var u = e.getFieldsMap(n);
  3442. e.applyChanges(u, r, i), r = {}, i = [], n = o.popLast();
  3443. }
  3444. t ? r[o.lastSegment()] = ge(t) : i.push(o.lastSegment());
  3445. }));
  3446. var o = this.getFieldsMap(n);
  3447. this.applyChanges(o, r, i);
  3448. },
  3449. /**
  3450. * Removes the field at the specified path. If there is no field at the
  3451. * specified path, nothing is changed.
  3452. *
  3453. * @param path - The field path to remove.
  3454. */
  3455. t.prototype.delete = function(t) {
  3456. var e = this.field(t.popLast());
  3457. me(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()];
  3458. }, t.prototype.isEqual = function(t) {
  3459. return ue(this.value, t.value);
  3460. },
  3461. /**
  3462. * Returns the map that contains the leaf element of `path`. If the parent
  3463. * entry does not yet exist, or if it is not a map, a new map will be created.
  3464. */
  3465. t.prototype.getFieldsMap = function(t) {
  3466. var e = this.value;
  3467. e.mapValue.fields || (e.mapValue = {
  3468. fields: {}
  3469. });
  3470. for (var n = 0; n < t.length; ++n) {
  3471. var r = e.mapValue.fields[t.get(n)];
  3472. me(r) && r.mapValue.fields || (r = {
  3473. mapValue: {
  3474. fields: {}
  3475. }
  3476. }, e.mapValue.fields[t.get(n)] = r), e = r;
  3477. }
  3478. return e.mapValue.fields;
  3479. },
  3480. /**
  3481. * Modifies `fieldsMap` by adding, replacing or deleting the specified
  3482. * entries.
  3483. */
  3484. t.prototype.applyChanges = function(t, e, n) {
  3485. Kt(e, (function(e, n) {
  3486. return t[e] = n;
  3487. }));
  3488. for (var r = 0, i = n; r < i.length; r++) {
  3489. var o = i[r];
  3490. delete t[o];
  3491. }
  3492. }, t.prototype.clone = function() {
  3493. return new t(ge(this.value));
  3494. }, t;
  3495. }();
  3496. /**
  3497. * @license
  3498. * Copyright 2017 Google LLC
  3499. *
  3500. * Licensed under the Apache License, Version 2.0 (the "License");
  3501. * you may not use this file except in compliance with the License.
  3502. * You may obtain a copy of the License at
  3503. *
  3504. * http://www.apache.org/licenses/LICENSE-2.0
  3505. *
  3506. * Unless required by applicable law or agreed to in writing, software
  3507. * distributed under the License is distributed on an "AS IS" BASIS,
  3508. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3509. * See the License for the specific language governing permissions and
  3510. * limitations under the License.
  3511. */
  3512. /**
  3513. * An ObjectValue represents a MapValue in the Firestore Proto and offers the
  3514. * ability to add and remove fields (via the ObjectValueBuilder).
  3515. */
  3516. /**
  3517. * Returns a FieldMask built from all fields in a MapValue.
  3518. */
  3519. function nn(t) {
  3520. var e = [];
  3521. return Kt(t.fields, (function(t, n) {
  3522. var r = new ht([ t ]);
  3523. if (me(n)) {
  3524. var i = nn(n.mapValue).fields;
  3525. if (0 === i.length)
  3526. // Preserve the empty map by adding it to the FieldMask.
  3527. e.push(r); else
  3528. // For nested and non-empty ObjectValues, add the FieldPath of the
  3529. // leaf nodes.
  3530. for (var o = 0, u = i; o < u.length; o++) {
  3531. var a = u[o];
  3532. e.push(r.child(a));
  3533. }
  3534. } else
  3535. // For nested and non-empty ObjectValues, add the FieldPath of the leaf
  3536. // nodes.
  3537. e.push(r);
  3538. })), new tn(e)
  3539. /**
  3540. * @license
  3541. * Copyright 2017 Google LLC
  3542. *
  3543. * Licensed under the Apache License, Version 2.0 (the "License");
  3544. * you may not use this file except in compliance with the License.
  3545. * You may obtain a copy of the License at
  3546. *
  3547. * http://www.apache.org/licenses/LICENSE-2.0
  3548. *
  3549. * Unless required by applicable law or agreed to in writing, software
  3550. * distributed under the License is distributed on an "AS IS" BASIS,
  3551. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3552. * See the License for the specific language governing permissions and
  3553. * limitations under the License.
  3554. */
  3555. /**
  3556. * Represents a document in Firestore with a key, version, data and whether it
  3557. * has local mutations applied to it.
  3558. *
  3559. * Documents can transition between states via `convertToFoundDocument()`,
  3560. * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
  3561. * not transition to one of these states even after all mutations have been
  3562. * applied, `isValidDocument()` returns false and the document should be removed
  3563. * from all views.
  3564. */;
  3565. }
  3566. var rn = /** @class */ function() {
  3567. function t(t, e, n, r, i, o, u) {
  3568. this.key = t, this.documentType = e, this.version = n, this.readTime = r, this.createTime = i,
  3569. this.data = o, this.documentState = u
  3570. /**
  3571. * Creates a document with no known version or data, but which can serve as
  3572. * base document for mutations.
  3573. */;
  3574. }
  3575. return t.newInvalidDocument = function(e) {
  3576. return new t(e, 0 /* DocumentType.INVALID */ ,
  3577. /* version */ at.min(),
  3578. /* readTime */ at.min(),
  3579. /* createTime */ at.min(), en.empty(), 0 /* DocumentState.SYNCED */);
  3580. },
  3581. /**
  3582. * Creates a new document that is known to exist with the given data at the
  3583. * given version.
  3584. */
  3585. t.newFoundDocument = function(e, n, r, i) {
  3586. return new t(e, 1 /* DocumentType.FOUND_DOCUMENT */ ,
  3587. /* version */ n,
  3588. /* readTime */ at.min(),
  3589. /* createTime */ r, i, 0 /* DocumentState.SYNCED */);
  3590. },
  3591. /** Creates a new document that is known to not exist at the given version. */ t.newNoDocument = function(e, n) {
  3592. return new t(e, 2 /* DocumentType.NO_DOCUMENT */ ,
  3593. /* version */ n,
  3594. /* readTime */ at.min(),
  3595. /* createTime */ at.min(), en.empty(), 0 /* DocumentState.SYNCED */);
  3596. },
  3597. /**
  3598. * Creates a new document that is known to exist at the given version but
  3599. * whose data is not known (e.g. a document that was updated without a known
  3600. * base document).
  3601. */
  3602. t.newUnknownDocument = function(e, n) {
  3603. return new t(e, 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  3604. /* version */ n,
  3605. /* readTime */ at.min(),
  3606. /* createTime */ at.min(), en.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);
  3607. },
  3608. /**
  3609. * Changes the document type to indicate that it exists and that its version
  3610. * and data are known.
  3611. */
  3612. t.prototype.convertToFoundDocument = function(t, e) {
  3613. // If a document is switching state from being an invalid or deleted
  3614. // document to a valid (FOUND_DOCUMENT) document, either due to receiving an
  3615. // update from Watch or due to applying a local set mutation on top
  3616. // of a deleted document, our best guess about its createTime would be the
  3617. // version at which the document transitioned to a FOUND_DOCUMENT.
  3618. return !this.createTime.isEqual(at.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t),
  3619. this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e,
  3620. this.documentState = 0 /* DocumentState.SYNCED */ , this;
  3621. },
  3622. /**
  3623. * Changes the document type to indicate that it doesn't exist at the given
  3624. * version.
  3625. */
  3626. t.prototype.convertToNoDocument = function(t) {
  3627. return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ ,
  3628. this.data = en.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , this;
  3629. },
  3630. /**
  3631. * Changes the document type to indicate that it exists at a given version but
  3632. * that its data is not known (e.g. a document that was updated without a known
  3633. * base document).
  3634. */
  3635. t.prototype.convertToUnknownDocument = function(t) {
  3636. return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  3637. this.data = en.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ ,
  3638. this;
  3639. }, t.prototype.setHasCommittedMutations = function() {
  3640. return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;
  3641. }, t.prototype.setHasLocalMutations = function() {
  3642. return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = at.min(),
  3643. this;
  3644. }, t.prototype.setReadTime = function(t) {
  3645. return this.readTime = t, this;
  3646. }, Object.defineProperty(t.prototype, "hasLocalMutations", {
  3647. get: function() {
  3648. return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;
  3649. },
  3650. enumerable: !1,
  3651. configurable: !0
  3652. }), Object.defineProperty(t.prototype, "hasCommittedMutations", {
  3653. get: function() {
  3654. return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;
  3655. },
  3656. enumerable: !1,
  3657. configurable: !0
  3658. }), Object.defineProperty(t.prototype, "hasPendingWrites", {
  3659. get: function() {
  3660. return this.hasLocalMutations || this.hasCommittedMutations;
  3661. },
  3662. enumerable: !1,
  3663. configurable: !0
  3664. }), t.prototype.isValidDocument = function() {
  3665. return 0 /* DocumentType.INVALID */ !== this.documentType;
  3666. }, t.prototype.isFoundDocument = function() {
  3667. return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;
  3668. }, t.prototype.isNoDocument = function() {
  3669. return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;
  3670. }, t.prototype.isUnknownDocument = function() {
  3671. return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;
  3672. }, t.prototype.isEqual = function(e) {
  3673. return e instanceof t && this.key.isEqual(e.key) && this.version.isEqual(e.version) && this.documentType === e.documentType && this.documentState === e.documentState && this.data.isEqual(e.data);
  3674. }, t.prototype.mutableCopy = function() {
  3675. return new t(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);
  3676. }, t.prototype.toString = function() {
  3677. return "Document(".concat(this.key, ", ").concat(this.version, ", ").concat(JSON.stringify(this.data.value), ", {createTime: ").concat(this.createTime, "}), {documentType: ").concat(this.documentType, "}), {documentState: ").concat(this.documentState, "})");
  3678. }, t;
  3679. }(), on = function(t, e, n, r, i, o, u) {
  3680. void 0 === e && (e = null), void 0 === n && (n = []), void 0 === r && (r = []),
  3681. void 0 === i && (i = null), void 0 === o && (o = null), void 0 === u && (u = null),
  3682. this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = r, this.limit = i,
  3683. this.startAt = o, this.endAt = u, this.ft = null;
  3684. };
  3685. /**
  3686. * Compares the value for field `field` in the provided documents. Throws if
  3687. * the field does not exist in both documents.
  3688. */
  3689. /**
  3690. * @license
  3691. * Copyright 2019 Google LLC
  3692. *
  3693. * Licensed under the Apache License, Version 2.0 (the "License");
  3694. * you may not use this file except in compliance with the License.
  3695. * You may obtain a copy of the License at
  3696. *
  3697. * http://www.apache.org/licenses/LICENSE-2.0
  3698. *
  3699. * Unless required by applicable law or agreed to in writing, software
  3700. * distributed under the License is distributed on an "AS IS" BASIS,
  3701. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3702. * See the License for the specific language governing permissions and
  3703. * limitations under the License.
  3704. */
  3705. // Visible for testing
  3706. /**
  3707. * Initializes a Target with a path and optional additional query constraints.
  3708. * Path must currently be empty if this is a collection group query.
  3709. *
  3710. * NOTE: you should always construct `Target` from `Query.toTarget` instead of
  3711. * using this factory method, because `Query` provides an implicit `orderBy`
  3712. * property.
  3713. */
  3714. function un(t, e, n, r, i, o, u) {
  3715. return void 0 === e && (e = null), void 0 === n && (n = []), void 0 === r && (r = []),
  3716. void 0 === i && (i = null), void 0 === o && (o = null), void 0 === u && (u = null),
  3717. new on(t, e, n, r, i, o, u);
  3718. }
  3719. function an(t) {
  3720. var e = G(t);
  3721. if (null === e.ft) {
  3722. var n = e.path.canonicalString();
  3723. null !== e.collectionGroup && (n += "|cg:" + e.collectionGroup), n += "|f:", n += e.filters.map((function(t) {
  3724. return Re(t);
  3725. })).join(","), n += "|ob:", n += e.orderBy.map((function(t) {
  3726. return function(t) {
  3727. // TODO(b/29183165): Make this collision robust.
  3728. return t.field.canonicalString() + t.dir;
  3729. }(t);
  3730. })).join(","), Qt(e.limit) || (n += "|l:", n += e.limit), e.startAt && (n += "|lb:",
  3731. n += e.startAt.inclusive ? "b:" : "a:", n += e.startAt.position.map((function(t) {
  3732. return le(t);
  3733. })).join(",")), e.endAt && (n += "|ub:", n += e.endAt.inclusive ? "a:" : "b:", n += e.endAt.position.map((function(t) {
  3734. return le(t);
  3735. })).join(",")), e.ft = n;
  3736. }
  3737. return e.ft;
  3738. }
  3739. function sn(t, e) {
  3740. if (t.limit !== e.limit) return !1;
  3741. if (t.orderBy.length !== e.orderBy.length) return !1;
  3742. for (var n = 0; n < t.orderBy.length; n++) if (!We(t.orderBy[n], e.orderBy[n])) return !1;
  3743. if (t.filters.length !== e.filters.length) return !1;
  3744. for (var r = 0; r < t.filters.length; r++) if (!Ve(t.filters[r], e.filters[r])) return !1;
  3745. return t.collectionGroup === e.collectionGroup && !!t.path.isEqual(e.path) && !!De(t.startAt, e.startAt) && De(t.endAt, e.endAt);
  3746. }
  3747. function cn(t) {
  3748. return ft.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
  3749. }
  3750. /** Returns the field filters that target the given field path. */ function ln(t, e) {
  3751. return t.filters.filter((function(t) {
  3752. return t instanceof Ae && t.field.isEqual(e);
  3753. }));
  3754. }
  3755. /**
  3756. * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
  3757. * filters. Returns `null` if there are no such filters.
  3758. */
  3759. /**
  3760. * Returns the value to use as the lower bound for ascending index segment at
  3761. * the provided `fieldPath` (or the upper bound for an descending segment).
  3762. */ function hn(t, e, n) {
  3763. // Process all filters to find a value for the current field segment
  3764. for (var r = ie, i = !0, o = 0, u = ln(t, e); o < u.length; o++) {
  3765. var a = u[o], s = ie, c = !0;
  3766. switch (a.op) {
  3767. case "<" /* Operator.LESS_THAN */ :
  3768. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  3769. s = be(a.value);
  3770. break;
  3771. case "==" /* Operator.EQUAL */ :
  3772. case "in" /* Operator.IN */ :
  3773. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  3774. s = a.value;
  3775. break;
  3776. case ">" /* Operator.GREATER_THAN */ :
  3777. s = a.value, c = !1;
  3778. break;
  3779. case "!=" /* Operator.NOT_EQUAL */ :
  3780. case "not-in" /* Operator.NOT_IN */ :
  3781. s = ie;
  3782. // Remaining filters cannot be used as lower bounds.
  3783. }
  3784. Te({
  3785. value: r,
  3786. inclusive: i
  3787. }, {
  3788. value: s,
  3789. inclusive: c
  3790. }) < 0 && (r = s, i = c);
  3791. }
  3792. // If there is an additional bound, compare the values against the existing
  3793. // range to see if we can narrow the scope.
  3794. if (null !== n) for (var l = 0; l < t.orderBy.length; ++l) if (t.orderBy[l].field.isEqual(e)) {
  3795. var h = n.position[l];
  3796. Te({
  3797. value: r,
  3798. inclusive: i
  3799. }, {
  3800. value: h,
  3801. inclusive: n.inclusive
  3802. }) < 0 && (r = h, i = n.inclusive);
  3803. break;
  3804. }
  3805. return {
  3806. value: r,
  3807. inclusive: i
  3808. };
  3809. }
  3810. /**
  3811. * Returns the value to use as the upper bound for ascending index segment at
  3812. * the provided `fieldPath` (or the lower bound for a descending segment).
  3813. */ function fn(t, e, n) {
  3814. // Process all filters to find a value for the current field segment
  3815. for (var r = re, i = !0, o = 0, u = ln(t, e); o < u.length; o++) {
  3816. var a = u[o], s = re, c = !0;
  3817. switch (a.op) {
  3818. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  3819. case ">" /* Operator.GREATER_THAN */ :
  3820. s = Ie(a.value), c = !1;
  3821. break;
  3822. case "==" /* Operator.EQUAL */ :
  3823. case "in" /* Operator.IN */ :
  3824. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  3825. s = a.value;
  3826. break;
  3827. case "<" /* Operator.LESS_THAN */ :
  3828. s = a.value, c = !1;
  3829. break;
  3830. case "!=" /* Operator.NOT_EQUAL */ :
  3831. case "not-in" /* Operator.NOT_IN */ :
  3832. s = re;
  3833. // Remaining filters cannot be used as upper bounds.
  3834. }
  3835. Ee({
  3836. value: r,
  3837. inclusive: i
  3838. }, {
  3839. value: s,
  3840. inclusive: c
  3841. }) > 0 && (r = s, i = c);
  3842. }
  3843. // If there is an additional bound, compare the values against the existing
  3844. // range to see if we can narrow the scope.
  3845. if (null !== n) for (var l = 0; l < t.orderBy.length; ++l) if (t.orderBy[l].field.isEqual(e)) {
  3846. var h = n.position[l];
  3847. Ee({
  3848. value: r,
  3849. inclusive: i
  3850. }, {
  3851. value: h,
  3852. inclusive: n.inclusive
  3853. }) > 0 && (r = h, i = n.inclusive);
  3854. break;
  3855. }
  3856. return {
  3857. value: r,
  3858. inclusive: i
  3859. };
  3860. }
  3861. /** Returns the number of segments of a perfect index for this target. */
  3862. /**
  3863. * @license
  3864. * Copyright 2017 Google LLC
  3865. *
  3866. * Licensed under the Apache License, Version 2.0 (the "License");
  3867. * you may not use this file except in compliance with the License.
  3868. * You may obtain a copy of the License at
  3869. *
  3870. * http://www.apache.org/licenses/LICENSE-2.0
  3871. *
  3872. * Unless required by applicable law or agreed to in writing, software
  3873. * distributed under the License is distributed on an "AS IS" BASIS,
  3874. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3875. * See the License for the specific language governing permissions and
  3876. * limitations under the License.
  3877. */
  3878. /**
  3879. * Query encapsulates all the query attributes we support in the SDK. It can
  3880. * be run against the LocalStore, as well as be converted to a `Target` to
  3881. * query the RemoteStore results.
  3882. *
  3883. * Visible for testing.
  3884. */ var dn =
  3885. /**
  3886. * Initializes a Query with a path and optional additional query constraints.
  3887. * Path must currently be empty if this is a collection group query.
  3888. */
  3889. function(t, e, n, r, i, o /* LimitType.First */ , u, a) {
  3890. void 0 === e && (e = null), void 0 === n && (n = []), void 0 === r && (r = []),
  3891. void 0 === i && (i = null), void 0 === o && (o = "F"), void 0 === u && (u = null),
  3892. void 0 === a && (a = null), this.path = t, this.collectionGroup = e, this.explicitOrderBy = n,
  3893. this.filters = r, this.limit = i, this.limitType = o, this.startAt = u, this.endAt = a,
  3894. this.dt = null,
  3895. // The corresponding `Target` of this `Query` instance.
  3896. this._t = null, this.startAt, this.endAt;
  3897. };
  3898. /** Creates a new Query instance with the options provided. */ function pn(t, e, n, r, i, o, u, a) {
  3899. return new dn(t, e, n, r, i, o, u, a);
  3900. }
  3901. /** Creates a new Query for a query that matches all documents at `path` */ function yn(t) {
  3902. return new dn(t);
  3903. }
  3904. /**
  3905. * Helper to convert a collection group query into a collection query at a
  3906. * specific path. This is used when executing collection group queries, since
  3907. * we have to split the query into a set of collection queries at multiple
  3908. * paths.
  3909. */
  3910. /**
  3911. * Returns true if this query does not specify any query constraints that
  3912. * could remove results.
  3913. */ function vn(t) {
  3914. return 0 === t.filters.length && null === t.limit && null == t.startAt && null == t.endAt && (0 === t.explicitOrderBy.length || 1 === t.explicitOrderBy.length && t.explicitOrderBy[0].field.isKeyField());
  3915. }
  3916. function mn(t) {
  3917. return t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null;
  3918. }
  3919. function gn(t) {
  3920. for (var e = 0, n = t.filters; e < n.length; e++) {
  3921. var r = n[e].getFirstInequalityField();
  3922. if (null !== r) return r;
  3923. }
  3924. return null;
  3925. }
  3926. /**
  3927. * Creates a new Query for a collection group query that matches all documents
  3928. * within the provided collection group.
  3929. */
  3930. /**
  3931. * Returns whether the query matches a collection group rather than a specific
  3932. * collection.
  3933. */ function wn(t) {
  3934. return null !== t.collectionGroup;
  3935. }
  3936. /**
  3937. * Returns the implicit order by constraint that is used to execute the Query,
  3938. * which can be different from the order by constraints the user provided (e.g.
  3939. * the SDK and backend always orders by `__name__`).
  3940. */ function bn(t) {
  3941. var e = G(t);
  3942. if (null === e.dt) {
  3943. e.dt = [];
  3944. var n = gn(e), r = mn(e);
  3945. if (null !== n && null === r)
  3946. // In order to implicitly add key ordering, we must also add the
  3947. // inequality filter field for it to be a valid query.
  3948. // Note that the default inequality field and key ordering is ascending.
  3949. n.isKeyField() || e.dt.push(new ze(n)), e.dt.push(new ze(ht.keyField(), "asc" /* Direction.ASCENDING */)); else {
  3950. for (var i = !1, o = 0, u = e.explicitOrderBy; o < u.length; o++) {
  3951. var a = u[o];
  3952. e.dt.push(a), a.field.isKeyField() && (i = !0);
  3953. }
  3954. if (!i) {
  3955. // The order of the implicit key ordering always matches the last
  3956. // explicit order by
  3957. var s = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */;
  3958. e.dt.push(new ze(ht.keyField(), s));
  3959. }
  3960. }
  3961. }
  3962. return e.dt;
  3963. }
  3964. /**
  3965. * Converts this `Query` instance to it's corresponding `Target` representation.
  3966. */ function In(t) {
  3967. var e = G(t);
  3968. if (!e._t) if ("F" /* LimitType.First */ === e.limitType) e._t = un(e.path, e.collectionGroup, bn(e), e.filters, e.limit, e.startAt, e.endAt); else {
  3969. for (
  3970. // Flip the orderBy directions since we want the last results
  3971. var n = [], r = 0, i = bn(e); r < i.length; r++) {
  3972. var o = i[r], u = "desc" /* Direction.DESCENDING */ === o.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */;
  3973. n.push(new ze(o.field, u));
  3974. }
  3975. // We need to swap the cursors to match the now-flipped query ordering.
  3976. var a = e.endAt ? new Se(e.endAt.position, e.endAt.inclusive) : null, s = e.startAt ? new Se(e.startAt.position, e.startAt.inclusive) : null;
  3977. // Now return as a LimitType.First query.
  3978. e._t = un(e.path, e.collectionGroup, n, e.filters, e.limit, a, s);
  3979. }
  3980. return e._t;
  3981. }
  3982. function Tn(t, e) {
  3983. e.getFirstInequalityField(), gn(t);
  3984. var n = t.filters.concat([ e ]);
  3985. return new dn(t.path, t.collectionGroup, t.explicitOrderBy.slice(), n, t.limit, t.limitType, t.startAt, t.endAt);
  3986. }
  3987. function En(t, e, n) {
  3988. return new dn(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, n, t.startAt, t.endAt);
  3989. }
  3990. function Sn(t, e) {
  3991. return sn(In(t), In(e)) && t.limitType === e.limitType;
  3992. }
  3993. // TODO(b/29183165): This is used to get a unique string from a query to, for
  3994. // example, use as a dictionary key, but the implementation is subject to
  3995. // collisions. Make it collision-free.
  3996. function _n(t) {
  3997. return "".concat(an(In(t)), "|lt:").concat(t.limitType);
  3998. }
  3999. function Dn(t) {
  4000. return "Query(target=".concat(function(t) {
  4001. var e = t.path.canonicalString();
  4002. return null !== t.collectionGroup && (e += " collectionGroup=" + t.collectionGroup),
  4003. t.filters.length > 0 && (e += ", filters: [".concat(t.filters.map((function(t) {
  4004. return Le(t);
  4005. })).join(", "), "]")), Qt(t.limit) || (e += ", limit: " + t.limit), t.orderBy.length > 0 && (e += ", orderBy: [".concat(t.orderBy.map((function(t) {
  4006. return function(t) {
  4007. return "".concat(t.field.canonicalString(), " (").concat(t.dir, ")");
  4008. }(t);
  4009. })).join(", "), "]")), t.startAt && (e += ", startAt: ", e += t.startAt.inclusive ? "b:" : "a:",
  4010. e += t.startAt.position.map((function(t) {
  4011. return le(t);
  4012. })).join(",")), t.endAt && (e += ", endAt: ", e += t.endAt.inclusive ? "a:" : "b:",
  4013. e += t.endAt.position.map((function(t) {
  4014. return le(t);
  4015. })).join(",")), "Target(".concat(e, ")");
  4016. }(In(t)), "; limitType=").concat(t.limitType, ")");
  4017. }
  4018. /** Returns whether `doc` matches the constraints of `query`. */ function xn(t, e) {
  4019. return e.isFoundDocument() && function(t, e) {
  4020. var n = e.key.path;
  4021. return null !== t.collectionGroup ? e.key.hasCollectionId(t.collectionGroup) && t.path.isPrefixOf(n) : ft.isDocumentKey(t.path) ? t.path.isEqual(n) : t.path.isImmediateParentOf(n);
  4022. }(t, e) && function(t, e) {
  4023. // We must use `queryOrderBy()` to get the list of all orderBys (both implicit and explicit).
  4024. // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must
  4025. // be taken into account. For example, the query "a > 1 || b==1" has an implicit "orderBy a" due
  4026. // to the inequality, and is evaluated as "a > 1 orderBy a || b==1 orderBy a".
  4027. // A document with content of {b:1} matches the filters, but does not match the orderBy because
  4028. // it's missing the field 'a'.
  4029. for (var n = 0, r = bn(t); n < r.length; n++) {
  4030. var i = r[n];
  4031. // order by key always matches
  4032. if (!i.field.isKeyField() && null === e.data.field(i.field)) return !1;
  4033. }
  4034. return !0;
  4035. }(t, e) && function(t, e) {
  4036. for (var n = 0, r = t.filters; n < r.length; n++) {
  4037. if (!r[n].matches(e)) return !1;
  4038. }
  4039. return !0;
  4040. }(t, e) && function(t, e) {
  4041. return !(t.startAt &&
  4042. /**
  4043. * Returns true if a document sorts before a bound using the provided sort
  4044. * order.
  4045. */
  4046. !function(t, e, n) {
  4047. var r = _e(t, e, n);
  4048. return t.inclusive ? r <= 0 : r < 0;
  4049. }(t.startAt, bn(t), e)) && !(t.endAt && !function(t, e, n) {
  4050. var r = _e(t, e, n);
  4051. return t.inclusive ? r >= 0 : r > 0;
  4052. }(t.endAt, bn(t), e));
  4053. }(t, e);
  4054. }
  4055. function An(t) {
  4056. return t.collectionGroup || (t.path.length % 2 == 1 ? t.path.lastSegment() : t.path.get(t.path.length - 2));
  4057. }
  4058. /**
  4059. * Returns a new comparator function that can be used to compare two documents
  4060. * based on the Query's ordering constraint.
  4061. */ function Cn(t) {
  4062. return function(e, n) {
  4063. for (var r = !1, i = 0, o = bn(t); i < o.length; i++) {
  4064. var u = o[i], a = Nn(u, e, n);
  4065. if (0 !== a) return a;
  4066. r = r || u.field.isKeyField();
  4067. }
  4068. return 0;
  4069. };
  4070. }
  4071. function Nn(t, e, n) {
  4072. var r = t.field.isKeyField() ? ft.comparator(e.key, n.key) : function(t, e, n) {
  4073. var r = e.data.field(t), i = n.data.field(t);
  4074. return null !== r && null !== i ? se(r, i) : q();
  4075. }(t.field, e, n);
  4076. switch (t.dir) {
  4077. case "asc" /* Direction.ASCENDING */ :
  4078. return r;
  4079. case "desc" /* Direction.DESCENDING */ :
  4080. return -1 * r;
  4081. default:
  4082. return q();
  4083. }
  4084. }
  4085. /**
  4086. * @license
  4087. * Copyright 2020 Google LLC
  4088. *
  4089. * Licensed under the Apache License, Version 2.0 (the "License");
  4090. * you may not use this file except in compliance with the License.
  4091. * You may obtain a copy of the License at
  4092. *
  4093. * http://www.apache.org/licenses/LICENSE-2.0
  4094. *
  4095. * Unless required by applicable law or agreed to in writing, software
  4096. * distributed under the License is distributed on an "AS IS" BASIS,
  4097. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4098. * See the License for the specific language governing permissions and
  4099. * limitations under the License.
  4100. */
  4101. /**
  4102. * Returns an DoubleValue for `value` that is encoded based the serializer's
  4103. * `useProto3Json` setting.
  4104. */ function kn(t, e) {
  4105. if (t.wt) {
  4106. if (isNaN(e)) return {
  4107. doubleValue: "NaN"
  4108. };
  4109. if (e === 1 / 0) return {
  4110. doubleValue: "Infinity"
  4111. };
  4112. if (e === -1 / 0) return {
  4113. doubleValue: "-Infinity"
  4114. };
  4115. }
  4116. return {
  4117. doubleValue: zt(e) ? "-0" : e
  4118. };
  4119. }
  4120. /**
  4121. * Returns an IntegerValue for `value`.
  4122. */ function Fn(t) {
  4123. return {
  4124. integerValue: "" + t
  4125. };
  4126. }
  4127. /**
  4128. * Returns a value for a number that's appropriate to put into a proto.
  4129. * The return value is an IntegerValue if it can safely represent the value,
  4130. * otherwise a DoubleValue is returned.
  4131. */ function On(t, e) {
  4132. return Wt(e) ? Fn(e) : kn(t, e);
  4133. }
  4134. /**
  4135. * @license
  4136. * Copyright 2018 Google LLC
  4137. *
  4138. * Licensed under the Apache License, Version 2.0 (the "License");
  4139. * you may not use this file except in compliance with the License.
  4140. * You may obtain a copy of the License at
  4141. *
  4142. * http://www.apache.org/licenses/LICENSE-2.0
  4143. *
  4144. * Unless required by applicable law or agreed to in writing, software
  4145. * distributed under the License is distributed on an "AS IS" BASIS,
  4146. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4147. * See the License for the specific language governing permissions and
  4148. * limitations under the License.
  4149. */
  4150. /** Used to represent a field transform on a mutation. */ var Rn = function() {
  4151. // Make sure that the structural type of `TransformOperation` is unique.
  4152. // See https://github.com/microsoft/TypeScript/issues/5451
  4153. this._ = void 0;
  4154. };
  4155. /**
  4156. * Computes the local transform result against the provided `previousValue`,
  4157. * optionally using the provided localWriteTime.
  4158. */ function Vn(t, e, n) {
  4159. return t instanceof Pn ? function(t, e) {
  4160. var n = {
  4161. fields: {
  4162. __type__: {
  4163. stringValue: "server_timestamp"
  4164. },
  4165. __local_write_time__: {
  4166. timestampValue: {
  4167. seconds: t.seconds,
  4168. nanos: t.nanoseconds
  4169. }
  4170. }
  4171. }
  4172. };
  4173. return e && (n.fields.__previous_value__ = e), {
  4174. mapValue: n
  4175. };
  4176. }(n, e) : t instanceof qn ? Un(t, e) : t instanceof Bn ? Gn(t, e) : function(t, e) {
  4177. // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit
  4178. // precision and resolves overflows by reducing precision, we do not
  4179. // manually cap overflows at 2^63.
  4180. var n = Ln(t, e), r = jn(n) + jn(t.gt);
  4181. return de(n) && de(t.gt) ? Fn(r) : kn(t.yt, r);
  4182. }(t, e);
  4183. }
  4184. /**
  4185. * Computes a final transform result after the transform has been acknowledged
  4186. * by the server, potentially using the server-provided transformResult.
  4187. */ function Mn(t, e, n) {
  4188. // The server just sends null as the transform result for array operations,
  4189. // so we have to calculate a result the same as we do for local
  4190. // applications.
  4191. return t instanceof qn ? Un(t, e) : t instanceof Bn ? Gn(t, e) : n;
  4192. }
  4193. /**
  4194. * If this transform operation is not idempotent, returns the base value to
  4195. * persist for this transform. If a base value is returned, the transform
  4196. * operation is always applied to this base value, even if document has
  4197. * already been updated.
  4198. *
  4199. * Base values provide consistent behavior for non-idempotent transforms and
  4200. * allow us to return the same latency-compensated value even if the backend
  4201. * has already applied the transform operation. The base value is null for
  4202. * idempotent transforms, as they can be re-played even if the backend has
  4203. * already applied them.
  4204. *
  4205. * @returns a base value to store along with the mutation, or null for
  4206. * idempotent transforms.
  4207. */ function Ln(t, e) {
  4208. return t instanceof Kn ? de(n = e) || function(t) {
  4209. return !!t && "doubleValue" in t;
  4210. }(n) ? e : {
  4211. integerValue: 0
  4212. } : null;
  4213. var n;
  4214. }
  4215. /** Transforms a value into a server-generated timestamp. */ var Pn = /** @class */ function(e) {
  4216. function n() {
  4217. return null !== e && e.apply(this, arguments) || this;
  4218. }
  4219. return t(n, e), n;
  4220. }(Rn), qn = /** @class */ function(e) {
  4221. function n(t) {
  4222. var n = this;
  4223. return (n = e.call(this) || this).elements = t, n;
  4224. }
  4225. return t(n, e), n;
  4226. }(Rn);
  4227. /** Transforms an array value via a union operation. */ function Un(t, e) {
  4228. for (var n = Qn(e), r = function(t) {
  4229. n.some((function(e) {
  4230. return ue(e, t);
  4231. })) || n.push(t);
  4232. }, i = 0, o = t.elements; i < o.length; i++) {
  4233. r(o[i]);
  4234. }
  4235. return {
  4236. arrayValue: {
  4237. values: n
  4238. }
  4239. };
  4240. }
  4241. /** Transforms an array value via a remove operation. */ var Bn = /** @class */ function(e) {
  4242. function n(t) {
  4243. var n = this;
  4244. return (n = e.call(this) || this).elements = t, n;
  4245. }
  4246. return t(n, e), n;
  4247. }(Rn);
  4248. function Gn(t, e) {
  4249. for (var n = Qn(e), r = function(t) {
  4250. n = n.filter((function(e) {
  4251. return !ue(e, t);
  4252. }));
  4253. }, i = 0, o = t.elements; i < o.length; i++) {
  4254. r(o[i]);
  4255. }
  4256. return {
  4257. arrayValue: {
  4258. values: n
  4259. }
  4260. };
  4261. }
  4262. /**
  4263. * Implements the backend semantics for locally computed NUMERIC_ADD (increment)
  4264. * transforms. Converts all field values to integers or doubles, but unlike the
  4265. * backend does not cap integer values at 2^63. Instead, JavaScript number
  4266. * arithmetic is used and precision loss can occur for values greater than 2^53.
  4267. */ var Kn = /** @class */ function(e) {
  4268. function n(t, n) {
  4269. var r = this;
  4270. return (r = e.call(this) || this).yt = t, r.gt = n, r;
  4271. }
  4272. return t(n, e), n;
  4273. }(Rn);
  4274. function jn(t) {
  4275. return Jt(t.integerValue || t.doubleValue);
  4276. }
  4277. function Qn(t) {
  4278. return pe(t) && t.arrayValue.values ? t.arrayValue.values.slice() : [];
  4279. }
  4280. /**
  4281. * @license
  4282. * Copyright 2017 Google LLC
  4283. *
  4284. * Licensed under the Apache License, Version 2.0 (the "License");
  4285. * you may not use this file except in compliance with the License.
  4286. * You may obtain a copy of the License at
  4287. *
  4288. * http://www.apache.org/licenses/LICENSE-2.0
  4289. *
  4290. * Unless required by applicable law or agreed to in writing, software
  4291. * distributed under the License is distributed on an "AS IS" BASIS,
  4292. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4293. * See the License for the specific language governing permissions and
  4294. * limitations under the License.
  4295. */
  4296. /** A field path and the TransformOperation to perform upon it. */ var zn = function(t, e) {
  4297. this.field = t, this.transform = e;
  4298. };
  4299. /** The result of successfully applying a mutation to the backend. */
  4300. var Wn = function(
  4301. /**
  4302. * The version at which the mutation was committed:
  4303. *
  4304. * - For most operations, this is the updateTime in the WriteResult.
  4305. * - For deletes, the commitTime of the WriteResponse (because deletes are
  4306. * not stored and have no updateTime).
  4307. *
  4308. * Note that these versions can be different: No-op writes will not change
  4309. * the updateTime even though the commitTime advances.
  4310. */
  4311. t,
  4312. /**
  4313. * The resulting fields returned from the backend after a mutation
  4314. * containing field transforms has been committed. Contains one FieldValue
  4315. * for each FieldTransform that was in the mutation.
  4316. *
  4317. * Will be empty if the mutation did not contain any field transforms.
  4318. */
  4319. e) {
  4320. this.version = t, this.transformResults = e;
  4321. }, Hn = /** @class */ function() {
  4322. function t(t, e) {
  4323. this.updateTime = t, this.exists = e
  4324. /** Creates a new empty Precondition. */;
  4325. }
  4326. return t.none = function() {
  4327. return new t;
  4328. },
  4329. /** Creates a new Precondition with an exists flag. */ t.exists = function(e) {
  4330. return new t(void 0, e);
  4331. },
  4332. /** Creates a new Precondition based on a version a document exists at. */ t.updateTime = function(e) {
  4333. return new t(e);
  4334. }, Object.defineProperty(t.prototype, "isNone", {
  4335. /** Returns whether this Precondition is empty. */ get: function() {
  4336. return void 0 === this.updateTime && void 0 === this.exists;
  4337. },
  4338. enumerable: !1,
  4339. configurable: !0
  4340. }), t.prototype.isEqual = function(t) {
  4341. return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);
  4342. }, t;
  4343. }();
  4344. /**
  4345. * Encodes a precondition for a mutation. This follows the model that the
  4346. * backend accepts with the special case of an explicit "empty" precondition
  4347. * (meaning no precondition).
  4348. */
  4349. /** Returns true if the preconditions is valid for the given document. */ function Yn(t, e) {
  4350. return void 0 !== t.updateTime ? e.isFoundDocument() && e.version.isEqual(t.updateTime) : void 0 === t.exists || t.exists === e.isFoundDocument();
  4351. }
  4352. /**
  4353. * A mutation describes a self-contained change to a document. Mutations can
  4354. * create, replace, delete, and update subsets of documents.
  4355. *
  4356. * Mutations not only act on the value of the document but also its version.
  4357. *
  4358. * For local mutations (mutations that haven't been committed yet), we preserve
  4359. * the existing version for Set and Patch mutations. For Delete mutations, we
  4360. * reset the version to 0.
  4361. *
  4362. * Here's the expected transition table.
  4363. *
  4364. * MUTATION APPLIED TO RESULTS IN
  4365. *
  4366. * SetMutation Document(v3) Document(v3)
  4367. * SetMutation NoDocument(v3) Document(v0)
  4368. * SetMutation InvalidDocument(v0) Document(v0)
  4369. * PatchMutation Document(v3) Document(v3)
  4370. * PatchMutation NoDocument(v3) NoDocument(v3)
  4371. * PatchMutation InvalidDocument(v0) UnknownDocument(v3)
  4372. * DeleteMutation Document(v3) NoDocument(v0)
  4373. * DeleteMutation NoDocument(v3) NoDocument(v0)
  4374. * DeleteMutation InvalidDocument(v0) NoDocument(v0)
  4375. *
  4376. * For acknowledged mutations, we use the updateTime of the WriteResponse as
  4377. * the resulting version for Set and Patch mutations. As deletes have no
  4378. * explicit update time, we use the commitTime of the WriteResponse for
  4379. * Delete mutations.
  4380. *
  4381. * If a mutation is acknowledged by the backend but fails the precondition check
  4382. * locally, we transition to an `UnknownDocument` and rely on Watch to send us
  4383. * the updated version.
  4384. *
  4385. * Field transforms are used only with Patch and Set Mutations. We use the
  4386. * `updateTransforms` message to store transforms, rather than the `transforms`s
  4387. * messages.
  4388. *
  4389. * ## Subclassing Notes
  4390. *
  4391. * Every type of mutation needs to implement its own applyToRemoteDocument() and
  4392. * applyToLocalView() to implement the actual behavior of applying the mutation
  4393. * to some source document (see `setMutationApplyToRemoteDocument()` for an
  4394. * example).
  4395. */ var Xn = function() {};
  4396. /**
  4397. * A utility method to calculate a `Mutation` representing the overlay from the
  4398. * final state of the document, and a `FieldMask` representing the fields that
  4399. * are mutated by the local mutations.
  4400. */ function Zn(t, e) {
  4401. if (!t.hasLocalMutations || e && 0 === e.fields.length) return null;
  4402. // mask is null when sets or deletes are applied to the current document.
  4403. if (null === e) return t.isNoDocument() ? new cr(t.key, Hn.none()) : new nr(t.key, t.data, Hn.none());
  4404. for (var n = t.data, r = en.empty(), i = new Ze(ht.comparator), o = 0, u = e.fields; o < u.length; o++) {
  4405. var a = u[o];
  4406. if (!i.has(a)) {
  4407. var s = n.field(a);
  4408. // If we are deleting a nested field, we take the immediate parent as
  4409. // the mask used to construct the resulting mutation.
  4410. // Justification: Nested fields can create parent fields implicitly. If
  4411. // only a leaf entry is deleted in later mutations, the parent field
  4412. // should still remain, but we may have lost this information.
  4413. // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).
  4414. // This leaves the final result (foo, {}). Despite the fact that `doc`
  4415. // has the correct result, `foo` is not in `mask`, and the resulting
  4416. // mutation would miss `foo`.
  4417. null === s && a.length > 1 && (a = a.popLast(), s = n.field(a)), null === s ? r.delete(a) : r.set(a, s),
  4418. i = i.add(a);
  4419. }
  4420. }
  4421. return new rr(t.key, r, new tn(i.toArray()), Hn.none());
  4422. }
  4423. /**
  4424. * Applies this mutation to the given document for the purposes of computing a
  4425. * new remote document. If the input document doesn't match the expected state
  4426. * (e.g. it is invalid or outdated), the document type may transition to
  4427. * unknown.
  4428. *
  4429. * @param mutation - The mutation to apply.
  4430. * @param document - The document to mutate. The input document can be an
  4431. * invalid document if the client has no knowledge of the pre-mutation state
  4432. * of the document.
  4433. * @param mutationResult - The result of applying the mutation from the backend.
  4434. */ function Jn(t, e, n) {
  4435. t instanceof nr ? function(t, e, n) {
  4436. // Unlike setMutationApplyToLocalView, if we're applying a mutation to a
  4437. // remote document the server has accepted the mutation so the precondition
  4438. // must have held.
  4439. var r = t.value.clone(), i = or(t.fieldTransforms, e, n.transformResults);
  4440. r.setAll(i), e.convertToFoundDocument(n.version, r).setHasCommittedMutations();
  4441. }(t, e, n) : t instanceof rr ? function(t, e, n) {
  4442. if (Yn(t.precondition, e)) {
  4443. var r = or(t.fieldTransforms, e, n.transformResults), i = e.data;
  4444. i.setAll(ir(t)), i.setAll(r), e.convertToFoundDocument(n.version, i).setHasCommittedMutations();
  4445. } else e.convertToUnknownDocument(n.version);
  4446. }(t, e, n) : function(t, e, n) {
  4447. // Unlike applyToLocalView, if we're applying a mutation to a remote
  4448. // document the server has accepted the mutation so the precondition must
  4449. // have held.
  4450. e.convertToNoDocument(n.version).setHasCommittedMutations();
  4451. }(0, e, n);
  4452. }
  4453. /**
  4454. * Applies this mutation to the given document for the purposes of computing
  4455. * the new local view of a document. If the input document doesn't match the
  4456. * expected state, the document is not modified.
  4457. *
  4458. * @param mutation - The mutation to apply.
  4459. * @param document - The document to mutate. The input document can be an
  4460. * invalid document if the client has no knowledge of the pre-mutation state
  4461. * of the document.
  4462. * @param previousMask - The fields that have been updated before applying this mutation.
  4463. * @param localWriteTime - A timestamp indicating the local write time of the
  4464. * batch this mutation is a part of.
  4465. * @returns A `FieldMask` representing the fields that are changed by applying this mutation.
  4466. */ function $n(t, e, n, r) {
  4467. return t instanceof nr ? function(t, e, n, r) {
  4468. if (!Yn(t.precondition, e))
  4469. // The mutation failed to apply (e.g. a document ID created with add()
  4470. // caused a name collision).
  4471. return n;
  4472. var i = t.value.clone(), o = ur(t.fieldTransforms, r, e);
  4473. return i.setAll(o), e.convertToFoundDocument(e.version, i).setHasLocalMutations(),
  4474. null;
  4475. // SetMutation overwrites all fields.
  4476. }(t, e, n, r) : t instanceof rr ? function(t, e, n, r) {
  4477. if (!Yn(t.precondition, e)) return n;
  4478. var i = ur(t.fieldTransforms, r, e), o = e.data;
  4479. return o.setAll(ir(t)), o.setAll(i), e.convertToFoundDocument(e.version, o).setHasLocalMutations(),
  4480. null === n ? null : n.unionWith(t.fieldMask.fields).unionWith(t.fieldTransforms.map((function(t) {
  4481. return t.field;
  4482. })));
  4483. }(t, e, n, r) : function(t, e, n) {
  4484. return Yn(t.precondition, e) ? (e.convertToNoDocument(e.version).setHasLocalMutations(),
  4485. null) : n;
  4486. }(t, e, n);
  4487. }
  4488. /**
  4489. * If this mutation is not idempotent, returns the base value to persist with
  4490. * this mutation. If a base value is returned, the mutation is always applied
  4491. * to this base value, even if document has already been updated.
  4492. *
  4493. * The base value is a sparse object that consists of only the document
  4494. * fields for which this mutation contains a non-idempotent transformation
  4495. * (e.g. a numeric increment). The provided value guarantees consistent
  4496. * behavior for non-idempotent transforms and allow us to return the same
  4497. * latency-compensated value even if the backend has already applied the
  4498. * mutation. The base value is null for idempotent mutations, as they can be
  4499. * re-played even if the backend has already applied them.
  4500. *
  4501. * @returns a base value to store along with the mutation, or null for
  4502. * idempotent mutations.
  4503. */ function tr(t, e) {
  4504. for (var n = null, r = 0, i = t.fieldTransforms; r < i.length; r++) {
  4505. var o = i[r], u = e.data.field(o.field), a = Ln(o.transform, u || null);
  4506. null != a && (null === n && (n = en.empty()), n.set(o.field, a));
  4507. }
  4508. return n || null;
  4509. }
  4510. function er(t, e) {
  4511. return t.type === e.type && !!t.key.isEqual(e.key) && !!t.precondition.isEqual(e.precondition) && !!function(t, e) {
  4512. return void 0 === t && void 0 === e || !(!t || !e) && it(t, e, (function(t, e) {
  4513. return function(t, e) {
  4514. return t.field.isEqual(e.field) && function(t, e) {
  4515. return t instanceof qn && e instanceof qn || t instanceof Bn && e instanceof Bn ? it(t.elements, e.elements, ue) : t instanceof Kn && e instanceof Kn ? ue(t.gt, e.gt) : t instanceof Pn && e instanceof Pn;
  4516. }(t.transform, e.transform);
  4517. }(t, e);
  4518. }));
  4519. }(t.fieldTransforms, e.fieldTransforms) && (0 /* MutationType.Set */ === t.type ? t.value.isEqual(e.value) : 1 /* MutationType.Patch */ !== t.type || t.data.isEqual(e.data) && t.fieldMask.isEqual(e.fieldMask));
  4520. }
  4521. /**
  4522. * A mutation that creates or replaces the document at the given key with the
  4523. * object value contents.
  4524. */ var nr = /** @class */ function(e) {
  4525. function n(t, n, r, i) {
  4526. void 0 === i && (i = []);
  4527. var o = this;
  4528. return (o = e.call(this) || this).key = t, o.value = n, o.precondition = r, o.fieldTransforms = i,
  4529. o.type = 0 /* MutationType.Set */ , o;
  4530. }
  4531. return t(n, e), n.prototype.getFieldMask = function() {
  4532. return null;
  4533. }, n;
  4534. }(Xn), rr = /** @class */ function(e) {
  4535. function n(t, n, r, i, o) {
  4536. void 0 === o && (o = []);
  4537. var u = this;
  4538. return (u = e.call(this) || this).key = t, u.data = n, u.fieldMask = r, u.precondition = i,
  4539. u.fieldTransforms = o, u.type = 1 /* MutationType.Patch */ , u;
  4540. }
  4541. return t(n, e), n.prototype.getFieldMask = function() {
  4542. return this.fieldMask;
  4543. }, n;
  4544. }(Xn);
  4545. function ir(t) {
  4546. var e = new Map;
  4547. return t.fieldMask.fields.forEach((function(n) {
  4548. if (!n.isEmpty()) {
  4549. var r = t.data.field(n);
  4550. e.set(n, r);
  4551. }
  4552. })), e
  4553. /**
  4554. * Creates a list of "transform results" (a transform result is a field value
  4555. * representing the result of applying a transform) for use after a mutation
  4556. * containing transforms has been acknowledged by the server.
  4557. *
  4558. * @param fieldTransforms - The field transforms to apply the result to.
  4559. * @param mutableDocument - The current state of the document after applying all
  4560. * previous mutations.
  4561. * @param serverTransformResults - The transform results received by the server.
  4562. * @returns The transform results list.
  4563. */;
  4564. }
  4565. function or(t, e, n) {
  4566. var r = new Map;
  4567. U(t.length === n.length);
  4568. for (var i = 0; i < n.length; i++) {
  4569. var o = t[i], u = o.transform, a = e.data.field(o.field);
  4570. r.set(o.field, Mn(u, a, n[i]));
  4571. }
  4572. return r;
  4573. }
  4574. /**
  4575. * Creates a list of "transform results" (a transform result is a field value
  4576. * representing the result of applying a transform) for use when applying a
  4577. * transform locally.
  4578. *
  4579. * @param fieldTransforms - The field transforms to apply the result to.
  4580. * @param localWriteTime - The local time of the mutation (used to
  4581. * generate ServerTimestampValues).
  4582. * @param mutableDocument - The document to apply transforms on.
  4583. * @returns The transform results list.
  4584. */ function ur(t, e, n) {
  4585. for (var r = new Map, i = 0, o = t; i < o.length; i++) {
  4586. var u = o[i], a = u.transform, s = n.data.field(u.field);
  4587. r.set(u.field, Vn(a, s, e));
  4588. }
  4589. return r;
  4590. }
  4591. /** A mutation that deletes the document at the given key. */ var ar, sr, cr = /** @class */ function(e) {
  4592. function n(t, n) {
  4593. var r = this;
  4594. return (r = e.call(this) || this).key = t, r.precondition = n, r.type = 2 /* MutationType.Delete */ ,
  4595. r.fieldTransforms = [], r;
  4596. }
  4597. return t(n, e), n.prototype.getFieldMask = function() {
  4598. return null;
  4599. }, n;
  4600. }(Xn), lr = /** @class */ function(e) {
  4601. function n(t, n) {
  4602. var r = this;
  4603. return (r = e.call(this) || this).key = t, r.precondition = n, r.type = 3 /* MutationType.Verify */ ,
  4604. r.fieldTransforms = [], r;
  4605. }
  4606. return t(n, e), n.prototype.getFieldMask = function() {
  4607. return null;
  4608. }, n;
  4609. }(Xn), hr =
  4610. // TODO(b/33078163): just use simplest form of existence filter for now
  4611. function(t) {
  4612. this.count = t;
  4613. };
  4614. /**
  4615. * Determines whether an error code represents a permanent error when received
  4616. * in response to a non-write operation.
  4617. *
  4618. * See isPermanentWriteError for classifying write errors.
  4619. */
  4620. function fr(t) {
  4621. switch (t) {
  4622. default:
  4623. return q();
  4624. case K.CANCELLED:
  4625. case K.UNKNOWN:
  4626. case K.DEADLINE_EXCEEDED:
  4627. case K.RESOURCE_EXHAUSTED:
  4628. case K.INTERNAL:
  4629. case K.UNAVAILABLE:
  4630. // Unauthenticated means something went wrong with our token and we need
  4631. // to retry with new credentials which will happen automatically.
  4632. case K.UNAUTHENTICATED:
  4633. return !1;
  4634. case K.INVALID_ARGUMENT:
  4635. case K.NOT_FOUND:
  4636. case K.ALREADY_EXISTS:
  4637. case K.PERMISSION_DENIED:
  4638. case K.FAILED_PRECONDITION:
  4639. // Aborted might be retried in some scenarios, but that is dependant on
  4640. // the context and should handled individually by the calling code.
  4641. // See https://cloud.google.com/apis/design/errors.
  4642. case K.ABORTED:
  4643. case K.OUT_OF_RANGE:
  4644. case K.UNIMPLEMENTED:
  4645. case K.DATA_LOSS:
  4646. return !0;
  4647. }
  4648. }
  4649. /**
  4650. * Determines whether an error code represents a permanent error when received
  4651. * in response to a write operation.
  4652. *
  4653. * Write operations must be handled specially because as of b/119437764, ABORTED
  4654. * errors on the write stream should be retried too (even though ABORTED errors
  4655. * are not generally retryable).
  4656. *
  4657. * Note that during the initial handshake on the write stream an ABORTED error
  4658. * signals that we should discard our stream token (i.e. it is permanent). This
  4659. * means a handshake error should be classified with isPermanentError, above.
  4660. */
  4661. /**
  4662. * Maps an error Code from GRPC status code number, like 0, 1, or 14. These
  4663. * are not the same as HTTP status codes.
  4664. *
  4665. * @returns The Code equivalent to the given GRPC status code. Fails if there
  4666. * is no match.
  4667. */ function dr(t) {
  4668. if (void 0 === t)
  4669. // This shouldn't normally happen, but in certain error cases (like trying
  4670. // to send invalid proto messages) we may get an error with no GRPC code.
  4671. return M("GRPC error has no .code"), K.UNKNOWN;
  4672. switch (t) {
  4673. case ar.OK:
  4674. return K.OK;
  4675. case ar.CANCELLED:
  4676. return K.CANCELLED;
  4677. case ar.UNKNOWN:
  4678. return K.UNKNOWN;
  4679. case ar.DEADLINE_EXCEEDED:
  4680. return K.DEADLINE_EXCEEDED;
  4681. case ar.RESOURCE_EXHAUSTED:
  4682. return K.RESOURCE_EXHAUSTED;
  4683. case ar.INTERNAL:
  4684. return K.INTERNAL;
  4685. case ar.UNAVAILABLE:
  4686. return K.UNAVAILABLE;
  4687. case ar.UNAUTHENTICATED:
  4688. return K.UNAUTHENTICATED;
  4689. case ar.INVALID_ARGUMENT:
  4690. return K.INVALID_ARGUMENT;
  4691. case ar.NOT_FOUND:
  4692. return K.NOT_FOUND;
  4693. case ar.ALREADY_EXISTS:
  4694. return K.ALREADY_EXISTS;
  4695. case ar.PERMISSION_DENIED:
  4696. return K.PERMISSION_DENIED;
  4697. case ar.FAILED_PRECONDITION:
  4698. return K.FAILED_PRECONDITION;
  4699. case ar.ABORTED:
  4700. return K.ABORTED;
  4701. case ar.OUT_OF_RANGE:
  4702. return K.OUT_OF_RANGE;
  4703. case ar.UNIMPLEMENTED:
  4704. return K.UNIMPLEMENTED;
  4705. case ar.DATA_LOSS:
  4706. return K.DATA_LOSS;
  4707. default:
  4708. return q();
  4709. }
  4710. }
  4711. /**
  4712. * Converts an HTTP response's error status to the equivalent error code.
  4713. *
  4714. * @param status - An HTTP error response status ("FAILED_PRECONDITION",
  4715. * "UNKNOWN", etc.)
  4716. * @returns The equivalent Code. Non-matching responses are mapped to
  4717. * Code.UNKNOWN.
  4718. */ (sr = ar || (ar = {}))[sr.OK = 0] = "OK", sr[sr.CANCELLED = 1] = "CANCELLED",
  4719. sr[sr.UNKNOWN = 2] = "UNKNOWN", sr[sr.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT",
  4720. sr[sr.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", sr[sr.NOT_FOUND = 5] = "NOT_FOUND",
  4721. sr[sr.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", sr[sr.PERMISSION_DENIED = 7] = "PERMISSION_DENIED",
  4722. sr[sr.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", sr[sr.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED",
  4723. sr[sr.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", sr[sr.ABORTED = 10] = "ABORTED",
  4724. sr[sr.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", sr[sr.UNIMPLEMENTED = 12] = "UNIMPLEMENTED",
  4725. sr[sr.INTERNAL = 13] = "INTERNAL", sr[sr.UNAVAILABLE = 14] = "UNAVAILABLE", sr[sr.DATA_LOSS = 15] = "DATA_LOSS";
  4726. /**
  4727. * @license
  4728. * Copyright 2017 Google LLC
  4729. *
  4730. * Licensed under the Apache License, Version 2.0 (the "License");
  4731. * you may not use this file except in compliance with the License.
  4732. * You may obtain a copy of the License at
  4733. *
  4734. * http://www.apache.org/licenses/LICENSE-2.0
  4735. *
  4736. * Unless required by applicable law or agreed to in writing, software
  4737. * distributed under the License is distributed on an "AS IS" BASIS,
  4738. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4739. * See the License for the specific language governing permissions and
  4740. * limitations under the License.
  4741. */
  4742. /**
  4743. * A map implementation that uses objects as keys. Objects must have an
  4744. * associated equals function and must be immutable. Entries in the map are
  4745. * stored together with the key being produced from the mapKeyFn. This map
  4746. * automatically handles collisions of keys.
  4747. */
  4748. var pr = /** @class */ function() {
  4749. function t(t, e) {
  4750. this.mapKeyFn = t, this.equalsFn = e,
  4751. /**
  4752. * The inner map for a key/value pair. Due to the possibility of collisions we
  4753. * keep a list of entries that we do a linear search through to find an actual
  4754. * match. Note that collisions should be rare, so we still expect near
  4755. * constant time lookups in practice.
  4756. */
  4757. this.inner = {},
  4758. /** The number of entries stored in the map */
  4759. this.innerSize = 0
  4760. /** Get a value for this key, or undefined if it does not exist. */;
  4761. }
  4762. return t.prototype.get = function(t) {
  4763. var e = this.mapKeyFn(t), n = this.inner[e];
  4764. if (void 0 !== n) for (var r = 0, i = n; r < i.length; r++) {
  4765. var o = i[r], u = o[0], a = o[1];
  4766. if (this.equalsFn(u, t)) return a;
  4767. }
  4768. }, t.prototype.has = function(t) {
  4769. return void 0 !== this.get(t);
  4770. },
  4771. /** Put this key and value in the map. */ t.prototype.set = function(t, e) {
  4772. var n = this.mapKeyFn(t), r = this.inner[n];
  4773. if (void 0 === r) return this.inner[n] = [ [ t, e ] ], void this.innerSize++;
  4774. for (var i = 0; i < r.length; i++) if (this.equalsFn(r[i][0], t))
  4775. // This is updating an existing entry and does not increase `innerSize`.
  4776. return void (r[i] = [ t, e ]);
  4777. r.push([ t, e ]), this.innerSize++;
  4778. },
  4779. /**
  4780. * Remove this key from the map. Returns a boolean if anything was deleted.
  4781. */
  4782. t.prototype.delete = function(t) {
  4783. var e = this.mapKeyFn(t), n = this.inner[e];
  4784. if (void 0 === n) return !1;
  4785. for (var r = 0; r < n.length; r++) if (this.equalsFn(n[r][0], t)) return 1 === n.length ? delete this.inner[e] : n.splice(r, 1),
  4786. this.innerSize--, !0;
  4787. return !1;
  4788. }, t.prototype.forEach = function(t) {
  4789. Kt(this.inner, (function(e, n) {
  4790. for (var r = 0, i = n; r < i.length; r++) {
  4791. var o = i[r], u = o[0], a = o[1];
  4792. t(u, a);
  4793. }
  4794. }));
  4795. }, t.prototype.isEmpty = function() {
  4796. return jt(this.inner);
  4797. }, t.prototype.size = function() {
  4798. return this.innerSize;
  4799. }, t;
  4800. }(), yr = new He(ft.comparator);
  4801. /**
  4802. * @license
  4803. * Copyright 2017 Google LLC
  4804. *
  4805. * Licensed under the Apache License, Version 2.0 (the "License");
  4806. * you may not use this file except in compliance with the License.
  4807. * You may obtain a copy of the License at
  4808. *
  4809. * http://www.apache.org/licenses/LICENSE-2.0
  4810. *
  4811. * Unless required by applicable law or agreed to in writing, software
  4812. * distributed under the License is distributed on an "AS IS" BASIS,
  4813. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4814. * See the License for the specific language governing permissions and
  4815. * limitations under the License.
  4816. */ function vr() {
  4817. return yr;
  4818. }
  4819. var mr = new He(ft.comparator);
  4820. function gr() {
  4821. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  4822. for (var n = mr, r = 0, i = t; r < i.length; r++) {
  4823. var o = i[r];
  4824. n = n.insert(o.key, o);
  4825. }
  4826. return n;
  4827. }
  4828. function wr(t) {
  4829. var e = mr;
  4830. return t.forEach((function(t, n) {
  4831. return e = e.insert(t, n.overlayedDocument);
  4832. })), e;
  4833. }
  4834. function br() {
  4835. return Tr();
  4836. }
  4837. function Ir() {
  4838. return Tr();
  4839. }
  4840. function Tr() {
  4841. return new pr((function(t) {
  4842. return t.toString();
  4843. }), (function(t, e) {
  4844. return t.isEqual(e);
  4845. }));
  4846. }
  4847. var Er = new He(ft.comparator), Sr = new Ze(ft.comparator);
  4848. function _r() {
  4849. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  4850. for (var n = Sr, r = 0, i = t; r < i.length; r++) {
  4851. var o = i[r];
  4852. n = n.add(o);
  4853. }
  4854. return n;
  4855. }
  4856. var Dr = new Ze(rt);
  4857. function xr() {
  4858. return Dr;
  4859. }
  4860. /**
  4861. * @license
  4862. * Copyright 2017 Google LLC
  4863. *
  4864. * Licensed under the Apache License, Version 2.0 (the "License");
  4865. * you may not use this file except in compliance with the License.
  4866. * You may obtain a copy of the License at
  4867. *
  4868. * http://www.apache.org/licenses/LICENSE-2.0
  4869. *
  4870. * Unless required by applicable law or agreed to in writing, software
  4871. * distributed under the License is distributed on an "AS IS" BASIS,
  4872. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4873. * See the License for the specific language governing permissions and
  4874. * limitations under the License.
  4875. */
  4876. /**
  4877. * An event from the RemoteStore. It is split into targetChanges (changes to the
  4878. * state or the set of documents in our watched targets) and documentUpdates
  4879. * (changes to the actual documents).
  4880. */ var Ar = /** @class */ function() {
  4881. function t(
  4882. /**
  4883. * The snapshot version this event brings us up to, or MIN if not set.
  4884. */
  4885. t,
  4886. /**
  4887. * A map from target to changes to the target. See TargetChange.
  4888. */
  4889. e,
  4890. /**
  4891. * A set of targets that is known to be inconsistent. Listens for these
  4892. * targets should be re-established without resume tokens.
  4893. */
  4894. n,
  4895. /**
  4896. * A set of which documents have changed or been deleted, along with the
  4897. * doc's new values (if not deleted).
  4898. */
  4899. r,
  4900. /**
  4901. * A set of which document updates are due only to limbo resolution targets.
  4902. */
  4903. i) {
  4904. this.snapshotVersion = t, this.targetChanges = e, this.targetMismatches = n, this.documentUpdates = r,
  4905. this.resolvedLimboDocuments = i;
  4906. }
  4907. /**
  4908. * HACK: Views require RemoteEvents in order to determine whether the view is
  4909. * CURRENT, but secondary tabs don't receive remote events. So this method is
  4910. * used to create a synthesized RemoteEvent that can be used to apply a
  4911. * CURRENT status change to a View, for queries executed in a different tab.
  4912. */
  4913. // PORTING NOTE: Multi-tab only
  4914. return t.createSynthesizedRemoteEventForCurrentChange = function(e, n, r) {
  4915. var i = new Map;
  4916. return i.set(e, Cr.createSynthesizedTargetChangeForCurrentChange(e, n, r)), new t(at.min(), i, xr(), vr(), _r());
  4917. }, t;
  4918. }(), Cr = /** @class */ function() {
  4919. function t(
  4920. /**
  4921. * An opaque, server-assigned token that allows watching a query to be resumed
  4922. * after disconnecting without retransmitting all the data that matches the
  4923. * query. The resume token essentially identifies a point in time from which
  4924. * the server should resume sending results.
  4925. */
  4926. t,
  4927. /**
  4928. * The "current" (synced) status of this target. Note that "current"
  4929. * has special meaning in the RPC protocol that implies that a target is
  4930. * both up-to-date and consistent with the rest of the watch stream.
  4931. */
  4932. e,
  4933. /**
  4934. * The set of documents that were newly assigned to this target as part of
  4935. * this remote event.
  4936. */
  4937. n,
  4938. /**
  4939. * The set of documents that were already assigned to this target but received
  4940. * an update during this remote event.
  4941. */
  4942. r,
  4943. /**
  4944. * The set of documents that were removed from this target as part of this
  4945. * remote event.
  4946. */
  4947. i) {
  4948. this.resumeToken = t, this.current = e, this.addedDocuments = n, this.modifiedDocuments = r,
  4949. this.removedDocuments = i
  4950. /**
  4951. * This method is used to create a synthesized TargetChanges that can be used to
  4952. * apply a CURRENT status change to a View (for queries executed in a different
  4953. * tab) or for new queries (to raise snapshots with correct CURRENT status).
  4954. */;
  4955. }
  4956. return t.createSynthesizedTargetChangeForCurrentChange = function(e, n, r) {
  4957. return new t(r, n, _r(), _r(), _r());
  4958. }, t;
  4959. }(), Nr = function(
  4960. /** The new document applies to all of these targets. */
  4961. t,
  4962. /** The new document is removed from all of these targets. */
  4963. e,
  4964. /** The key of the document for this change. */
  4965. n,
  4966. /**
  4967. * The new document or NoDocument if it was deleted. Is null if the
  4968. * document went out of view without the server sending a new document.
  4969. */
  4970. r) {
  4971. this.It = t, this.removedTargetIds = e, this.key = n, this.Tt = r;
  4972. }, kr = function(t, e) {
  4973. this.targetId = t, this.Et = e;
  4974. }, Fr = function(
  4975. /** What kind of change occurred to the watch target. */
  4976. t,
  4977. /** The target IDs that were added/removed/set. */
  4978. e,
  4979. /**
  4980. * An opaque, server-assigned token that allows watching a target to be
  4981. * resumed after disconnecting without retransmitting all the data that
  4982. * matches the target. The resume token essentially identifies a point in
  4983. * time from which the server should resume sending results.
  4984. */
  4985. n
  4986. /** An RPC error indicating why the watch failed. */ , r) {
  4987. void 0 === n && (n = Yt.EMPTY_BYTE_STRING), void 0 === r && (r = null), this.state = t,
  4988. this.targetIds = e, this.resumeToken = n, this.cause = r;
  4989. }, Or = /** @class */ function() {
  4990. function t() {
  4991. /**
  4992. * The number of pending responses (adds or removes) that we are waiting on.
  4993. * We only consider targets active that have no pending responses.
  4994. */
  4995. this.At = 0,
  4996. /**
  4997. * Keeps track of the document changes since the last raised snapshot.
  4998. *
  4999. * These changes are continuously updated as we receive document updates and
  5000. * always reflect the current set of changes against the last issued snapshot.
  5001. */
  5002. this.Rt = Mr(),
  5003. /** See public getters for explanations of these fields. */
  5004. this.bt = Yt.EMPTY_BYTE_STRING, this.Pt = !1,
  5005. /**
  5006. * Whether this target state should be included in the next snapshot. We
  5007. * initialize to true so that newly-added targets are included in the next
  5008. * RemoteEvent.
  5009. */
  5010. this.vt = !0;
  5011. }
  5012. return Object.defineProperty(t.prototype, "current", {
  5013. /**
  5014. * Whether this target has been marked 'current'.
  5015. *
  5016. * 'Current' has special meaning in the RPC protocol: It implies that the
  5017. * Watch backend has sent us all changes up to the point at which the target
  5018. * was added and that the target is consistent with the rest of the watch
  5019. * stream.
  5020. */
  5021. get: function() {
  5022. return this.Pt;
  5023. },
  5024. enumerable: !1,
  5025. configurable: !0
  5026. }), Object.defineProperty(t.prototype, "resumeToken", {
  5027. /** The last resume token sent to us for this target. */ get: function() {
  5028. return this.bt;
  5029. },
  5030. enumerable: !1,
  5031. configurable: !0
  5032. }), Object.defineProperty(t.prototype, "Vt", {
  5033. /** Whether this target has pending target adds or target removes. */ get: function() {
  5034. return 0 !== this.At;
  5035. },
  5036. enumerable: !1,
  5037. configurable: !0
  5038. }), Object.defineProperty(t.prototype, "St", {
  5039. /** Whether we have modified any state that should trigger a snapshot. */ get: function() {
  5040. return this.vt;
  5041. },
  5042. enumerable: !1,
  5043. configurable: !0
  5044. }),
  5045. /**
  5046. * Applies the resume token to the TargetChange, but only when it has a new
  5047. * value. Empty resumeTokens are discarded.
  5048. */
  5049. t.prototype.Dt = function(t) {
  5050. t.approximateByteSize() > 0 && (this.vt = !0, this.bt = t);
  5051. },
  5052. /**
  5053. * Creates a target change from the current set of changes.
  5054. *
  5055. * To reset the document changes after raising this snapshot, call
  5056. * `clearPendingChanges()`.
  5057. */
  5058. t.prototype.Ct = function() {
  5059. var t = _r(), e = _r(), n = _r();
  5060. return this.Rt.forEach((function(r, i) {
  5061. switch (i) {
  5062. case 0 /* ChangeType.Added */ :
  5063. t = t.add(r);
  5064. break;
  5065. case 2 /* ChangeType.Modified */ :
  5066. e = e.add(r);
  5067. break;
  5068. case 1 /* ChangeType.Removed */ :
  5069. n = n.add(r);
  5070. break;
  5071. default:
  5072. q();
  5073. }
  5074. })), new Cr(this.bt, this.Pt, t, e, n);
  5075. },
  5076. /**
  5077. * Resets the document changes and sets `hasPendingChanges` to false.
  5078. */
  5079. t.prototype.xt = function() {
  5080. this.vt = !1, this.Rt = Mr();
  5081. }, t.prototype.Nt = function(t, e) {
  5082. this.vt = !0, this.Rt = this.Rt.insert(t, e);
  5083. }, t.prototype.kt = function(t) {
  5084. this.vt = !0, this.Rt = this.Rt.remove(t);
  5085. }, t.prototype.Ot = function() {
  5086. this.At += 1;
  5087. }, t.prototype.Mt = function() {
  5088. this.At -= 1;
  5089. }, t.prototype.Ft = function() {
  5090. this.vt = !0, this.Pt = !0;
  5091. }, t;
  5092. }(), Rr = /** @class */ function() {
  5093. function t(t) {
  5094. this.$t = t,
  5095. /** The internal state of all tracked targets. */
  5096. this.Bt = new Map,
  5097. /** Keeps track of the documents to update since the last raised snapshot. */
  5098. this.Lt = vr(),
  5099. /** A mapping of document keys to their set of target IDs. */
  5100. this.qt = Vr(),
  5101. /**
  5102. * A list of targets with existence filter mismatches. These targets are
  5103. * known to be inconsistent and their listens needs to be re-established by
  5104. * RemoteStore.
  5105. */
  5106. this.Ut = new Ze(rt)
  5107. /**
  5108. * Processes and adds the DocumentWatchChange to the current set of changes.
  5109. */;
  5110. }
  5111. return t.prototype.Kt = function(t) {
  5112. for (var e = 0, n = t.It; e < n.length; e++) {
  5113. var r = n[e];
  5114. t.Tt && t.Tt.isFoundDocument() ? this.Gt(r, t.Tt) : this.Qt(r, t.key, t.Tt);
  5115. }
  5116. for (var i = 0, o = t.removedTargetIds; i < o.length; i++) {
  5117. var u = o[i];
  5118. this.Qt(u, t.key, t.Tt);
  5119. }
  5120. },
  5121. /** Processes and adds the WatchTargetChange to the current set of changes. */ t.prototype.jt = function(t) {
  5122. var e = this;
  5123. this.forEachTarget(t, (function(n) {
  5124. var r = e.Wt(n);
  5125. switch (t.state) {
  5126. case 0 /* WatchTargetChangeState.NoChange */ :
  5127. e.zt(n) && r.Dt(t.resumeToken);
  5128. break;
  5129. case 1 /* WatchTargetChangeState.Added */ :
  5130. // We need to decrement the number of pending acks needed from watch
  5131. // for this targetId.
  5132. r.Mt(), r.Vt ||
  5133. // We have a freshly added target, so we need to reset any state
  5134. // that we had previously. This can happen e.g. when remove and add
  5135. // back a target for existence filter mismatches.
  5136. r.xt(), r.Dt(t.resumeToken);
  5137. break;
  5138. case 2 /* WatchTargetChangeState.Removed */ :
  5139. // We need to keep track of removed targets to we can post-filter and
  5140. // remove any target changes.
  5141. // We need to decrement the number of pending acks needed from watch
  5142. // for this targetId.
  5143. r.Mt(), r.Vt || e.removeTarget(n);
  5144. break;
  5145. case 3 /* WatchTargetChangeState.Current */ :
  5146. e.zt(n) && (r.Ft(), r.Dt(t.resumeToken));
  5147. break;
  5148. case 4 /* WatchTargetChangeState.Reset */ :
  5149. e.zt(n) && (
  5150. // Reset the target and synthesizes removes for all existing
  5151. // documents. The backend will re-add any documents that still
  5152. // match the target before it sends the next global snapshot.
  5153. e.Ht(n), r.Dt(t.resumeToken));
  5154. break;
  5155. default:
  5156. q();
  5157. }
  5158. }));
  5159. },
  5160. /**
  5161. * Iterates over all targetIds that the watch change applies to: either the
  5162. * targetIds explicitly listed in the change or the targetIds of all currently
  5163. * active targets.
  5164. */
  5165. t.prototype.forEachTarget = function(t, e) {
  5166. var n = this;
  5167. t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.Bt.forEach((function(t, r) {
  5168. n.zt(r) && e(r);
  5169. }));
  5170. },
  5171. /**
  5172. * Handles existence filters and synthesizes deletes for filter mismatches.
  5173. * Targets that are invalidated by filter mismatches are added to
  5174. * `pendingTargetResets`.
  5175. */
  5176. t.prototype.Jt = function(t) {
  5177. var e = t.targetId, n = t.Et.count, r = this.Yt(e);
  5178. if (r) {
  5179. var i = r.target;
  5180. if (cn(i)) if (0 === n) {
  5181. // The existence filter told us the document does not exist. We deduce
  5182. // that this document does not exist and apply a deleted document to
  5183. // our updates. Without applying this deleted document there might be
  5184. // another query that will raise this document as part of a snapshot
  5185. // until it is resolved, essentially exposing inconsistency between
  5186. // queries.
  5187. var o = new ft(i.path);
  5188. this.Qt(e, o, rn.newNoDocument(o, at.min()));
  5189. } else U(1 === n); else this.Xt(e) !== n && (
  5190. // Existence filter mismatch: We reset the mapping and raise a new
  5191. // snapshot with `isFromCache:true`.
  5192. this.Ht(e), this.Ut = this.Ut.add(e));
  5193. }
  5194. },
  5195. /**
  5196. * Converts the currently accumulated state into a remote event at the
  5197. * provided snapshot version. Resets the accumulated changes before returning.
  5198. */
  5199. t.prototype.Zt = function(t) {
  5200. var e = this, n = new Map;
  5201. this.Bt.forEach((function(r, i) {
  5202. var o = e.Yt(i);
  5203. if (o) {
  5204. if (r.current && cn(o.target)) {
  5205. // Document queries for document that don't exist can produce an empty
  5206. // result set. To update our local cache, we synthesize a document
  5207. // delete if we have not previously received the document. This
  5208. // resolves the limbo state of the document, removing it from
  5209. // limboDocumentRefs.
  5210. // TODO(dimond): Ideally we would have an explicit lookup target
  5211. // instead resulting in an explicit delete message and we could
  5212. // remove this special logic.
  5213. var u = new ft(o.target.path);
  5214. null !== e.Lt.get(u) || e.te(i, u) || e.Qt(i, u, rn.newNoDocument(u, t));
  5215. }
  5216. r.St && (n.set(i, r.Ct()), r.xt());
  5217. }
  5218. }));
  5219. var r = _r();
  5220. // We extract the set of limbo-only document updates as the GC logic
  5221. // special-cases documents that do not appear in the target cache.
  5222. // TODO(gsoltis): Expand on this comment once GC is available in the JS
  5223. // client.
  5224. this.qt.forEach((function(t, n) {
  5225. var i = !0;
  5226. n.forEachWhile((function(t) {
  5227. var n = e.Yt(t);
  5228. return !n || 2 /* TargetPurpose.LimboResolution */ === n.purpose || (i = !1, !1);
  5229. })), i && (r = r.add(t));
  5230. })), this.Lt.forEach((function(e, n) {
  5231. return n.setReadTime(t);
  5232. }));
  5233. var i = new Ar(t, n, this.Ut, this.Lt, r);
  5234. return this.Lt = vr(), this.qt = Vr(), this.Ut = new Ze(rt), i;
  5235. },
  5236. /**
  5237. * Adds the provided document to the internal list of document updates and
  5238. * its document key to the given target's mapping.
  5239. */
  5240. // Visible for testing.
  5241. t.prototype.Gt = function(t, e) {
  5242. if (this.zt(t)) {
  5243. var n = this.te(t, e.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */;
  5244. this.Wt(t).Nt(e.key, n), this.Lt = this.Lt.insert(e.key, e), this.qt = this.qt.insert(e.key, this.ee(e.key).add(t));
  5245. }
  5246. },
  5247. /**
  5248. * Removes the provided document from the target mapping. If the
  5249. * document no longer matches the target, but the document's state is still
  5250. * known (e.g. we know that the document was deleted or we received the change
  5251. * that caused the filter mismatch), the new document can be provided
  5252. * to update the remote document cache.
  5253. */
  5254. // Visible for testing.
  5255. t.prototype.Qt = function(t, e, n) {
  5256. if (this.zt(t)) {
  5257. var r = this.Wt(t);
  5258. this.te(t, e) ? r.Nt(e, 1 /* ChangeType.Removed */) :
  5259. // The document may have entered and left the target before we raised a
  5260. // snapshot, so we can just ignore the change.
  5261. r.kt(e), this.qt = this.qt.insert(e, this.ee(e).delete(t)), n && (this.Lt = this.Lt.insert(e, n));
  5262. }
  5263. }, t.prototype.removeTarget = function(t) {
  5264. this.Bt.delete(t);
  5265. },
  5266. /**
  5267. * Returns the current count of documents in the target. This includes both
  5268. * the number of documents that the LocalStore considers to be part of the
  5269. * target as well as any accumulated changes.
  5270. */
  5271. t.prototype.Xt = function(t) {
  5272. var e = this.Wt(t).Ct();
  5273. return this.$t.getRemoteKeysForTarget(t).size + e.addedDocuments.size - e.removedDocuments.size;
  5274. },
  5275. /**
  5276. * Increment the number of acks needed from watch before we can consider the
  5277. * server to be 'in-sync' with the client's active targets.
  5278. */
  5279. t.prototype.Ot = function(t) {
  5280. this.Wt(t).Ot();
  5281. }, t.prototype.Wt = function(t) {
  5282. var e = this.Bt.get(t);
  5283. return e || (e = new Or, this.Bt.set(t, e)), e;
  5284. }, t.prototype.ee = function(t) {
  5285. var e = this.qt.get(t);
  5286. return e || (e = new Ze(rt), this.qt = this.qt.insert(t, e)), e;
  5287. },
  5288. /**
  5289. * Verifies that the user is still interested in this target (by calling
  5290. * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs
  5291. * from watch.
  5292. */
  5293. t.prototype.zt = function(t) {
  5294. var e = null !== this.Yt(t);
  5295. return e || V("WatchChangeAggregator", "Detected inactive target", t), e;
  5296. },
  5297. /**
  5298. * Returns the TargetData for an active target (i.e. a target that the user
  5299. * is still interested in that has no outstanding target change requests).
  5300. */
  5301. t.prototype.Yt = function(t) {
  5302. var e = this.Bt.get(t);
  5303. return e && e.Vt ? null : this.$t.ne(t);
  5304. },
  5305. /**
  5306. * Resets the state of a Watch target to its initial state (e.g. sets
  5307. * 'current' to false, clears the resume token and removes its target mapping
  5308. * from all documents).
  5309. */
  5310. t.prototype.Ht = function(t) {
  5311. var e = this;
  5312. this.Bt.set(t, new Or), this.$t.getRemoteKeysForTarget(t).forEach((function(n) {
  5313. e.Qt(t, n, /*updatedDocument=*/ null);
  5314. }));
  5315. },
  5316. /**
  5317. * Returns whether the LocalStore considers the document to be part of the
  5318. * specified target.
  5319. */
  5320. t.prototype.te = function(t, e) {
  5321. return this.$t.getRemoteKeysForTarget(t).has(e);
  5322. }, t;
  5323. }();
  5324. /**
  5325. * A TargetChange specifies the set of changes for a specific target as part of
  5326. * a RemoteEvent. These changes track which documents are added, modified or
  5327. * removed, as well as the target's resume token and whether the target is
  5328. * marked CURRENT.
  5329. * The actual changes *to* documents are not part of the TargetChange since
  5330. * documents may be part of multiple targets.
  5331. */ function Vr() {
  5332. return new He(ft.comparator);
  5333. }
  5334. function Mr() {
  5335. return new He(ft.comparator);
  5336. }
  5337. /**
  5338. * @license
  5339. * Copyright 2017 Google LLC
  5340. *
  5341. * Licensed under the Apache License, Version 2.0 (the "License");
  5342. * you may not use this file except in compliance with the License.
  5343. * You may obtain a copy of the License at
  5344. *
  5345. * http://www.apache.org/licenses/LICENSE-2.0
  5346. *
  5347. * Unless required by applicable law or agreed to in writing, software
  5348. * distributed under the License is distributed on an "AS IS" BASIS,
  5349. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5350. * See the License for the specific language governing permissions and
  5351. * limitations under the License.
  5352. */ var Lr = {
  5353. asc: "ASCENDING",
  5354. desc: "DESCENDING"
  5355. }, Pr = {
  5356. "<": "LESS_THAN",
  5357. "<=": "LESS_THAN_OR_EQUAL",
  5358. ">": "GREATER_THAN",
  5359. ">=": "GREATER_THAN_OR_EQUAL",
  5360. "==": "EQUAL",
  5361. "!=": "NOT_EQUAL",
  5362. "array-contains": "ARRAY_CONTAINS",
  5363. in: "IN",
  5364. "not-in": "NOT_IN",
  5365. "array-contains-any": "ARRAY_CONTAINS_ANY"
  5366. }, qr = {
  5367. and: "AND",
  5368. or: "OR"
  5369. }, Ur = function(t, e) {
  5370. this.databaseId = t, this.wt = e;
  5371. };
  5372. /**
  5373. * This class generates JsonObject values for the Datastore API suitable for
  5374. * sending to either GRPC stub methods or via the JSON/HTTP REST API.
  5375. *
  5376. * The serializer supports both Protobuf.js and Proto3 JSON formats. By
  5377. * setting `useProto3Json` to true, the serializer will use the Proto3 JSON
  5378. * format.
  5379. *
  5380. * For a description of the Proto3 JSON format check
  5381. * https://developers.google.com/protocol-buffers/docs/proto3#json
  5382. *
  5383. * TODO(klimt): We can remove the databaseId argument if we keep the full
  5384. * resource name in documents.
  5385. */
  5386. /**
  5387. * Returns a value for a Date that's appropriate to put into a proto.
  5388. */
  5389. function Br(t, e) {
  5390. return t.wt ? "".concat(new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", ""), ".").concat(("000000000" + e.nanoseconds).slice(-9), "Z") : {
  5391. seconds: "" + e.seconds,
  5392. nanos: e.nanoseconds
  5393. };
  5394. }
  5395. /**
  5396. * Returns a value for bytes that's appropriate to put in a proto.
  5397. *
  5398. * Visible for testing.
  5399. */ function Gr(t, e) {
  5400. return t.wt ? e.toBase64() : e.toUint8Array();
  5401. }
  5402. /**
  5403. * Returns a ByteString based on the proto string value.
  5404. */ function Kr(t, e) {
  5405. return Br(t, e.toTimestamp());
  5406. }
  5407. function jr(t) {
  5408. return U(!!t), at.fromTimestamp(function(t) {
  5409. var e = Zt(t);
  5410. return new ut(e.seconds, e.nanos);
  5411. }(t));
  5412. }
  5413. function Qr(t, e) {
  5414. return function(t) {
  5415. return new ct([ "projects", t.projectId, "databases", t.database ]);
  5416. }(t).child("documents").child(e).canonicalString();
  5417. }
  5418. function zr(t) {
  5419. var e = ct.fromString(t);
  5420. return U(pi(e)), e;
  5421. }
  5422. function Wr(t, e) {
  5423. return Qr(t.databaseId, e.path);
  5424. }
  5425. function Hr(t, e) {
  5426. var n = zr(e);
  5427. if (n.get(1) !== t.databaseId.projectId) throw new j(K.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n.get(1) + " vs " + t.databaseId.projectId);
  5428. if (n.get(3) !== t.databaseId.database) throw new j(K.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n.get(3) + " vs " + t.databaseId.database);
  5429. return new ft(Jr(n));
  5430. }
  5431. function Yr(t, e) {
  5432. return Qr(t.databaseId, e);
  5433. }
  5434. function Xr(t) {
  5435. var e = zr(t);
  5436. // In v1beta1 queries for collections at the root did not have a trailing
  5437. // "/documents". In v1 all resource paths contain "/documents". Preserve the
  5438. // ability to read the v1beta1 form for compatibility with queries persisted
  5439. // in the local target cache.
  5440. return 4 === e.length ? ct.emptyPath() : Jr(e);
  5441. }
  5442. function Zr(t) {
  5443. return new ct([ "projects", t.databaseId.projectId, "databases", t.databaseId.database ]).canonicalString();
  5444. }
  5445. function Jr(t) {
  5446. return U(t.length > 4 && "documents" === t.get(4)), t.popFirst(5)
  5447. /** Creates a Document proto from key and fields (but no create/update time) */;
  5448. }
  5449. function $r(t, e, n) {
  5450. return {
  5451. name: Wr(t, e),
  5452. fields: n.value.mapValue.fields
  5453. };
  5454. }
  5455. function ti(t, e, n) {
  5456. var r = Hr(t, e.name), i = jr(e.updateTime), o = e.createTime ? jr(e.createTime) : at.min(), u = new en({
  5457. mapValue: {
  5458. fields: e.fields
  5459. }
  5460. }), a = rn.newFoundDocument(r, i, o, u);
  5461. return n && a.setHasCommittedMutations(), n ? a.setHasCommittedMutations() : a;
  5462. }
  5463. function ei(t, e) {
  5464. var n;
  5465. if (e instanceof nr) n = {
  5466. update: $r(t, e.key, e.value)
  5467. }; else if (e instanceof cr) n = {
  5468. delete: Wr(t, e.key)
  5469. }; else if (e instanceof rr) n = {
  5470. update: $r(t, e.key, e.data),
  5471. updateMask: di(e.fieldMask)
  5472. }; else {
  5473. if (!(e instanceof lr)) return q();
  5474. n = {
  5475. verify: Wr(t, e.key)
  5476. };
  5477. }
  5478. return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((function(t) {
  5479. return function(t, e) {
  5480. var n = e.transform;
  5481. if (n instanceof Pn) return {
  5482. fieldPath: e.field.canonicalString(),
  5483. setToServerValue: "REQUEST_TIME"
  5484. };
  5485. if (n instanceof qn) return {
  5486. fieldPath: e.field.canonicalString(),
  5487. appendMissingElements: {
  5488. values: n.elements
  5489. }
  5490. };
  5491. if (n instanceof Bn) return {
  5492. fieldPath: e.field.canonicalString(),
  5493. removeAllFromArray: {
  5494. values: n.elements
  5495. }
  5496. };
  5497. if (n instanceof Kn) return {
  5498. fieldPath: e.field.canonicalString(),
  5499. increment: n.gt
  5500. };
  5501. throw q();
  5502. }(0, t);
  5503. }))), e.precondition.isNone || (n.currentDocument = function(t, e) {
  5504. return void 0 !== e.updateTime ? {
  5505. updateTime: Kr(t, e.updateTime)
  5506. } : void 0 !== e.exists ? {
  5507. exists: e.exists
  5508. } : q();
  5509. }(t, e.precondition)), n;
  5510. }
  5511. function ni(t, e) {
  5512. var n = e.currentDocument ? function(t) {
  5513. return void 0 !== t.updateTime ? Hn.updateTime(jr(t.updateTime)) : void 0 !== t.exists ? Hn.exists(t.exists) : Hn.none();
  5514. }(e.currentDocument) : Hn.none(), r = e.updateTransforms ? e.updateTransforms.map((function(e) {
  5515. return function(t, e) {
  5516. var n = null;
  5517. if ("setToServerValue" in e) U("REQUEST_TIME" === e.setToServerValue), n = new Pn; else if ("appendMissingElements" in e) {
  5518. var r = e.appendMissingElements.values || [];
  5519. n = new qn(r);
  5520. } else if ("removeAllFromArray" in e) {
  5521. var i = e.removeAllFromArray.values || [];
  5522. n = new Bn(i);
  5523. } else "increment" in e ? n = new Kn(t, e.increment) : q();
  5524. var o = ht.fromServerFormat(e.fieldPath);
  5525. return new zn(o, n);
  5526. }(t, e);
  5527. })) : [];
  5528. if (e.update) {
  5529. e.update.name;
  5530. var i = Hr(t, e.update.name), o = new en({
  5531. mapValue: {
  5532. fields: e.update.fields
  5533. }
  5534. });
  5535. if (e.updateMask) {
  5536. var u = function(t) {
  5537. var e = t.fieldPaths || [];
  5538. return new tn(e.map((function(t) {
  5539. return ht.fromServerFormat(t);
  5540. })));
  5541. }(e.updateMask);
  5542. return new rr(i, o, u, n, r);
  5543. }
  5544. return new nr(i, o, n, r);
  5545. }
  5546. if (e.delete) {
  5547. var a = Hr(t, e.delete);
  5548. return new cr(a, n);
  5549. }
  5550. if (e.verify) {
  5551. var s = Hr(t, e.verify);
  5552. return new lr(s, n);
  5553. }
  5554. return q();
  5555. }
  5556. function ri(t, e) {
  5557. return {
  5558. documents: [ Yr(t, e.path) ]
  5559. };
  5560. }
  5561. function ii(t, e) {
  5562. // Dissect the path into parent, collectionId, and optional key filter.
  5563. var n = {
  5564. structuredQuery: {}
  5565. }, r = e.path;
  5566. null !== e.collectionGroup ? (n.parent = Yr(t, r), n.structuredQuery.from = [ {
  5567. collectionId: e.collectionGroup,
  5568. allDescendants: !0
  5569. } ]) : (n.parent = Yr(t, r.popLast()), n.structuredQuery.from = [ {
  5570. collectionId: r.lastSegment()
  5571. } ]);
  5572. var i = function(t) {
  5573. if (0 !== t.length) return fi(Ce.create(t, "and" /* CompositeOperator.AND */));
  5574. }(e.filters);
  5575. i && (n.structuredQuery.where = i);
  5576. var o = function(t) {
  5577. if (0 !== t.length) return t.map((function(t) {
  5578. // visible for testing
  5579. return function(t) {
  5580. return {
  5581. field: li(t.field),
  5582. direction: ai(t.dir)
  5583. };
  5584. }(t);
  5585. }));
  5586. }(e.orderBy);
  5587. o && (n.structuredQuery.orderBy = o);
  5588. var u, a = function(t, e) {
  5589. return t.wt || Qt(e) ? e : {
  5590. value: e
  5591. };
  5592. }(t, e.limit);
  5593. return null !== a && (n.structuredQuery.limit = a), e.startAt && (n.structuredQuery.startAt = {
  5594. before: (u = e.startAt).inclusive,
  5595. values: u.position
  5596. }), e.endAt && (n.structuredQuery.endAt = function(t) {
  5597. return {
  5598. before: !t.inclusive,
  5599. values: t.position
  5600. };
  5601. }(e.endAt)), n;
  5602. }
  5603. function oi(t) {
  5604. var e = Xr(t.parent), n = t.structuredQuery, r = n.from ? n.from.length : 0, i = null;
  5605. if (r > 0) {
  5606. U(1 === r);
  5607. var o = n.from[0];
  5608. o.allDescendants ? i = o.collectionId : e = e.child(o.collectionId);
  5609. }
  5610. var u = [];
  5611. n.where && (u = function(t) {
  5612. var e = ui(t);
  5613. return e instanceof Ce && Fe(e) ? e.getFilters() : [ e ];
  5614. }(n.where));
  5615. var a = [];
  5616. n.orderBy && (a = n.orderBy.map((function(t) {
  5617. return function(t) {
  5618. return new ze(hi(t.field),
  5619. // visible for testing
  5620. function(t) {
  5621. switch (t) {
  5622. case "ASCENDING":
  5623. return "asc" /* Direction.ASCENDING */;
  5624. case "DESCENDING":
  5625. return "desc" /* Direction.DESCENDING */;
  5626. default:
  5627. return;
  5628. }
  5629. }(t.direction));
  5630. }(t);
  5631. })));
  5632. var s = null;
  5633. n.limit && (s = function(t) {
  5634. var e;
  5635. return Qt(e = "object" == typeof t ? t.value : t) ? null : e;
  5636. }(n.limit));
  5637. var c = null;
  5638. n.startAt && (c = function(t) {
  5639. var e = !!t.before, n = t.values || [];
  5640. return new Se(n, e);
  5641. }(n.startAt));
  5642. var l = null;
  5643. return n.endAt && (l = function(t) {
  5644. var e = !t.before, n = t.values || [];
  5645. return new Se(n, e);
  5646. }(n.endAt)), pn(e, i, a, u, s, "F" /* LimitType.First */ , c, l);
  5647. }
  5648. function ui(t) {
  5649. return void 0 !== t.unaryFilter ? function(t) {
  5650. switch (t.unaryFilter.op) {
  5651. case "IS_NAN":
  5652. var e = hi(t.unaryFilter.field);
  5653. return Ae.create(e, "==" /* Operator.EQUAL */ , {
  5654. doubleValue: NaN
  5655. });
  5656. case "IS_NULL":
  5657. var n = hi(t.unaryFilter.field);
  5658. return Ae.create(n, "==" /* Operator.EQUAL */ , {
  5659. nullValue: "NULL_VALUE"
  5660. });
  5661. case "IS_NOT_NAN":
  5662. var r = hi(t.unaryFilter.field);
  5663. return Ae.create(r, "!=" /* Operator.NOT_EQUAL */ , {
  5664. doubleValue: NaN
  5665. });
  5666. case "IS_NOT_NULL":
  5667. var i = hi(t.unaryFilter.field);
  5668. return Ae.create(i, "!=" /* Operator.NOT_EQUAL */ , {
  5669. nullValue: "NULL_VALUE"
  5670. });
  5671. default:
  5672. return q();
  5673. }
  5674. }(t) : void 0 !== t.fieldFilter ? function(t) {
  5675. return Ae.create(hi(t.fieldFilter.field), function(t) {
  5676. switch (t) {
  5677. case "EQUAL":
  5678. return "==" /* Operator.EQUAL */;
  5679. case "NOT_EQUAL":
  5680. return "!=" /* Operator.NOT_EQUAL */;
  5681. case "GREATER_THAN":
  5682. return ">" /* Operator.GREATER_THAN */;
  5683. case "GREATER_THAN_OR_EQUAL":
  5684. return ">=" /* Operator.GREATER_THAN_OR_EQUAL */;
  5685. case "LESS_THAN":
  5686. return "<" /* Operator.LESS_THAN */;
  5687. case "LESS_THAN_OR_EQUAL":
  5688. return "<=" /* Operator.LESS_THAN_OR_EQUAL */;
  5689. case "ARRAY_CONTAINS":
  5690. return "array-contains" /* Operator.ARRAY_CONTAINS */;
  5691. case "IN":
  5692. return "in" /* Operator.IN */;
  5693. case "NOT_IN":
  5694. return "not-in" /* Operator.NOT_IN */;
  5695. case "ARRAY_CONTAINS_ANY":
  5696. return "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */;
  5697. default:
  5698. return q();
  5699. }
  5700. }(t.fieldFilter.op), t.fieldFilter.value);
  5701. }(t) : void 0 !== t.compositeFilter ? function(t) {
  5702. return Ce.create(t.compositeFilter.filters.map((function(t) {
  5703. return ui(t);
  5704. })), function(t) {
  5705. switch (t) {
  5706. case "AND":
  5707. return "and" /* CompositeOperator.AND */;
  5708. case "OR":
  5709. return "or" /* CompositeOperator.OR */;
  5710. default:
  5711. return q();
  5712. }
  5713. }(t.compositeFilter.op));
  5714. }(t) : q();
  5715. }
  5716. function ai(t) {
  5717. return Lr[t];
  5718. }
  5719. function si(t) {
  5720. return Pr[t];
  5721. }
  5722. function ci(t) {
  5723. return qr[t];
  5724. }
  5725. function li(t) {
  5726. return {
  5727. fieldPath: t.canonicalString()
  5728. };
  5729. }
  5730. function hi(t) {
  5731. return ht.fromServerFormat(t.fieldPath);
  5732. }
  5733. function fi(t) {
  5734. return t instanceof Ae ? function(t) {
  5735. if ("==" /* Operator.EQUAL */ === t.op) {
  5736. if (ve(t.value)) return {
  5737. unaryFilter: {
  5738. field: li(t.field),
  5739. op: "IS_NAN"
  5740. }
  5741. };
  5742. if (ye(t.value)) return {
  5743. unaryFilter: {
  5744. field: li(t.field),
  5745. op: "IS_NULL"
  5746. }
  5747. };
  5748. } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) {
  5749. if (ve(t.value)) return {
  5750. unaryFilter: {
  5751. field: li(t.field),
  5752. op: "IS_NOT_NAN"
  5753. }
  5754. };
  5755. if (ye(t.value)) return {
  5756. unaryFilter: {
  5757. field: li(t.field),
  5758. op: "IS_NOT_NULL"
  5759. }
  5760. };
  5761. }
  5762. return {
  5763. fieldFilter: {
  5764. field: li(t.field),
  5765. op: si(t.op),
  5766. value: t.value
  5767. }
  5768. };
  5769. }(t) : t instanceof Ce ? function(t) {
  5770. var e = t.getFilters().map((function(t) {
  5771. return fi(t);
  5772. }));
  5773. return 1 === e.length ? e[0] : {
  5774. compositeFilter: {
  5775. op: ci(t.op),
  5776. filters: e
  5777. }
  5778. };
  5779. }(t) : q();
  5780. }
  5781. function di(t) {
  5782. var e = [];
  5783. return t.fields.forEach((function(t) {
  5784. return e.push(t.canonicalString());
  5785. })), {
  5786. fieldPaths: e
  5787. };
  5788. }
  5789. function pi(t) {
  5790. // Resource names have at least 4 components (project ID, database ID)
  5791. return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2);
  5792. }
  5793. /**
  5794. * @license
  5795. * Copyright 2017 Google LLC
  5796. *
  5797. * Licensed under the Apache License, Version 2.0 (the "License");
  5798. * you may not use this file except in compliance with the License.
  5799. * You may obtain a copy of the License at
  5800. *
  5801. * http://www.apache.org/licenses/LICENSE-2.0
  5802. *
  5803. * Unless required by applicable law or agreed to in writing, software
  5804. * distributed under the License is distributed on an "AS IS" BASIS,
  5805. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5806. * See the License for the specific language governing permissions and
  5807. * limitations under the License.
  5808. */
  5809. /**
  5810. * Encodes a resource path into a IndexedDb-compatible string form.
  5811. */ function yi(t) {
  5812. for (var e = "", n = 0; n < t.length; n++) e.length > 0 && (e = mi(e)), e = vi(t.get(n), e);
  5813. return mi(e);
  5814. }
  5815. /** Encodes a single segment of a resource path into the given result */ function vi(t, e) {
  5816. for (var n = e, r = t.length, i = 0; i < r; i++) {
  5817. var o = t.charAt(i);
  5818. switch (o) {
  5819. case "\0":
  5820. n += "";
  5821. break;
  5822. case "":
  5823. n += "";
  5824. break;
  5825. default:
  5826. n += o;
  5827. }
  5828. }
  5829. return n;
  5830. }
  5831. /** Encodes a path separator into the given result */ function mi(t) {
  5832. return t + "";
  5833. }
  5834. /**
  5835. * Decodes the given IndexedDb-compatible string form of a resource path into
  5836. * a ResourcePath instance. Note that this method is not suitable for use with
  5837. * decoding resource names from the server; those are One Platform format
  5838. * strings.
  5839. */ function gi(t) {
  5840. // Event the empty path must encode as a path of at least length 2. A path
  5841. // with exactly 2 must be the empty path.
  5842. var e = t.length;
  5843. if (U(e >= 2), 2 === e) return U("" === t.charAt(0) && "" === t.charAt(1)), ct.emptyPath();
  5844. // Escape characters cannot exist past the second-to-last position in the
  5845. // source value.
  5846. for (var n = e - 2, r = [], i = "", o = 0; o < e; ) {
  5847. // The last two characters of a valid encoded path must be a separator, so
  5848. // there must be an end to this segment.
  5849. var u = t.indexOf("", o);
  5850. switch ((u < 0 || u > n) && q(), t.charAt(u + 1)) {
  5851. case "":
  5852. var a = t.substring(o, u), s = void 0;
  5853. 0 === i.length ?
  5854. // Avoid copying for the common case of a segment that excludes \0
  5855. // and \001
  5856. s = a : (s = i += a, i = ""), r.push(s);
  5857. break;
  5858. case "":
  5859. i += t.substring(o, u), i += "\0";
  5860. break;
  5861. case "":
  5862. // The escape character can be used in the output to encode itself.
  5863. i += t.substring(o, u + 1);
  5864. break;
  5865. default:
  5866. q();
  5867. }
  5868. o = u + 2;
  5869. }
  5870. return new ct(r);
  5871. }
  5872. /**
  5873. * @license
  5874. * Copyright 2022 Google LLC
  5875. *
  5876. * Licensed under the Apache License, Version 2.0 (the "License");
  5877. * you may not use this file except in compliance with the License.
  5878. * You may obtain a copy of the License at
  5879. *
  5880. * http://www.apache.org/licenses/LICENSE-2.0
  5881. *
  5882. * Unless required by applicable law or agreed to in writing, software
  5883. * distributed under the License is distributed on an "AS IS" BASIS,
  5884. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5885. * See the License for the specific language governing permissions and
  5886. * limitations under the License.
  5887. */ var wi = [ "userId", "batchId" ];
  5888. /**
  5889. * @license
  5890. * Copyright 2022 Google LLC
  5891. *
  5892. * Licensed under the Apache License, Version 2.0 (the "License");
  5893. * you may not use this file except in compliance with the License.
  5894. * You may obtain a copy of the License at
  5895. *
  5896. * http://www.apache.org/licenses/LICENSE-2.0
  5897. *
  5898. * Unless required by applicable law or agreed to in writing, software
  5899. * distributed under the License is distributed on an "AS IS" BASIS,
  5900. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5901. * See the License for the specific language governing permissions and
  5902. * limitations under the License.
  5903. */
  5904. /**
  5905. * Name of the IndexedDb object store.
  5906. *
  5907. * Note that the name 'owner' is chosen to ensure backwards compatibility with
  5908. * older clients that only supported single locked access to the persistence
  5909. * layer.
  5910. */
  5911. /**
  5912. * Creates a [userId, encodedPath] key for use in the DbDocumentMutations
  5913. * index to iterate over all at document mutations for a given path or lower.
  5914. */ function bi(t, e) {
  5915. return [ t, yi(e) ];
  5916. }
  5917. /**
  5918. * Creates a full index key of [userId, encodedPath, batchId] for inserting
  5919. * and deleting into the DbDocumentMutations index.
  5920. */ function Ii(t, e, n) {
  5921. return [ t, yi(e), n ];
  5922. }
  5923. /**
  5924. * Because we store all the useful information for this store in the key,
  5925. * there is no useful information to store as the value. The raw (unencoded)
  5926. * path cannot be stored because IndexedDb doesn't store prototype
  5927. * information.
  5928. */ var Ti = {}, Ei = [ "prefixPath", "collectionGroup", "readTime", "documentId" ], Si = [ "prefixPath", "collectionGroup", "documentId" ], _i = [ "collectionGroup", "readTime", "prefixPath", "documentId" ], Di = [ "canonicalId", "targetId" ], xi = [ "targetId", "path" ], Ai = [ "path", "targetId" ], Ci = [ "collectionId", "parent" ], Ni = [ "indexId", "uid" ], ki = [ "uid", "sequenceNumber" ], Fi = [ "indexId", "uid", "arrayValue", "directionalValue", "orderedDocumentKey", "documentKey" ], Oi = [ "indexId", "uid", "orderedDocumentKey" ], Ri = [ "userId", "collectionPath", "documentId" ], Vi = [ "userId", "collectionPath", "largestBatchId" ], Mi = [ "userId", "collectionGroup", "largestBatchId" ], Li = r(r([], r(r([], r(r([], r(r([], [ "mutationQueues", "mutations", "documentMutations", "remoteDocuments", "targets", "owner", "targetGlobal", "targetDocuments" ], !1), [ "clientMetadata" ], !1), !0), [ "remoteDocumentGlobal" ], !1), !0), [ "collectionParents" ], !1), !0), [ "bundles", "namedQueries" ], !1), Pi = r(r([], Li, !0), [ "documentOverlays" ], !1), qi = [ "mutationQueues", "mutations", "documentMutations", "remoteDocumentsV14", "targets", "owner", "targetGlobal", "targetDocuments", "clientMetadata", "remoteDocumentGlobal", "collectionParents", "bundles", "namedQueries", "documentOverlays" ], Ui = qi, Bi = r(r([], Ui, !0), [ "indexConfiguration", "indexState", "indexEntries" ], !1), Gi = /** @class */ function(e) {
  5929. function n(t, n) {
  5930. var r = this;
  5931. return (r = e.call(this) || this).se = t, r.currentSequenceNumber = n, r;
  5932. }
  5933. return t(n, e), n;
  5934. }(_t);
  5935. /**
  5936. * @license
  5937. * Copyright 2020 Google LLC
  5938. *
  5939. * Licensed under the Apache License, Version 2.0 (the "License");
  5940. * you may not use this file except in compliance with the License.
  5941. * You may obtain a copy of the License at
  5942. *
  5943. * http://www.apache.org/licenses/LICENSE-2.0
  5944. *
  5945. * Unless required by applicable law or agreed to in writing, software
  5946. * distributed under the License is distributed on an "AS IS" BASIS,
  5947. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5948. * See the License for the specific language governing permissions and
  5949. * limitations under the License.
  5950. */ function Ki(t, e) {
  5951. var n = G(t);
  5952. return Ct.M(n.se, e);
  5953. }
  5954. /**
  5955. * @license
  5956. * Copyright 2017 Google LLC
  5957. *
  5958. * Licensed under the Apache License, Version 2.0 (the "License");
  5959. * you may not use this file except in compliance with the License.
  5960. * You may obtain a copy of the License at
  5961. *
  5962. * http://www.apache.org/licenses/LICENSE-2.0
  5963. *
  5964. * Unless required by applicable law or agreed to in writing, software
  5965. * distributed under the License is distributed on an "AS IS" BASIS,
  5966. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5967. * See the License for the specific language governing permissions and
  5968. * limitations under the License.
  5969. */
  5970. /**
  5971. * A batch of mutations that will be sent as one unit to the backend.
  5972. */ var ji = /** @class */ function() {
  5973. /**
  5974. * @param batchId - The unique ID of this mutation batch.
  5975. * @param localWriteTime - The original write time of this mutation.
  5976. * @param baseMutations - Mutations that are used to populate the base
  5977. * values when this mutation is applied locally. This can be used to locally
  5978. * overwrite values that are persisted in the remote document cache. Base
  5979. * mutations are never sent to the backend.
  5980. * @param mutations - The user-provided mutations in this mutation batch.
  5981. * User-provided mutations are applied both locally and remotely on the
  5982. * backend.
  5983. */
  5984. function t(t, e, n, r) {
  5985. this.batchId = t, this.localWriteTime = e, this.baseMutations = n, this.mutations = r
  5986. /**
  5987. * Applies all the mutations in this MutationBatch to the specified document
  5988. * to compute the state of the remote document
  5989. *
  5990. * @param document - The document to apply mutations to.
  5991. * @param batchResult - The result of applying the MutationBatch to the
  5992. * backend.
  5993. */;
  5994. }
  5995. return t.prototype.applyToRemoteDocument = function(t, e) {
  5996. for (var n = e.mutationResults, r = 0; r < this.mutations.length; r++) {
  5997. var i = this.mutations[r];
  5998. i.key.isEqual(t.key) && Jn(i, t, n[r]);
  5999. }
  6000. },
  6001. /**
  6002. * Computes the local view of a document given all the mutations in this
  6003. * batch.
  6004. *
  6005. * @param document - The document to apply mutations to.
  6006. * @param mutatedFields - Fields that have been updated before applying this mutation batch.
  6007. * @returns A `FieldMask` representing all the fields that are mutated.
  6008. */
  6009. t.prototype.applyToLocalView = function(t, e) {
  6010. // First, apply the base state. This allows us to apply non-idempotent
  6011. // transform against a consistent set of values.
  6012. for (var n = 0, r = this.baseMutations; n < r.length; n++) {
  6013. var i = r[n];
  6014. i.key.isEqual(t.key) && (e = $n(i, t, e, this.localWriteTime));
  6015. }
  6016. // Second, apply all user-provided mutations.
  6017. for (var o = 0, u = this.mutations; o < u.length; o++) {
  6018. var a = u[o];
  6019. a.key.isEqual(t.key) && (e = $n(a, t, e, this.localWriteTime));
  6020. }
  6021. return e;
  6022. },
  6023. /**
  6024. * Computes the local view for all provided documents given the mutations in
  6025. * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to
  6026. * replace all the mutation applications.
  6027. */
  6028. t.prototype.applyToLocalDocumentSet = function(t, e) {
  6029. var n = this, r = Ir();
  6030. // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations
  6031. // directly (as done in `applyToLocalView()`), we can reduce the complexity
  6032. // to O(n).
  6033. return this.mutations.forEach((function(i) {
  6034. var o = t.get(i.key), u = o.overlayedDocument, a = n.applyToLocalView(u, o.mutatedFields), s = Zn(u,
  6035. // Set mutatedFields to null if the document is only from local mutations.
  6036. // This creates a Set or Delete mutation, instead of trying to create a
  6037. // patch mutation as the overlay.
  6038. a = e.has(i.key) ? null : a);
  6039. // TODO(mutabledocuments): This method should take a MutableDocumentMap
  6040. // and we should remove this cast.
  6041. null !== s && r.set(i.key, s), u.isValidDocument() || u.convertToNoDocument(at.min());
  6042. })), r;
  6043. }, t.prototype.keys = function() {
  6044. return this.mutations.reduce((function(t, e) {
  6045. return t.add(e.key);
  6046. }), _r());
  6047. }, t.prototype.isEqual = function(t) {
  6048. return this.batchId === t.batchId && it(this.mutations, t.mutations, (function(t, e) {
  6049. return er(t, e);
  6050. })) && it(this.baseMutations, t.baseMutations, (function(t, e) {
  6051. return er(t, e);
  6052. }));
  6053. }, t;
  6054. }(), Qi = /** @class */ function() {
  6055. function t(t, e, n,
  6056. /**
  6057. * A pre-computed mapping from each mutated document to the resulting
  6058. * version.
  6059. */
  6060. r) {
  6061. this.batch = t, this.commitVersion = e, this.mutationResults = n, this.docVersions = r
  6062. /**
  6063. * Creates a new MutationBatchResult for the given batch and results. There
  6064. * must be one result for each mutation in the batch. This static factory
  6065. * caches a document=&gt;version mapping (docVersions).
  6066. */;
  6067. }
  6068. return t.from = function(e, n, r) {
  6069. U(e.mutations.length === r.length);
  6070. for (var i = Er, o = e.mutations, u = 0; u < o.length; u++) i = i.insert(o[u].key, r[u].version);
  6071. return new t(e, n, r, i);
  6072. }, t;
  6073. }(), zi = /** @class */ function() {
  6074. function t(t, e) {
  6075. this.largestBatchId = t, this.mutation = e;
  6076. }
  6077. return t.prototype.getKey = function() {
  6078. return this.mutation.key;
  6079. }, t.prototype.isEqual = function(t) {
  6080. return null !== t && this.mutation === t.mutation;
  6081. }, t.prototype.toString = function() {
  6082. return "Overlay{\n largestBatchId: ".concat(this.largestBatchId, ",\n mutation: ").concat(this.mutation.toString(), "\n }");
  6083. }, t;
  6084. }(), Wi = /** @class */ function() {
  6085. function t(
  6086. /** The target being listened to. */
  6087. t,
  6088. /**
  6089. * The target ID to which the target corresponds; Assigned by the
  6090. * LocalStore for user listens and by the SyncEngine for limbo watches.
  6091. */
  6092. e,
  6093. /** The purpose of the target. */
  6094. n,
  6095. /**
  6096. * The sequence number of the last transaction during which this target data
  6097. * was modified.
  6098. */
  6099. r,
  6100. /** The latest snapshot version seen for this target. */
  6101. i
  6102. /**
  6103. * The maximum snapshot version at which the associated view
  6104. * contained no limbo documents.
  6105. */ , o
  6106. /**
  6107. * An opaque, server-assigned token that allows watching a target to be
  6108. * resumed after disconnecting without retransmitting all the data that
  6109. * matches the target. The resume token essentially identifies a point in
  6110. * time from which the server should resume sending results.
  6111. */ , u) {
  6112. void 0 === i && (i = at.min()), void 0 === o && (o = at.min()), void 0 === u && (u = Yt.EMPTY_BYTE_STRING),
  6113. this.target = t, this.targetId = e, this.purpose = n, this.sequenceNumber = r, this.snapshotVersion = i,
  6114. this.lastLimboFreeSnapshotVersion = o, this.resumeToken = u;
  6115. }
  6116. /** Creates a new target data instance with an updated sequence number. */ return t.prototype.withSequenceNumber = function(e) {
  6117. return new t(this.target, this.targetId, this.purpose, e, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken);
  6118. },
  6119. /**
  6120. * Creates a new target data instance with an updated resume token and
  6121. * snapshot version.
  6122. */
  6123. t.prototype.withResumeToken = function(e, n) {
  6124. return new t(this.target, this.targetId, this.purpose, this.sequenceNumber, n, this.lastLimboFreeSnapshotVersion, e);
  6125. },
  6126. /**
  6127. * Creates a new target data instance with an updated last limbo free
  6128. * snapshot version number.
  6129. */
  6130. t.prototype.withLastLimboFreeSnapshotVersion = function(e) {
  6131. return new t(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, e, this.resumeToken);
  6132. }, t;
  6133. }(), Hi = function(t) {
  6134. this.ie = t;
  6135. };
  6136. /** The result of applying a mutation batch to the backend. */
  6137. /** Encodes a document for storage locally. */ function Yi(t, e) {
  6138. var n = e.key, r = {
  6139. prefixPath: n.getCollectionPath().popLast().toArray(),
  6140. collectionGroup: n.collectionGroup,
  6141. documentId: n.path.lastSegment(),
  6142. readTime: Xi(e.readTime),
  6143. hasCommittedMutations: e.hasCommittedMutations
  6144. };
  6145. if (e.isFoundDocument()) r.document = function(t, e) {
  6146. return {
  6147. name: Wr(t, e.key),
  6148. fields: e.data.value.mapValue.fields,
  6149. updateTime: Br(t, e.version.toTimestamp()),
  6150. createTime: Br(t, e.createTime.toTimestamp())
  6151. };
  6152. }(t.ie, e); else if (e.isNoDocument()) r.noDocument = {
  6153. path: n.path.toArray(),
  6154. readTime: Zi(e.version)
  6155. }; else {
  6156. if (!e.isUnknownDocument()) return q();
  6157. r.unknownDocument = {
  6158. path: n.path.toArray(),
  6159. version: Zi(e.version)
  6160. };
  6161. }
  6162. return r;
  6163. }
  6164. function Xi(t) {
  6165. var e = t.toTimestamp();
  6166. return [ e.seconds, e.nanoseconds ];
  6167. }
  6168. function Zi(t) {
  6169. var e = t.toTimestamp();
  6170. return {
  6171. seconds: e.seconds,
  6172. nanoseconds: e.nanoseconds
  6173. };
  6174. }
  6175. function Ji(t) {
  6176. var e = new ut(t.seconds, t.nanoseconds);
  6177. return at.fromTimestamp(e);
  6178. }
  6179. /** Encodes a batch of mutations into a DbMutationBatch for local storage. */
  6180. /** Decodes a DbMutationBatch into a MutationBatch */ function $i(t, e) {
  6181. // Squash old transform mutations into existing patch or set mutations.
  6182. // The replacement of representing `transforms` with `update_transforms`
  6183. // on the SDK means that old `transform` mutations stored in IndexedDB need
  6184. // to be updated to `update_transforms`.
  6185. // TODO(b/174608374): Remove this code once we perform a schema migration.
  6186. for (var n = (e.baseMutations || []).map((function(e) {
  6187. return ni(t.ie, e);
  6188. })), r = 0; r < e.mutations.length - 1; ++r) {
  6189. var i = e.mutations[r];
  6190. if (r + 1 < e.mutations.length && void 0 !== e.mutations[r + 1].transform) {
  6191. var o = e.mutations[r + 1];
  6192. i.updateTransforms = o.transform.fieldTransforms, e.mutations.splice(r + 1, 1),
  6193. ++r;
  6194. }
  6195. }
  6196. var u = e.mutations.map((function(e) {
  6197. return ni(t.ie, e);
  6198. })), a = ut.fromMillis(e.localWriteTimeMs);
  6199. return new ji(e.batchId, a, n, u);
  6200. }
  6201. /** Decodes a DbTarget into TargetData */ function to(t) {
  6202. var e, n, r = Ji(t.readTime), i = void 0 !== t.lastLimboFreeSnapshotVersion ? Ji(t.lastLimboFreeSnapshotVersion) : at.min();
  6203. return void 0 !== t.query.documents ? (U(1 === (n = t.query).documents.length),
  6204. e = In(yn(Xr(n.documents[0])))) : e = function(t) {
  6205. return In(oi(t));
  6206. }(t.query), new Wi(e, t.targetId, 0 /* TargetPurpose.Listen */ , t.lastListenSequenceNumber, r, i, Yt.fromBase64String(t.resumeToken))
  6207. /** Encodes TargetData into a DbTarget for storage locally. */;
  6208. }
  6209. function eo(t, e) {
  6210. var n, r = Zi(e.snapshotVersion), i = Zi(e.lastLimboFreeSnapshotVersion);
  6211. n = cn(e.target) ? ri(t.ie, e.target) : ii(t.ie, e.target);
  6212. // We can't store the resumeToken as a ByteString in IndexedDb, so we
  6213. // convert it to a base64 string for storage.
  6214. var o = e.resumeToken.toBase64();
  6215. // lastListenSequenceNumber is always 0 until we do real GC.
  6216. return {
  6217. targetId: e.targetId,
  6218. canonicalId: an(e.target),
  6219. readTime: r,
  6220. resumeToken: o,
  6221. lastListenSequenceNumber: e.sequenceNumber,
  6222. lastLimboFreeSnapshotVersion: i,
  6223. query: n
  6224. };
  6225. }
  6226. /**
  6227. * A helper function for figuring out what kind of query has been stored.
  6228. */
  6229. /**
  6230. * Encodes a `BundledQuery` from bundle proto to a Query object.
  6231. *
  6232. * This reconstructs the original query used to build the bundle being loaded,
  6233. * including features exists only in SDKs (for example: limit-to-last).
  6234. */ function no(t) {
  6235. var e = oi({
  6236. parent: t.parent,
  6237. structuredQuery: t.structuredQuery
  6238. });
  6239. return "LAST" === t.limitType ? En(e, e.limit, "L" /* LimitType.Last */) : e;
  6240. }
  6241. /** Encodes a NamedQuery proto object to a NamedQuery model object. */
  6242. /** Encodes a DbDocumentOverlay object to an Overlay model object. */ function ro(t, e) {
  6243. return new zi(e.largestBatchId, ni(t.ie, e.overlayMutation));
  6244. }
  6245. /** Decodes an Overlay model object into a DbDocumentOverlay object. */
  6246. /**
  6247. * Returns the DbDocumentOverlayKey corresponding to the given user and
  6248. * document key.
  6249. */ function io(t, e) {
  6250. var n = e.path.lastSegment();
  6251. return [ t, yi(e.path.popLast()), n ];
  6252. }
  6253. function oo(t, e, n, r) {
  6254. return {
  6255. indexId: t,
  6256. uid: e.uid || "",
  6257. sequenceNumber: n,
  6258. readTime: Zi(r.readTime),
  6259. documentKey: yi(r.documentKey.path),
  6260. largestBatchId: r.largestBatchId
  6261. };
  6262. }
  6263. /**
  6264. * @license
  6265. * Copyright 2020 Google LLC
  6266. *
  6267. * Licensed under the Apache License, Version 2.0 (the "License");
  6268. * you may not use this file except in compliance with the License.
  6269. * You may obtain a copy of the License at
  6270. *
  6271. * http://www.apache.org/licenses/LICENSE-2.0
  6272. *
  6273. * Unless required by applicable law or agreed to in writing, software
  6274. * distributed under the License is distributed on an "AS IS" BASIS,
  6275. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6276. * See the License for the specific language governing permissions and
  6277. * limitations under the License.
  6278. */ var uo = /** @class */ function() {
  6279. function t() {}
  6280. return t.prototype.getBundleMetadata = function(t, e) {
  6281. return ao(t).get(e).next((function(t) {
  6282. if (t) return {
  6283. id: (e = t).bundleId,
  6284. createTime: Ji(e.createTime),
  6285. version: e.version
  6286. };
  6287. /** Encodes a DbBundle to a BundleMetadata object. */ var e;
  6288. /** Encodes a BundleMetadata to a DbBundle. */ }));
  6289. }, t.prototype.saveBundleMetadata = function(t, e) {
  6290. return ao(t).put({
  6291. bundleId: (n = e).id,
  6292. createTime: Zi(jr(n.createTime)),
  6293. version: n.version
  6294. });
  6295. var n;
  6296. /** Encodes a DbNamedQuery to a NamedQuery. */ }, t.prototype.getNamedQuery = function(t, e) {
  6297. return so(t).get(e).next((function(t) {
  6298. if (t) return {
  6299. name: (e = t).name,
  6300. query: no(e.bundledQuery),
  6301. readTime: Ji(e.readTime)
  6302. };
  6303. var e;
  6304. /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ }));
  6305. }, t.prototype.saveNamedQuery = function(t, e) {
  6306. return so(t).put(function(t) {
  6307. return {
  6308. name: t.name,
  6309. readTime: Zi(jr(t.readTime)),
  6310. bundledQuery: t.bundledQuery
  6311. };
  6312. }(e));
  6313. }, t;
  6314. }();
  6315. /**
  6316. * Helper to get a typed SimpleDbStore for the bundles object store.
  6317. */ function ao(t) {
  6318. return Ki(t, "bundles");
  6319. }
  6320. /**
  6321. * Helper to get a typed SimpleDbStore for the namedQueries object store.
  6322. */ function so(t) {
  6323. return Ki(t, "namedQueries");
  6324. }
  6325. /**
  6326. * @license
  6327. * Copyright 2022 Google LLC
  6328. *
  6329. * Licensed under the Apache License, Version 2.0 (the "License");
  6330. * you may not use this file except in compliance with the License.
  6331. * You may obtain a copy of the License at
  6332. *
  6333. * http://www.apache.org/licenses/LICENSE-2.0
  6334. *
  6335. * Unless required by applicable law or agreed to in writing, software
  6336. * distributed under the License is distributed on an "AS IS" BASIS,
  6337. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6338. * See the License for the specific language governing permissions and
  6339. * limitations under the License.
  6340. */
  6341. /**
  6342. * Implementation of DocumentOverlayCache using IndexedDb.
  6343. */ var co = /** @class */ function() {
  6344. /**
  6345. * @param serializer - The document serializer.
  6346. * @param userId - The userId for which we are accessing overlays.
  6347. */
  6348. function t(t, e) {
  6349. this.yt = t, this.userId = e;
  6350. }
  6351. return t.re = function(e, n) {
  6352. return new t(e, n.uid || "");
  6353. }, t.prototype.getOverlay = function(t, e) {
  6354. var n = this;
  6355. return lo(t).get(io(this.userId, e)).next((function(t) {
  6356. return t ? ro(n.yt, t) : null;
  6357. }));
  6358. }, t.prototype.getOverlays = function(t, e) {
  6359. var n = this, r = br();
  6360. return xt.forEach(e, (function(e) {
  6361. return n.getOverlay(t, e).next((function(t) {
  6362. null !== t && r.set(e, t);
  6363. }));
  6364. })).next((function() {
  6365. return r;
  6366. }));
  6367. }, t.prototype.saveOverlays = function(t, e, n) {
  6368. var r = this, i = [];
  6369. return n.forEach((function(n, o) {
  6370. var u = new zi(e, o);
  6371. i.push(r.oe(t, u));
  6372. })), xt.waitFor(i);
  6373. }, t.prototype.removeOverlaysForBatchId = function(t, e, n) {
  6374. var r = this, i = new Set;
  6375. // Get the set of unique collection paths.
  6376. e.forEach((function(t) {
  6377. return i.add(yi(t.getCollectionPath()));
  6378. }));
  6379. var o = [];
  6380. return i.forEach((function(e) {
  6381. var i = IDBKeyRange.bound([ r.userId, e, n ], [ r.userId, e, n + 1 ],
  6382. /*lowerOpen=*/ !1,
  6383. /*upperOpen=*/ !0);
  6384. o.push(lo(t).Y("collectionPathOverlayIndex", i));
  6385. })), xt.waitFor(o);
  6386. }, t.prototype.getOverlaysForCollection = function(t, e, n) {
  6387. var r = this, i = br(), o = yi(e), u = IDBKeyRange.bound([ this.userId, o, n ], [ this.userId, o, Number.POSITIVE_INFINITY ],
  6388. /*lowerOpen=*/ !0);
  6389. return lo(t).W("collectionPathOverlayIndex", u).next((function(t) {
  6390. for (var e = 0, n = t; e < n.length; e++) {
  6391. var o = n[e], u = ro(r.yt, o);
  6392. i.set(u.getKey(), u);
  6393. }
  6394. return i;
  6395. }));
  6396. }, t.prototype.getOverlaysForCollectionGroup = function(t, e, n, r) {
  6397. var i, o = this, u = br(), a = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, Number.POSITIVE_INFINITY ],
  6398. /*lowerOpen=*/ !0);
  6399. return lo(t).Z({
  6400. index: "collectionGroupOverlayIndex",
  6401. range: a
  6402. }, (function(t, e, n) {
  6403. // We do not want to return partial batch overlays, even if the size
  6404. // of the result set exceeds the given `count` argument. Therefore, we
  6405. // continue to aggregate results even after the result size exceeds
  6406. // `count` if there are more overlays from the `currentBatchId`.
  6407. var a = ro(o.yt, e);
  6408. u.size() < r || a.largestBatchId === i ? (u.set(a.getKey(), a), i = a.largestBatchId) : n.done();
  6409. })).next((function() {
  6410. return u;
  6411. }));
  6412. }, t.prototype.oe = function(t, e) {
  6413. return lo(t).put(function(t, e, n) {
  6414. var r = io(e, n.mutation.key);
  6415. return r[0], {
  6416. userId: e,
  6417. collectionPath: r[1],
  6418. documentId: r[2],
  6419. collectionGroup: n.mutation.key.getCollectionGroup(),
  6420. largestBatchId: n.largestBatchId,
  6421. overlayMutation: ei(t.ie, n.mutation)
  6422. };
  6423. }(this.yt, this.userId, e));
  6424. }, t;
  6425. }();
  6426. /**
  6427. * Helper to get a typed SimpleDbStore for the document overlay object store.
  6428. */ function lo(t) {
  6429. return Ki(t, "documentOverlays");
  6430. }
  6431. /**
  6432. * @license
  6433. * Copyright 2021 Google LLC
  6434. *
  6435. * Licensed under the Apache License, Version 2.0 (the "License");
  6436. * you may not use this file except in compliance with the License.
  6437. * You may obtain a copy of the License at
  6438. *
  6439. * http://www.apache.org/licenses/LICENSE-2.0
  6440. *
  6441. * Unless required by applicable law or agreed to in writing, software
  6442. * distributed under the License is distributed on an "AS IS" BASIS,
  6443. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6444. * See the License for the specific language governing permissions and
  6445. * limitations under the License.
  6446. */
  6447. // Note: This code is copied from the backend. Code that is not used by
  6448. // Firestore was removed.
  6449. /** Firestore index value writer. */ var ho = /** @class */ function() {
  6450. function t() {}
  6451. // The write methods below short-circuit writing terminators for values
  6452. // containing a (terminating) truncated value.
  6453. // As an example, consider the resulting encoding for:
  6454. // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM)
  6455. // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC)
  6456. // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC)
  6457. /** Writes an index value. */ return t.prototype.ue = function(t, e) {
  6458. this.ce(t, e),
  6459. // Write separator to split index values
  6460. // (see go/firestore-storage-format#encodings).
  6461. e.ae();
  6462. }, t.prototype.ce = function(t, e) {
  6463. if ("nullValue" in t) this.he(e, 5); else if ("booleanValue" in t) this.he(e, 10),
  6464. e.le(t.booleanValue ? 1 : 0); else if ("integerValue" in t) this.he(e, 15), e.le(Jt(t.integerValue)); else if ("doubleValue" in t) {
  6465. var n = Jt(t.doubleValue);
  6466. isNaN(n) ? this.he(e, 13) : (this.he(e, 15), zt(n) ?
  6467. // -0.0, 0 and 0.0 are all considered the same
  6468. e.le(0) : e.le(n));
  6469. } else if ("timestampValue" in t) {
  6470. var r = t.timestampValue;
  6471. this.he(e, 20), "string" == typeof r ? e.fe(r) : (e.fe("".concat(r.seconds || "")),
  6472. e.le(r.nanos || 0));
  6473. } else if ("stringValue" in t) this.de(t.stringValue, e), this._e(e); else if ("bytesValue" in t) this.he(e, 30),
  6474. e.we($t(t.bytesValue)), this._e(e); else if ("referenceValue" in t) this.me(t.referenceValue, e); else if ("geoPointValue" in t) {
  6475. var i = t.geoPointValue;
  6476. this.he(e, 45), e.le(i.latitude || 0), e.le(i.longitude || 0);
  6477. } else "mapValue" in t ? we(t) ? this.he(e, Number.MAX_SAFE_INTEGER) : (this.ge(t.mapValue, e),
  6478. this._e(e)) : "arrayValue" in t ? (this.ye(t.arrayValue, e), this._e(e)) : q();
  6479. }, t.prototype.de = function(t, e) {
  6480. this.he(e, 25), this.pe(t, e);
  6481. }, t.prototype.pe = function(t, e) {
  6482. e.fe(t);
  6483. }, t.prototype.ge = function(t, e) {
  6484. var n = t.fields || {};
  6485. this.he(e, 55);
  6486. for (var r = 0, i = Object.keys(n); r < i.length; r++) {
  6487. var o = i[r];
  6488. this.de(o, e), this.ce(n[o], e);
  6489. }
  6490. }, t.prototype.ye = function(t, e) {
  6491. var n = t.values || [];
  6492. this.he(e, 50);
  6493. for (var r = 0, i = n; r < i.length; r++) {
  6494. var o = i[r];
  6495. this.ce(o, e);
  6496. }
  6497. }, t.prototype.me = function(t, e) {
  6498. var n = this;
  6499. this.he(e, 37), ft.fromName(t).path.forEach((function(t) {
  6500. n.he(e, 60), n.pe(t, e);
  6501. }));
  6502. }, t.prototype.he = function(t, e) {
  6503. t.le(e);
  6504. }, t.prototype._e = function(t) {
  6505. // While the SDK does not implement truncation, the truncation marker is
  6506. // used to terminate all variable length values (which are strings, bytes,
  6507. // references, arrays and maps).
  6508. t.le(2);
  6509. }, t;
  6510. }();
  6511. /**
  6512. * Counts the number of zeros in a byte.
  6513. *
  6514. * Visible for testing.
  6515. */
  6516. function fo(t) {
  6517. if (0 === t) return 8;
  6518. var e = 0;
  6519. return t >> 4 == 0 && (
  6520. // Test if the first four bits are zero.
  6521. e += 4, t <<= 4), t >> 6 == 0 && (
  6522. // Test if the first two (or next two) bits are zero.
  6523. e += 2, t <<= 2), t >> 7 == 0 && (
  6524. // Test if the remaining bit is zero.
  6525. e += 1), e
  6526. /** Counts the number of leading zeros in the given byte array. */
  6527. /**
  6528. * Returns the number of bytes required to store "value". Leading zero bytes
  6529. * are skipped.
  6530. */;
  6531. }
  6532. function po(t) {
  6533. // This is just the number of bytes for the unsigned representation of the number.
  6534. var e = 64 - function(t) {
  6535. for (var e = 0, n = 0; n < 8; ++n) {
  6536. var r = fo(255 & t[n]);
  6537. if (e += r, 8 !== r) break;
  6538. }
  6539. return e;
  6540. }(t);
  6541. return Math.ceil(e / 8);
  6542. }
  6543. /**
  6544. * OrderedCodeWriter is a minimal-allocation implementation of the writing
  6545. * behavior defined by the backend.
  6546. *
  6547. * The code is ported from its Java counterpart.
  6548. */ ho.Ie = new ho;
  6549. var yo = /** @class */ function() {
  6550. function t() {
  6551. this.buffer = new Uint8Array(1024), this.position = 0;
  6552. }
  6553. return t.prototype.Te = function(t) {
  6554. for (var e = t[Symbol.iterator](), n = e.next(); !n.done; ) this.Ee(n.value), n = e.next();
  6555. this.Ae();
  6556. }, t.prototype.Re = function(t) {
  6557. for (var e = t[Symbol.iterator](), n = e.next(); !n.done; ) this.be(n.value), n = e.next();
  6558. this.Pe();
  6559. },
  6560. /** Writes utf8 bytes into this byte sequence, ascending. */ t.prototype.ve = function(t) {
  6561. for (var e = 0, n = t; e < n.length; e++) {
  6562. var r = n[e], i = r.charCodeAt(0);
  6563. if (i < 128) this.Ee(i); else if (i < 2048) this.Ee(960 | i >>> 6), this.Ee(128 | 63 & i); else if (r < "\ud800" || "\udbff" < r) this.Ee(480 | i >>> 12),
  6564. this.Ee(128 | 63 & i >>> 6), this.Ee(128 | 63 & i); else {
  6565. var o = r.codePointAt(0);
  6566. this.Ee(240 | o >>> 18), this.Ee(128 | 63 & o >>> 12), this.Ee(128 | 63 & o >>> 6),
  6567. this.Ee(128 | 63 & o);
  6568. }
  6569. }
  6570. this.Ae();
  6571. },
  6572. /** Writes utf8 bytes into this byte sequence, descending */ t.prototype.Ve = function(t) {
  6573. for (var e = 0, n = t; e < n.length; e++) {
  6574. var r = n[e], i = r.charCodeAt(0);
  6575. if (i < 128) this.be(i); else if (i < 2048) this.be(960 | i >>> 6), this.be(128 | 63 & i); else if (r < "\ud800" || "\udbff" < r) this.be(480 | i >>> 12),
  6576. this.be(128 | 63 & i >>> 6), this.be(128 | 63 & i); else {
  6577. var o = r.codePointAt(0);
  6578. this.be(240 | o >>> 18), this.be(128 | 63 & o >>> 12), this.be(128 | 63 & o >>> 6),
  6579. this.be(128 | 63 & o);
  6580. }
  6581. }
  6582. this.Pe();
  6583. }, t.prototype.Se = function(t) {
  6584. // Values are encoded with a single byte length prefix, followed by the
  6585. // actual value in big-endian format with leading 0 bytes dropped.
  6586. var e = this.De(t), n = po(e);
  6587. this.Ce(1 + n), this.buffer[this.position++] = 255 & n;
  6588. // Write the length
  6589. for (var r = e.length - n; r < e.length; ++r) this.buffer[this.position++] = 255 & e[r];
  6590. }, t.prototype.xe = function(t) {
  6591. // Values are encoded with a single byte length prefix, followed by the
  6592. // inverted value in big-endian format with leading 0 bytes dropped.
  6593. var e = this.De(t), n = po(e);
  6594. this.Ce(1 + n), this.buffer[this.position++] = ~(255 & n);
  6595. // Write the length
  6596. for (var r = e.length - n; r < e.length; ++r) this.buffer[this.position++] = ~(255 & e[r]);
  6597. },
  6598. /**
  6599. * Writes the "infinity" byte sequence that sorts after all other byte
  6600. * sequences written in ascending order.
  6601. */
  6602. t.prototype.Ne = function() {
  6603. this.ke(255), this.ke(255);
  6604. },
  6605. /**
  6606. * Writes the "infinity" byte sequence that sorts before all other byte
  6607. * sequences written in descending order.
  6608. */
  6609. t.prototype.Oe = function() {
  6610. this.Me(255), this.Me(255);
  6611. },
  6612. /**
  6613. * Resets the buffer such that it is the same as when it was newly
  6614. * constructed.
  6615. */
  6616. t.prototype.reset = function() {
  6617. this.position = 0;
  6618. }, t.prototype.seed = function(t) {
  6619. this.Ce(t.length), this.buffer.set(t, this.position), this.position += t.length;
  6620. },
  6621. /** Makes a copy of the encoded bytes in this buffer. */ t.prototype.Fe = function() {
  6622. return this.buffer.slice(0, this.position);
  6623. },
  6624. /**
  6625. * Encodes `val` into an encoding so that the order matches the IEEE 754
  6626. * floating-point comparison results with the following exceptions:
  6627. * -0.0 < 0.0
  6628. * all non-NaN < NaN
  6629. * NaN = NaN
  6630. */
  6631. t.prototype.De = function(t) {
  6632. var e =
  6633. /** Converts a JavaScript number to a byte array (using big endian encoding). */
  6634. function(t) {
  6635. var e = new DataView(new ArrayBuffer(8));
  6636. return e.setFloat64(0, t, /* littleEndian= */ !1), new Uint8Array(e.buffer);
  6637. }(t), n = 0 != (128 & e[0]);
  6638. // Check if the first bit is set. We use a bit mask since value[0] is
  6639. // encoded as a number from 0 to 255.
  6640. // Revert the two complement to get natural ordering
  6641. e[0] ^= n ? 255 : 128;
  6642. for (var r = 1; r < e.length; ++r) e[r] ^= n ? 255 : 0;
  6643. return e;
  6644. },
  6645. /** Writes a single byte ascending to the buffer. */ t.prototype.Ee = function(t) {
  6646. var e = 255 & t;
  6647. 0 === e ? (this.ke(0), this.ke(255)) : 255 === e ? (this.ke(255), this.ke(0)) : this.ke(e);
  6648. },
  6649. /** Writes a single byte descending to the buffer. */ t.prototype.be = function(t) {
  6650. var e = 255 & t;
  6651. 0 === e ? (this.Me(0), this.Me(255)) : 255 === e ? (this.Me(255), this.Me(0)) : this.Me(t);
  6652. }, t.prototype.Ae = function() {
  6653. this.ke(0), this.ke(1);
  6654. }, t.prototype.Pe = function() {
  6655. this.Me(0), this.Me(1);
  6656. }, t.prototype.ke = function(t) {
  6657. this.Ce(1), this.buffer[this.position++] = t;
  6658. }, t.prototype.Me = function(t) {
  6659. this.Ce(1), this.buffer[this.position++] = ~t;
  6660. }, t.prototype.Ce = function(t) {
  6661. var e = t + this.position;
  6662. if (!(e <= this.buffer.length)) {
  6663. // Try doubling.
  6664. var n = 2 * this.buffer.length;
  6665. // Still not big enough? Just allocate the right size.
  6666. n < e && (n = e);
  6667. // Create the new buffer.
  6668. var r = new Uint8Array(n);
  6669. r.set(this.buffer), // copy old data
  6670. this.buffer = r;
  6671. }
  6672. }, t;
  6673. }(), vo = /** @class */ function() {
  6674. function t(t) {
  6675. this.$e = t;
  6676. }
  6677. return t.prototype.we = function(t) {
  6678. this.$e.Te(t);
  6679. }, t.prototype.fe = function(t) {
  6680. this.$e.ve(t);
  6681. }, t.prototype.le = function(t) {
  6682. this.$e.Se(t);
  6683. }, t.prototype.ae = function() {
  6684. this.$e.Ne();
  6685. }, t;
  6686. }(), mo = /** @class */ function() {
  6687. function t(t) {
  6688. this.$e = t;
  6689. }
  6690. return t.prototype.we = function(t) {
  6691. this.$e.Re(t);
  6692. }, t.prototype.fe = function(t) {
  6693. this.$e.Ve(t);
  6694. }, t.prototype.le = function(t) {
  6695. this.$e.xe(t);
  6696. }, t.prototype.ae = function() {
  6697. this.$e.Oe();
  6698. }, t;
  6699. }(), go = /** @class */ function() {
  6700. function t() {
  6701. this.$e = new yo, this.Be = new vo(this.$e), this.Le = new mo(this.$e);
  6702. }
  6703. return t.prototype.seed = function(t) {
  6704. this.$e.seed(t);
  6705. }, t.prototype.qe = function(t) {
  6706. return 0 /* IndexKind.ASCENDING */ === t ? this.Be : this.Le;
  6707. }, t.prototype.Fe = function() {
  6708. return this.$e.Fe();
  6709. }, t.prototype.reset = function() {
  6710. this.$e.reset();
  6711. }, t;
  6712. }(), wo = /** @class */ function() {
  6713. function t(t, e, n, r) {
  6714. this.indexId = t, this.documentKey = e, this.arrayValue = n, this.directionalValue = r
  6715. /**
  6716. * Returns an IndexEntry entry that sorts immediately after the current
  6717. * directional value.
  6718. */;
  6719. }
  6720. return t.prototype.Ue = function() {
  6721. var e = this.directionalValue.length, n = 0 === e || 255 === this.directionalValue[e - 1] ? e + 1 : e, r = new Uint8Array(n);
  6722. return r.set(this.directionalValue, 0), n !== e ? r.set([ 0 ], this.directionalValue.length) : ++r[r.length - 1],
  6723. new t(this.indexId, this.documentKey, this.arrayValue, r);
  6724. }, t;
  6725. }();
  6726. function bo(t, e) {
  6727. var n = t.indexId - e.indexId;
  6728. return 0 !== n ? n : 0 !== (n = Io(t.arrayValue, e.arrayValue)) ? n : 0 !== (n = Io(t.directionalValue, e.directionalValue)) ? n : ft.comparator(t.documentKey, e.documentKey);
  6729. }
  6730. function Io(t, e) {
  6731. for (var n = 0; n < t.length && n < e.length; ++n) {
  6732. var r = t[n] - e[n];
  6733. if (0 !== r) return r;
  6734. }
  6735. return t.length - e.length;
  6736. }
  6737. /**
  6738. * @license
  6739. * Copyright 2022 Google LLC
  6740. *
  6741. * Licensed under the Apache License, Version 2.0 (the "License");
  6742. * you may not use this file except in compliance with the License.
  6743. * You may obtain a copy of the License at
  6744. *
  6745. * http://www.apache.org/licenses/LICENSE-2.0
  6746. *
  6747. * Unless required by applicable law or agreed to in writing, software
  6748. * distributed under the License is distributed on an "AS IS" BASIS,
  6749. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6750. * See the License for the specific language governing permissions and
  6751. * limitations under the License.
  6752. */
  6753. /**
  6754. * A light query planner for Firestore.
  6755. *
  6756. * This class matches a `FieldIndex` against a Firestore Query `Target`. It
  6757. * determines whether a given index can be used to serve the specified target.
  6758. *
  6759. * The following table showcases some possible index configurations:
  6760. *
  6761. * Query | Index
  6762. * -----------------------------------------------------------------------------
  6763. * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC
  6764. * where('a', '==', 'a').where('b', '==', 'b') | a ASC
  6765. * where('a', '==', 'a').where('b', '==', 'b') | b DESC
  6766. * where('a', '>=', 'a').orderBy('a') | a ASC
  6767. * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC
  6768. * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC
  6769. * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC
  6770. * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING
  6771. * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS
  6772. */ var To = /** @class */ function() {
  6773. function t(t) {
  6774. this.collectionId = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment(),
  6775. this.Ke = t.orderBy, this.Ge = [];
  6776. for (var e = 0, n = t.filters; e < n.length; e++) {
  6777. var r = n[e];
  6778. r.isInequality() ? this.Qe = r : this.Ge.push(r);
  6779. }
  6780. }
  6781. /**
  6782. * Returns whether the index can be used to serve the TargetIndexMatcher's
  6783. * target.
  6784. *
  6785. * An index is considered capable of serving the target when:
  6786. * - The target uses all index segments for its filters and orderBy clauses.
  6787. * The target can have additional filter and orderBy clauses, but not
  6788. * fewer.
  6789. * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also
  6790. * have a corresponding `CONTAINS` segment.
  6791. * - All directional index segments can be mapped to the target as a series of
  6792. * equality filters, a single inequality filter and a series of orderBy
  6793. * clauses.
  6794. * - The segments that represent the equality filters may appear out of order.
  6795. * - The optional segment for the inequality filter must appear after all
  6796. * equality segments.
  6797. * - The segments that represent that orderBy clause of the target must appear
  6798. * in order after all equality and inequality segments. Single orderBy
  6799. * clauses cannot be skipped, but a continuous orderBy suffix may be
  6800. * omitted.
  6801. */ return t.prototype.je = function(t) {
  6802. U(t.collectionGroup === this.collectionId);
  6803. // If there is an array element, find a matching filter.
  6804. var e = pt(t);
  6805. if (void 0 !== e && !this.We(e)) return !1;
  6806. // Process all equalities first. Equalities can appear out of order.
  6807. for (var n = yt(t), r = 0, i = 0; r < n.length && this.We(n[r]); ++r) ;
  6808. // If we already have processed all segments, all segments are used to serve
  6809. // the equality filters and we do not need to map any segments to the
  6810. // target's inequality and orderBy clauses.
  6811. if (r === n.length) return !0;
  6812. // If there is an inequality filter, the next segment must match both the
  6813. // filter and the first orderBy clause.
  6814. if (void 0 !== this.Qe) {
  6815. var o = n[r];
  6816. if (!this.ze(this.Qe, o) || !this.He(this.Ke[i++], o)) return !1;
  6817. ++r;
  6818. }
  6819. // All remaining segments need to represent the prefix of the target's
  6820. // orderBy.
  6821. for (;r < n.length; ++r) {
  6822. var u = n[r];
  6823. if (i >= this.Ke.length || !this.He(this.Ke[i++], u)) return !1;
  6824. }
  6825. return !0;
  6826. }, t.prototype.We = function(t) {
  6827. for (var e = 0, n = this.Ge; e < n.length; e++) {
  6828. var r = n[e];
  6829. if (this.ze(r, t)) return !0;
  6830. }
  6831. return !1;
  6832. }, t.prototype.ze = function(t, e) {
  6833. if (void 0 === t || !t.field.isEqual(e.fieldPath)) return !1;
  6834. var n = "array-contains" /* Operator.ARRAY_CONTAINS */ === t.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t.op;
  6835. return 2 /* IndexKind.CONTAINS */ === e.kind === n;
  6836. }, t.prototype.He = function(t, e) {
  6837. return !!t.field.isEqual(e.fieldPath) && (0 /* IndexKind.ASCENDING */ === e.kind && "asc" /* Direction.ASCENDING */ === t.dir || 1 /* IndexKind.DESCENDING */ === e.kind && "desc" /* Direction.DESCENDING */ === t.dir);
  6838. }, t;
  6839. }();
  6840. /**
  6841. * @license
  6842. * Copyright 2022 Google LLC
  6843. *
  6844. * Licensed under the Apache License, Version 2.0 (the "License");
  6845. * you may not use this file except in compliance with the License.
  6846. * You may obtain a copy of the License at
  6847. *
  6848. * http://www.apache.org/licenses/LICENSE-2.0
  6849. *
  6850. * Unless required by applicable law or agreed to in writing, software
  6851. * distributed under the License is distributed on an "AS IS" BASIS,
  6852. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6853. * See the License for the specific language governing permissions and
  6854. * limitations under the License.
  6855. */
  6856. /**
  6857. * Provides utility functions that help with boolean logic transformations needed for handling
  6858. * complex filters used in queries.
  6859. */
  6860. /**
  6861. * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in
  6862. * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given
  6863. * input into a disjunction of equality filters and returns the expanded filter.
  6864. */ function Eo(t) {
  6865. var e, n;
  6866. if (U(t instanceof Ae || t instanceof Ce), t instanceof Ae) {
  6867. if (t instanceof Ke) {
  6868. var r = (null === (n = null === (e = t.value.arrayValue) || void 0 === e ? void 0 : e.values) || void 0 === n ? void 0 : n.map((function(e) {
  6869. return Ae.create(t.field, "==" /* Operator.EQUAL */ , e);
  6870. }))) || [];
  6871. return Ce.create(r, "or" /* CompositeOperator.OR */);
  6872. }
  6873. // We have reached other kinds of field filters.
  6874. return t;
  6875. }
  6876. // We have a composite filter.
  6877. var i = t.filters.map((function(t) {
  6878. return Eo(t);
  6879. }));
  6880. return Ce.create(i, t.op);
  6881. }
  6882. /**
  6883. * Given a composite filter, returns the list of terms in its disjunctive normal form.
  6884. *
  6885. * <p>Each element in the return value is one term of the resulting DNF. For instance: For the
  6886. * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list
  6887. * with two elements: a composite filter that performs (A && C), and a composite filter that
  6888. * performs (B && C).
  6889. *
  6890. * @param filter the composite filter to calculate DNF transform for.
  6891. * @return the terms in the DNF transform.
  6892. */ function So(t) {
  6893. if (0 === t.getFilters().length) return [];
  6894. var e = Ao(Eo(t));
  6895. return U(xo(e)), _o(e) || Do(e) ? [ e ] : e.getFilters()
  6896. /** Returns true if the given filter is a single field filter. e.g. (a == 10). */;
  6897. }
  6898. function _o(t) {
  6899. return t instanceof Ae;
  6900. }
  6901. /**
  6902. * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10
  6903. * && b == 20)
  6904. */ function Do(t) {
  6905. return t instanceof Ce && Fe(t);
  6906. }
  6907. /**
  6908. * Returns whether or not the given filter is in disjunctive normal form (DNF).
  6909. *
  6910. * <p>In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical
  6911. * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.
  6912. *
  6913. * <p>For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form
  6914. */ function xo(t) {
  6915. return _o(t) || Do(t) ||
  6916. /**
  6917. * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and
  6918. * field filters. e.g. (a == 10) || (b==20 && c==30)
  6919. */
  6920. function(t) {
  6921. if (t instanceof Ce && ke(t)) {
  6922. for (var e = 0, n = t.getFilters(); e < n.length; e++) {
  6923. var r = n[e];
  6924. if (!_o(r) && !Do(r)) return !1;
  6925. }
  6926. return !0;
  6927. }
  6928. return !1;
  6929. }(t);
  6930. }
  6931. function Ao(t) {
  6932. if (U(t instanceof Ae || t instanceof Ce), t instanceof Ae) return t;
  6933. if (1 === t.filters.length) return Ao(t.filters[0]);
  6934. // Compute DNF for each of the subfilters first
  6935. var e = t.filters.map((function(t) {
  6936. return Ao(t);
  6937. })), n = Ce.create(e, t.op);
  6938. return xo(n = ko(n)) ? n : (U(n instanceof Ce), U(Ne(n)), U(n.filters.length > 1),
  6939. n.filters.reduce((function(t, e) {
  6940. return Co(t, e);
  6941. })));
  6942. }
  6943. function Co(t, e) {
  6944. var n;
  6945. return U(t instanceof Ae || t instanceof Ce), U(e instanceof Ae || e instanceof Ce),
  6946. // FieldFilter FieldFilter
  6947. n = t instanceof Ae ? e instanceof Ae ? function(t, e) {
  6948. // Conjunction distribution for two field filters is the conjunction of them.
  6949. return Ce.create([ t, e ], "and" /* CompositeOperator.AND */);
  6950. }(t, e) : No(t, e) : e instanceof Ae ? No(e, t) : function(t, e) {
  6951. // There are four cases:
  6952. // (A & B) & (C & D) --> (A & B & C & D)
  6953. // (A & B) & (C | D) --> (A & B & C) | (A & B & D)
  6954. // (A | B) & (C & D) --> (C & D & A) | (C & D & B)
  6955. // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)
  6956. // Case 1 is a merge.
  6957. if (U(t.filters.length > 0 && e.filters.length > 0), Ne(t) && Ne(e)) return Me(t, e.getFilters());
  6958. // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases
  6959. // we should take each element of the disjunction and distribute it over the other side, and
  6960. // return the disjunction of the distribution results.
  6961. var n = ke(t) ? t : e, r = ke(t) ? e : t, i = n.filters.map((function(t) {
  6962. return Co(t, r);
  6963. }));
  6964. return Ce.create(i, "or" /* CompositeOperator.OR */);
  6965. }(t, e), ko(n);
  6966. }
  6967. function No(t, e) {
  6968. // There are two cases:
  6969. // A & (B & C) --> (A & B & C)
  6970. // A & (B | C) --> (A & B) | (A & C)
  6971. if (Ne(e))
  6972. // Case 1
  6973. return Me(e, t.getFilters());
  6974. // Case 2
  6975. var n = e.filters.map((function(e) {
  6976. return Co(t, e);
  6977. }));
  6978. return Ce.create(n, "or" /* CompositeOperator.OR */);
  6979. }
  6980. /**
  6981. * Applies the associativity property to the given filter and returns the resulting filter.
  6982. *
  6983. * <ul>
  6984. * <li>A | (B | C) == (A | B) | C == (A | B | C)
  6985. * <li>A & (B & C) == (A & B) & C == (A & B & C)
  6986. * </ul>
  6987. *
  6988. * <p>For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic
  6989. */ function ko(t) {
  6990. if (U(t instanceof Ae || t instanceof Ce), t instanceof Ae) return t;
  6991. var e = t.getFilters();
  6992. // If the composite filter only contains 1 filter, apply associativity to it.
  6993. if (1 === e.length) return ko(e[0]);
  6994. // Associativity applied to a flat composite filter results is itself.
  6995. if (Oe(t)) return t;
  6996. // First apply associativity to all subfilters. This will in turn recursively apply
  6997. // associativity to all nested composite filters and field filters.
  6998. var n = e.map((function(t) {
  6999. return ko(t);
  7000. })), r = [];
  7001. // For composite subfilters that perform the same kind of logical operation as `compositeFilter`
  7002. // take out their filters and add them to `compositeFilter`. For example:
  7003. // compositeFilter = (A | (B | C | D))
  7004. // compositeSubfilter = (B | C | D)
  7005. // Result: (A | B | C | D)
  7006. // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been
  7007. // added to the top-level "compositeFilter".
  7008. return n.forEach((function(e) {
  7009. e instanceof Ae ? r.push(e) : e instanceof Ce && (e.op === t.op ?
  7010. // compositeFilter: (A | (B | C))
  7011. // compositeSubfilter: (B | C)
  7012. // Result: (A | B | C)
  7013. r.push.apply(
  7014. // compositeFilter: (A | (B | C))
  7015. // compositeSubfilter: (B | C)
  7016. // Result: (A | B | C)
  7017. r, e.filters) :
  7018. // compositeFilter: (A | (B & C))
  7019. // compositeSubfilter: (B & C)
  7020. // Result: (A | (B & C))
  7021. r.push(e));
  7022. })), 1 === r.length ? r[0] : Ce.create(r, t.op)
  7023. /**
  7024. * @license
  7025. * Copyright 2019 Google LLC
  7026. *
  7027. * Licensed under the Apache License, Version 2.0 (the "License");
  7028. * you may not use this file except in compliance with the License.
  7029. * You may obtain a copy of the License at
  7030. *
  7031. * http://www.apache.org/licenses/LICENSE-2.0
  7032. *
  7033. * Unless required by applicable law or agreed to in writing, software
  7034. * distributed under the License is distributed on an "AS IS" BASIS,
  7035. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7036. * See the License for the specific language governing permissions and
  7037. * limitations under the License.
  7038. */
  7039. /**
  7040. * An in-memory implementation of IndexManager.
  7041. */;
  7042. }
  7043. var Fo = /** @class */ function() {
  7044. function t() {
  7045. this.Je = new Oo;
  7046. }
  7047. return t.prototype.addToCollectionParentIndex = function(t, e) {
  7048. return this.Je.add(e), xt.resolve();
  7049. }, t.prototype.getCollectionParents = function(t, e) {
  7050. return xt.resolve(this.Je.getEntries(e));
  7051. }, t.prototype.addFieldIndex = function(t, e) {
  7052. // Field indices are not supported with memory persistence.
  7053. return xt.resolve();
  7054. }, t.prototype.deleteFieldIndex = function(t, e) {
  7055. // Field indices are not supported with memory persistence.
  7056. return xt.resolve();
  7057. }, t.prototype.getDocumentsMatchingTarget = function(t, e) {
  7058. // Field indices are not supported with memory persistence.
  7059. return xt.resolve(null);
  7060. }, t.prototype.getIndexType = function(t, e) {
  7061. // Field indices are not supported with memory persistence.
  7062. return xt.resolve(0 /* IndexType.NONE */);
  7063. }, t.prototype.getFieldIndexes = function(t, e) {
  7064. // Field indices are not supported with memory persistence.
  7065. return xt.resolve([]);
  7066. }, t.prototype.getNextCollectionGroupToUpdate = function(t) {
  7067. // Field indices are not supported with memory persistence.
  7068. return xt.resolve(null);
  7069. }, t.prototype.getMinOffset = function(t, e) {
  7070. return xt.resolve(Tt.min());
  7071. }, t.prototype.getMinOffsetFromCollectionGroup = function(t, e) {
  7072. return xt.resolve(Tt.min());
  7073. }, t.prototype.updateCollectionGroup = function(t, e, n) {
  7074. // Field indices are not supported with memory persistence.
  7075. return xt.resolve();
  7076. }, t.prototype.updateIndexEntries = function(t, e) {
  7077. // Field indices are not supported with memory persistence.
  7078. return xt.resolve();
  7079. }, t;
  7080. }(), Oo = /** @class */ function() {
  7081. function t() {
  7082. this.index = {};
  7083. }
  7084. // Returns false if the entry already existed.
  7085. return t.prototype.add = function(t) {
  7086. var e = t.lastSegment(), n = t.popLast(), r = this.index[e] || new Ze(ct.comparator), i = !r.has(n);
  7087. return this.index[e] = r.add(n), i;
  7088. }, t.prototype.has = function(t) {
  7089. var e = t.lastSegment(), n = t.popLast(), r = this.index[e];
  7090. return r && r.has(n);
  7091. }, t.prototype.getEntries = function(t) {
  7092. return (this.index[t] || new Ze(ct.comparator)).toArray();
  7093. }, t;
  7094. }(), Ro = new Uint8Array(0), Vo = /** @class */ function() {
  7095. function t(t, e) {
  7096. this.user = t, this.databaseId = e,
  7097. /**
  7098. * An in-memory copy of the index entries we've already written since the SDK
  7099. * launched. Used to avoid re-writing the same entry repeatedly.
  7100. *
  7101. * This is *NOT* a complete cache of what's in persistence and so can never be
  7102. * used to satisfy reads.
  7103. */
  7104. this.Ye = new Oo,
  7105. /**
  7106. * Maps from a target to its equivalent list of sub-targets. Each sub-target
  7107. * contains only one term from the target's disjunctive normal form (DNF).
  7108. */
  7109. this.Xe = new pr((function(t) {
  7110. return an(t);
  7111. }), (function(t, e) {
  7112. return sn(t, e);
  7113. })), this.uid = t.uid || ""
  7114. /**
  7115. * Adds a new entry to the collection parent index.
  7116. *
  7117. * Repeated calls for the same collectionPath should be avoided within a
  7118. * transaction as IndexedDbIndexManager only caches writes once a transaction
  7119. * has been committed.
  7120. */;
  7121. }
  7122. return t.prototype.addToCollectionParentIndex = function(t, e) {
  7123. var n = this;
  7124. if (!this.Ye.has(e)) {
  7125. var r = e.lastSegment(), i = e.popLast();
  7126. t.addOnCommittedListener((function() {
  7127. // Add the collection to the in memory cache only if the transaction was
  7128. // successfully committed.
  7129. n.Ye.add(e);
  7130. }));
  7131. var o = {
  7132. collectionId: r,
  7133. parent: yi(i)
  7134. };
  7135. return Mo(t).put(o);
  7136. }
  7137. return xt.resolve();
  7138. }, t.prototype.getCollectionParents = function(t, e) {
  7139. var n = [], r = IDBKeyRange.bound([ e, "" ], [ ot(e), "" ],
  7140. /*lowerOpen=*/ !1,
  7141. /*upperOpen=*/ !0);
  7142. return Mo(t).W(r).next((function(t) {
  7143. for (var r = 0, i = t; r < i.length; r++) {
  7144. var o = i[r];
  7145. // This collectionId guard shouldn't be necessary (and isn't as long
  7146. // as we're running in a real browser), but there's a bug in
  7147. // indexeddbshim that breaks our range in our tests running in node:
  7148. // https://github.com/axemclion/IndexedDBShim/issues/334
  7149. if (o.collectionId !== e) break;
  7150. n.push(gi(o.parent));
  7151. }
  7152. return n;
  7153. }));
  7154. }, t.prototype.addFieldIndex = function(t, e) {
  7155. var n = this, r = Po(t), i = function(t) {
  7156. return {
  7157. indexId: t.indexId,
  7158. collectionGroup: t.collectionGroup,
  7159. fields: t.fields.map((function(t) {
  7160. return [ t.fieldPath.canonicalString(), t.kind ];
  7161. }))
  7162. };
  7163. }(e);
  7164. // TODO(indexing): Verify that the auto-incrementing index ID works in
  7165. // Safari & Firefox.
  7166. delete i.indexId;
  7167. // `indexId` is auto-populated by IndexedDb
  7168. var o = r.add(i);
  7169. if (e.indexState) {
  7170. var u = qo(t);
  7171. return o.next((function(t) {
  7172. u.put(oo(t, n.user, e.indexState.sequenceNumber, e.indexState.offset));
  7173. }));
  7174. }
  7175. return o.next();
  7176. }, t.prototype.deleteFieldIndex = function(t, e) {
  7177. var n = Po(t), r = qo(t), i = Lo(t);
  7178. return n.delete(e.indexId).next((function() {
  7179. return r.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ],
  7180. /*lowerOpen=*/ !1,
  7181. /*upperOpen=*/ !0));
  7182. })).next((function() {
  7183. return i.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ],
  7184. /*lowerOpen=*/ !1,
  7185. /*upperOpen=*/ !0));
  7186. }));
  7187. }, t.prototype.getDocumentsMatchingTarget = function(t, e) {
  7188. var n = this, r = Lo(t), i = !0, o = new Map;
  7189. return xt.forEach(this.Ze(e), (function(e) {
  7190. return n.tn(t, e).next((function(t) {
  7191. i && (i = !!t), o.set(e, t);
  7192. }));
  7193. })).next((function() {
  7194. if (i) {
  7195. var t = _r(), u = [];
  7196. return xt.forEach(o, (function(i, o) {
  7197. var a;
  7198. V("IndexedDbIndexManager", "Using index ".concat((a = i, "id=".concat(a.indexId, "|cg=").concat(a.collectionGroup, "|f=").concat(a.fields.map((function(t) {
  7199. return "".concat(t.fieldPath, ":").concat(t.kind);
  7200. })).join(","))), " to execute ").concat(an(e)));
  7201. var s = function(t, e) {
  7202. var n = pt(e);
  7203. if (void 0 === n) return null;
  7204. for (var r = 0, i = ln(t, n.fieldPath); r < i.length; r++) {
  7205. var o = i[r];
  7206. switch (o.op) {
  7207. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  7208. return o.value.arrayValue.values || [];
  7209. case "array-contains" /* Operator.ARRAY_CONTAINS */ :
  7210. return [ o.value ];
  7211. // Remaining filters are not array filters.
  7212. }
  7213. }
  7214. return null;
  7215. }(o, i), c = function(t, e) {
  7216. for (var n = new Map, r = 0, i = yt(e); r < i.length; r++) for (var o = i[r], u = 0, a = ln(t, o.fieldPath); u < a.length; u++) {
  7217. var s = a[u];
  7218. switch (s.op) {
  7219. case "==" /* Operator.EQUAL */ :
  7220. case "in" /* Operator.IN */ :
  7221. // Encode equality prefix, which is encoded in the index value before
  7222. // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
  7223. // `value != 'ab'`).
  7224. n.set(o.fieldPath.canonicalString(), s.value);
  7225. break;
  7226. case "not-in" /* Operator.NOT_IN */ :
  7227. case "!=" /* Operator.NOT_EQUAL */ :
  7228. // NotIn/NotEqual is always a suffix. There cannot be any remaining
  7229. // segments and hence we can return early here.
  7230. return n.set(o.fieldPath.canonicalString(), s.value), Array.from(n.values());
  7231. // Remaining filters cannot be used as notIn bounds.
  7232. }
  7233. }
  7234. return null;
  7235. }(o, i), l = function(t, e) {
  7236. // For each segment, retrieve a lower bound if there is a suitable filter or
  7237. // startAt.
  7238. for (var n = [], r = !0, i = 0, o = yt(e); i < o.length; i++) {
  7239. var u = o[i], a = 0 /* IndexKind.ASCENDING */ === u.kind ? hn(t, u.fieldPath, t.startAt) : fn(t, u.fieldPath, t.startAt);
  7240. n.push(a.value), r && (r = a.inclusive);
  7241. }
  7242. return new Se(n, r);
  7243. }(o, i), h = function(t, e) {
  7244. // For each segment, retrieve an upper bound if there is a suitable filter or
  7245. // endAt.
  7246. for (var n = [], r = !0, i = 0, o = yt(e); i < o.length; i++) {
  7247. var u = o[i], a = 0 /* IndexKind.ASCENDING */ === u.kind ? fn(t, u.fieldPath, t.endAt) : hn(t, u.fieldPath, t.endAt);
  7248. n.push(a.value), r && (r = a.inclusive);
  7249. }
  7250. return new Se(n, r);
  7251. }(o, i), f = n.en(i, o, l), d = n.en(i, o, h), p = n.nn(i, o, c), y = n.sn(i.indexId, s, f, l.inclusive, d, h.inclusive, p);
  7252. return xt.forEach(y, (function(n) {
  7253. return r.J(n, e.limit).next((function(e) {
  7254. e.forEach((function(e) {
  7255. var n = ft.fromSegments(e.documentKey);
  7256. t.has(n) || (t = t.add(n), u.push(n));
  7257. }));
  7258. }));
  7259. }));
  7260. })).next((function() {
  7261. return u;
  7262. }));
  7263. }
  7264. return xt.resolve(null);
  7265. }));
  7266. }, t.prototype.Ze = function(t) {
  7267. var e = this.Xe.get(t);
  7268. return e || (e = 0 === t.filters.length ? [ t ] : So(Ce.create(t.filters, "and" /* CompositeOperator.AND */)).map((function(e) {
  7269. return un(t.path, t.collectionGroup, t.orderBy, e.getFilters(), t.limit, t.startAt, t.endAt);
  7270. })), this.Xe.set(t, e), e);
  7271. },
  7272. /**
  7273. * Constructs a key range query on `DbIndexEntryStore` that unions all
  7274. * bounds.
  7275. */
  7276. t.prototype.sn = function(t, e, n, r, i, o, u) {
  7277. for (var a = this, s = (null != e ? e.length : 1) * Math.max(n.length, i.length), c = s / (null != e ? e.length : 1), l = [], h = function(s) {
  7278. var h = e ? f.rn(e[s / c]) : Ro, d = f.on(t, h, n[s % c], r), p = f.un(t, h, i[s % c], o), y = u.map((function(e) {
  7279. return a.on(t, h, e,
  7280. /* inclusive= */ !0);
  7281. }));
  7282. l.push.apply(l, f.createRange(d, p, y));
  7283. }, f = this, d = 0
  7284. // The number of total index scans we union together. This is similar to a
  7285. // distributed normal form, but adapted for array values. We create a single
  7286. // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter
  7287. // combined with the values from the query bounds.
  7288. ; d < s; ++d) h(d);
  7289. return l;
  7290. },
  7291. /** Generates the lower bound for `arrayValue` and `directionalValue`. */ t.prototype.on = function(t, e, n, r) {
  7292. var i = new wo(t, ft.empty(), e, n);
  7293. return r ? i : i.Ue();
  7294. },
  7295. /** Generates the upper bound for `arrayValue` and `directionalValue`. */ t.prototype.un = function(t, e, n, r) {
  7296. var i = new wo(t, ft.empty(), e, n);
  7297. return r ? i.Ue() : i;
  7298. }, t.prototype.tn = function(t, e) {
  7299. var n = new To(e), r = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment();
  7300. return this.getFieldIndexes(t, r).next((function(t) {
  7301. for (
  7302. // Return the index with the most number of segments.
  7303. var e = null, r = 0, i = t; r < i.length; r++) {
  7304. var o = i[r];
  7305. n.je(o) && (!e || o.fields.length > e.fields.length) && (e = o);
  7306. }
  7307. return e;
  7308. }));
  7309. }, t.prototype.getIndexType = function(t, e) {
  7310. var n = this, r = 2 /* IndexType.FULL */ , i = this.Ze(e);
  7311. return xt.forEach(i, (function(e) {
  7312. return n.tn(t, e).next((function(t) {
  7313. t ? 0 /* IndexType.NONE */ !== r && t.fields.length < function(t) {
  7314. for (var e = new Ze(ht.comparator), n = !1, r = 0, i = t.filters; r < i.length; r++) for (var o = 0, u = i[r].getFlattenedFilters(); o < u.length; o++) {
  7315. var a = u[o];
  7316. // __name__ is not an explicit segment of any index, so we don't need to
  7317. // count it.
  7318. a.field.isKeyField() || (
  7319. // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
  7320. // For instance, it is possible to have an index for "a ARRAY a ASC". Even
  7321. // though these are on the same field, they should be counted as two
  7322. // separate segments in an index.
  7323. "array-contains" /* Operator.ARRAY_CONTAINS */ === a.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === a.op ? n = !0 : e = e.add(a.field));
  7324. }
  7325. for (var s = 0, c = t.orderBy; s < c.length; s++) {
  7326. var l = c[s];
  7327. // __name__ is not an explicit segment of any index, so we don't need to
  7328. // count it.
  7329. l.field.isKeyField() || (e = e.add(l.field));
  7330. }
  7331. return e.size + (n ? 1 : 0);
  7332. }(e) && (r = 1 /* IndexType.PARTIAL */) : r = 0 /* IndexType.NONE */;
  7333. }));
  7334. })).next((function() {
  7335. // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider
  7336. // OR queries that have a `limit` to have a partial index. For such queries we perform sorting
  7337. // and apply the limit in memory as a post-processing step.
  7338. return function(t) {
  7339. return null !== t.limit;
  7340. }(e) && i.length > 1 && 2 /* IndexType.FULL */ === r ? 1 /* IndexType.PARTIAL */ : r;
  7341. }));
  7342. },
  7343. /**
  7344. * Returns the byte encoded form of the directional values in the field index.
  7345. * Returns `null` if the document does not have all fields specified in the
  7346. * index.
  7347. */
  7348. t.prototype.cn = function(t, e) {
  7349. for (var n = new go, r = 0, i = yt(t); r < i.length; r++) {
  7350. var o = i[r], u = e.data.field(o.fieldPath);
  7351. if (null == u) return null;
  7352. var a = n.qe(o.kind);
  7353. ho.Ie.ue(u, a);
  7354. }
  7355. return n.Fe();
  7356. },
  7357. /** Encodes a single value to the ascending index format. */ t.prototype.rn = function(t) {
  7358. var e = new go;
  7359. return ho.Ie.ue(t, e.qe(0 /* IndexKind.ASCENDING */)), e.Fe();
  7360. },
  7361. /**
  7362. * Returns an encoded form of the document key that sorts based on the key
  7363. * ordering of the field index.
  7364. */
  7365. t.prototype.an = function(t, e) {
  7366. var n = new go;
  7367. return ho.Ie.ue(fe(this.databaseId, e), n.qe(function(t) {
  7368. var e = yt(t);
  7369. return 0 === e.length ? 0 /* IndexKind.ASCENDING */ : e[e.length - 1].kind;
  7370. }(t))), n.Fe();
  7371. },
  7372. /**
  7373. * Encodes the given field values according to the specification in `target`.
  7374. * For IN queries, a list of possible values is returned.
  7375. */
  7376. t.prototype.nn = function(t, e, n) {
  7377. if (null === n) return [];
  7378. var r = [];
  7379. r.push(new go);
  7380. for (var i = 0, o = 0, u = yt(t); o < u.length; o++) for (var a = u[o], s = n[i++], c = 0, l = r; c < l.length; c++) {
  7381. var h = l[c];
  7382. if (this.hn(e, a.fieldPath) && pe(s)) r = this.ln(r, a, s); else {
  7383. var f = h.qe(a.kind);
  7384. ho.Ie.ue(s, f);
  7385. }
  7386. }
  7387. return this.fn(r);
  7388. },
  7389. /**
  7390. * Encodes the given bounds according to the specification in `target`. For IN
  7391. * queries, a list of possible values is returned.
  7392. */
  7393. t.prototype.en = function(t, e, n) {
  7394. return this.nn(t, e, n.position);
  7395. },
  7396. /** Returns the byte representation for the provided encoders. */ t.prototype.fn = function(t) {
  7397. for (var e = [], n = 0; n < t.length; ++n) e[n] = t[n].Fe();
  7398. return e;
  7399. },
  7400. /**
  7401. * Creates a separate encoder for each element of an array.
  7402. *
  7403. * The method appends each value to all existing encoders (e.g. filter("a",
  7404. * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A
  7405. * list of new encoders is returned.
  7406. */
  7407. t.prototype.ln = function(t, e, n) {
  7408. for (var i = r([], t, !0), o = [], u = 0, a = n.arrayValue.values || []; u < a.length; u++) for (var s = a[u], c = 0, l = i; c < l.length; c++) {
  7409. var h = l[c], f = new go;
  7410. f.seed(h.Fe()), ho.Ie.ue(s, f.qe(e.kind)), o.push(f);
  7411. }
  7412. return o;
  7413. }, t.prototype.hn = function(t, e) {
  7414. return !!t.filters.find((function(t) {
  7415. return t instanceof Ae && t.field.isEqual(e) && ("in" /* Operator.IN */ === t.op || "not-in" /* Operator.NOT_IN */ === t.op);
  7416. }));
  7417. }, t.prototype.getFieldIndexes = function(t, e) {
  7418. var n = this, r = Po(t), i = qo(t);
  7419. return (e ? r.W("collectionGroupIndex", IDBKeyRange.bound(e, e)) : r.W()).next((function(t) {
  7420. var e = [];
  7421. return xt.forEach(t, (function(t) {
  7422. return i.get([ t.indexId, n.uid ]).next((function(n) {
  7423. e.push(function(t, e) {
  7424. var n = e ? new wt(e.sequenceNumber, new Tt(Ji(e.readTime), new ft(gi(e.documentKey)), e.largestBatchId)) : wt.empty(), r = t.fields.map((function(t) {
  7425. var e = t[0], n = t[1];
  7426. return new mt(ht.fromServerFormat(e), n);
  7427. }));
  7428. return new dt(t.indexId, t.collectionGroup, r, n);
  7429. }(t, n));
  7430. }));
  7431. })).next((function() {
  7432. return e;
  7433. }));
  7434. }));
  7435. }, t.prototype.getNextCollectionGroupToUpdate = function(t) {
  7436. return this.getFieldIndexes(t).next((function(t) {
  7437. return 0 === t.length ? null : (t.sort((function(t, e) {
  7438. var n = t.indexState.sequenceNumber - e.indexState.sequenceNumber;
  7439. return 0 !== n ? n : rt(t.collectionGroup, e.collectionGroup);
  7440. })), t[0].collectionGroup);
  7441. }));
  7442. }, t.prototype.updateCollectionGroup = function(t, e, n) {
  7443. var r = this, i = Po(t), o = qo(t);
  7444. return this.dn(t).next((function(t) {
  7445. return i.W("collectionGroupIndex", IDBKeyRange.bound(e, e)).next((function(e) {
  7446. return xt.forEach(e, (function(e) {
  7447. return o.put(oo(e.indexId, r.user, t, n));
  7448. }));
  7449. }));
  7450. }));
  7451. }, t.prototype.updateIndexEntries = function(t, e) {
  7452. var n = this, r = new Map;
  7453. // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as
  7454. // it could be used across different IndexedDB transactions. As any cached
  7455. // data might be invalidated by other multi-tab clients, we can only trust
  7456. // data within a single IndexedDB transaction. We therefore add a cache
  7457. // here.
  7458. return xt.forEach(e, (function(e, i) {
  7459. var o = r.get(e.collectionGroup);
  7460. return (o ? xt.resolve(o) : n.getFieldIndexes(t, e.collectionGroup)).next((function(o) {
  7461. return r.set(e.collectionGroup, o), xt.forEach(o, (function(r) {
  7462. return n._n(t, e, r).next((function(e) {
  7463. var o = n.wn(i, r);
  7464. return e.isEqual(o) ? xt.resolve() : n.mn(t, i, r, e, o);
  7465. }));
  7466. }));
  7467. }));
  7468. }));
  7469. }, t.prototype.gn = function(t, e, n, r) {
  7470. return Lo(t).put({
  7471. indexId: r.indexId,
  7472. uid: this.uid,
  7473. arrayValue: r.arrayValue,
  7474. directionalValue: r.directionalValue,
  7475. orderedDocumentKey: this.an(n, e.key),
  7476. documentKey: e.key.path.toArray()
  7477. });
  7478. }, t.prototype.yn = function(t, e, n, r) {
  7479. return Lo(t).delete([ r.indexId, this.uid, r.arrayValue, r.directionalValue, this.an(n, e.key), e.key.path.toArray() ]);
  7480. }, t.prototype._n = function(t, e, n) {
  7481. var r = Lo(t), i = new Ze(bo);
  7482. return r.Z({
  7483. index: "documentKeyIndex",
  7484. range: IDBKeyRange.only([ n.indexId, this.uid, this.an(n, e) ])
  7485. }, (function(t, r) {
  7486. i = i.add(new wo(n.indexId, e, r.arrayValue, r.directionalValue));
  7487. })).next((function() {
  7488. return i;
  7489. }));
  7490. },
  7491. /** Creates the index entries for the given document. */ t.prototype.wn = function(t, e) {
  7492. var n = new Ze(bo), r = this.cn(e, t);
  7493. if (null == r) return n;
  7494. var i = pt(e);
  7495. if (null != i) {
  7496. var o = t.data.field(i.fieldPath);
  7497. if (pe(o)) for (var u = 0, a = o.arrayValue.values || []; u < a.length; u++) {
  7498. var s = a[u];
  7499. n = n.add(new wo(e.indexId, t.key, this.rn(s), r));
  7500. }
  7501. } else n = n.add(new wo(e.indexId, t.key, Ro, r));
  7502. return n;
  7503. },
  7504. /**
  7505. * Updates the index entries for the provided document by deleting entries
  7506. * that are no longer referenced in `newEntries` and adding all newly added
  7507. * entries.
  7508. */
  7509. t.prototype.mn = function(t, e, n, r, i) {
  7510. var o = this;
  7511. V("IndexedDbIndexManager", "Updating index entries for document '%s'", e.key);
  7512. var u = [];
  7513. return function(t, e, n, r, i) {
  7514. // Walk through the two sets at the same time, using the ordering defined by
  7515. // `comparator`.
  7516. for (var o = t.getIterator(), u = e.getIterator(), a = $e(o), s = $e(u); a || s; ) {
  7517. var c = !1, l = !1;
  7518. if (a && s) {
  7519. var h = n(a, s);
  7520. h < 0 ?
  7521. // The element was removed if the next element in our ordered
  7522. // walkthrough is only in `before`.
  7523. l = !0 : h > 0 && (
  7524. // The element was added if the next element in our ordered walkthrough
  7525. // is only in `after`.
  7526. c = !0);
  7527. } else null != a ? l = !0 : c = !0;
  7528. c ? (r(s), s = $e(u)) : l ? (i(a), a = $e(o)) : (a = $e(o), s = $e(u));
  7529. }
  7530. }(r, i, bo, (
  7531. /* onAdd= */ function(r) {
  7532. u.push(o.gn(t, e, n, r));
  7533. }), (
  7534. /* onRemove= */ function(r) {
  7535. u.push(o.yn(t, e, n, r));
  7536. })), xt.waitFor(u);
  7537. }, t.prototype.dn = function(t) {
  7538. var e = 1;
  7539. return qo(t).Z({
  7540. index: "sequenceNumberIndex",
  7541. reverse: !0,
  7542. range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])
  7543. }, (function(t, n, r) {
  7544. r.done(), e = n.sequenceNumber + 1;
  7545. })).next((function() {
  7546. return e;
  7547. }));
  7548. },
  7549. /**
  7550. * Returns a new set of IDB ranges that splits the existing range and excludes
  7551. * any values that match the `notInValue` from these ranges. As an example,
  7552. * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.
  7553. */
  7554. t.prototype.createRange = function(t, e, n) {
  7555. // The notIn values need to be sorted and unique so that we can return a
  7556. // sorted set of non-overlapping ranges.
  7557. n = n.sort((function(t, e) {
  7558. return bo(t, e);
  7559. })).filter((function(t, e, n) {
  7560. return !e || 0 !== bo(t, n[e - 1]);
  7561. }));
  7562. var r = [];
  7563. r.push(t);
  7564. for (var i = 0, o = n; i < o.length; i++) {
  7565. var u = o[i], a = bo(u, t), s = bo(u, e);
  7566. if (0 === a)
  7567. // `notInValue` is the lower bound. We therefore need to raise the bound
  7568. // to the next value.
  7569. r[0] = t.Ue(); else if (a > 0 && s < 0)
  7570. // `notInValue` is in the middle of the range
  7571. r.push(u), r.push(u.Ue()); else if (s > 0)
  7572. // `notInValue` (and all following values) are out of the range
  7573. break;
  7574. }
  7575. r.push(e);
  7576. for (var c = [], l = 0; l < r.length; l += 2) {
  7577. // If we encounter two bounds that will create an unmatchable key range,
  7578. // then we return an empty set of key ranges.
  7579. if (this.pn(r[l], r[l + 1])) return [];
  7580. var h = [ r[l].indexId, this.uid, r[l].arrayValue, r[l].directionalValue, Ro, [] ], f = [ r[l + 1].indexId, this.uid, r[l + 1].arrayValue, r[l + 1].directionalValue, Ro, [] ];
  7581. c.push(IDBKeyRange.bound(h, f));
  7582. }
  7583. return c;
  7584. }, t.prototype.pn = function(t, e) {
  7585. // If lower bound is greater than the upper bound, then the key
  7586. // range can never be matched.
  7587. return bo(t, e) > 0;
  7588. }, t.prototype.getMinOffsetFromCollectionGroup = function(t, e) {
  7589. return this.getFieldIndexes(t, e).next(Uo);
  7590. }, t.prototype.getMinOffset = function(t, e) {
  7591. var n = this;
  7592. return xt.mapArray(this.Ze(e), (function(e) {
  7593. return n.tn(t, e).next((function(t) {
  7594. return t || q();
  7595. }));
  7596. })).next(Uo);
  7597. }, t;
  7598. }();
  7599. /**
  7600. * Internal implementation of the collection-parent index exposed by MemoryIndexManager.
  7601. * Also used for in-memory caching by IndexedDbIndexManager and initial index population
  7602. * in indexeddb_schema.ts
  7603. */
  7604. /**
  7605. * Helper to get a typed SimpleDbStore for the collectionParents
  7606. * document store.
  7607. */
  7608. function Mo(t) {
  7609. return Ki(t, "collectionParents");
  7610. }
  7611. /**
  7612. * Helper to get a typed SimpleDbStore for the index entry object store.
  7613. */ function Lo(t) {
  7614. return Ki(t, "indexEntries");
  7615. }
  7616. /**
  7617. * Helper to get a typed SimpleDbStore for the index configuration object store.
  7618. */ function Po(t) {
  7619. return Ki(t, "indexConfiguration");
  7620. }
  7621. /**
  7622. * Helper to get a typed SimpleDbStore for the index state object store.
  7623. */ function qo(t) {
  7624. return Ki(t, "indexState");
  7625. }
  7626. function Uo(t) {
  7627. U(0 !== t.length);
  7628. for (var e = t[0].indexState.offset, n = e.largestBatchId, r = 1; r < t.length; r++) {
  7629. var i = t[r].indexState.offset;
  7630. Et(i, e) < 0 && (e = i), n < i.largestBatchId && (n = i.largestBatchId);
  7631. }
  7632. return new Tt(e.readTime, e.documentKey, n);
  7633. }
  7634. /**
  7635. * @license
  7636. * Copyright 2018 Google LLC
  7637. *
  7638. * Licensed under the Apache License, Version 2.0 (the "License");
  7639. * you may not use this file except in compliance with the License.
  7640. * You may obtain a copy of the License at
  7641. *
  7642. * http://www.apache.org/licenses/LICENSE-2.0
  7643. *
  7644. * Unless required by applicable law or agreed to in writing, software
  7645. * distributed under the License is distributed on an "AS IS" BASIS,
  7646. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7647. * See the License for the specific language governing permissions and
  7648. * limitations under the License.
  7649. */ var Bo = {
  7650. didRun: !1,
  7651. sequenceNumbersCollected: 0,
  7652. targetsRemoved: 0,
  7653. documentsRemoved: 0
  7654. }, Go = /** @class */ function() {
  7655. function t(
  7656. // When we attempt to collect, we will only do so if the cache size is greater than this
  7657. // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.
  7658. t,
  7659. // The percentage of sequence numbers that we will attempt to collect
  7660. e,
  7661. // A cap on the total number of sequence numbers that will be collected. This prevents
  7662. // us from collecting a huge number of sequence numbers if the cache has grown very large.
  7663. n) {
  7664. this.cacheSizeCollectionThreshold = t, this.percentileToCollect = e, this.maximumSequenceNumbersToCollect = n;
  7665. }
  7666. return t.withCacheSize = function(e) {
  7667. return new t(e, t.DEFAULT_COLLECTION_PERCENTILE, t.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);
  7668. }, t;
  7669. }();
  7670. /**
  7671. * @license
  7672. * Copyright 2020 Google LLC
  7673. *
  7674. * Licensed under the Apache License, Version 2.0 (the "License");
  7675. * you may not use this file except in compliance with the License.
  7676. * You may obtain a copy of the License at
  7677. *
  7678. * http://www.apache.org/licenses/LICENSE-2.0
  7679. *
  7680. * Unless required by applicable law or agreed to in writing, software
  7681. * distributed under the License is distributed on an "AS IS" BASIS,
  7682. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7683. * See the License for the specific language governing permissions and
  7684. * limitations under the License.
  7685. */
  7686. /**
  7687. * Delete a mutation batch and the associated document mutations.
  7688. * @returns A PersistencePromise of the document mutations that were removed.
  7689. */
  7690. function Ko(t, e, n) {
  7691. var r = t.store("mutations"), i = t.store("documentMutations"), o = [], u = IDBKeyRange.only(n.batchId), a = 0, s = r.Z({
  7692. range: u
  7693. }, (function(t, e, n) {
  7694. return a++, n.delete();
  7695. }));
  7696. o.push(s.next((function() {
  7697. U(1 === a);
  7698. })));
  7699. for (var c = [], l = 0, h = n.mutations; l < h.length; l++) {
  7700. var f = h[l], d = Ii(e, f.key.path, n.batchId);
  7701. o.push(i.delete(d)), c.push(f.key);
  7702. }
  7703. return xt.waitFor(o).next((function() {
  7704. return c;
  7705. }));
  7706. }
  7707. /**
  7708. * Returns an approximate size for the given document.
  7709. */ function jo(t) {
  7710. if (!t) return 0;
  7711. var e;
  7712. if (t.document) e = t.document; else if (t.unknownDocument) e = t.unknownDocument; else {
  7713. if (!t.noDocument) throw q();
  7714. e = t.noDocument;
  7715. }
  7716. return JSON.stringify(e).length;
  7717. }
  7718. /**
  7719. * @license
  7720. * Copyright 2017 Google LLC
  7721. *
  7722. * Licensed under the Apache License, Version 2.0 (the "License");
  7723. * you may not use this file except in compliance with the License.
  7724. * You may obtain a copy of the License at
  7725. *
  7726. * http://www.apache.org/licenses/LICENSE-2.0
  7727. *
  7728. * Unless required by applicable law or agreed to in writing, software
  7729. * distributed under the License is distributed on an "AS IS" BASIS,
  7730. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7731. * See the License for the specific language governing permissions and
  7732. * limitations under the License.
  7733. */
  7734. /** A mutation queue for a specific user, backed by IndexedDB. */ Go.DEFAULT_COLLECTION_PERCENTILE = 10,
  7735. Go.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, Go.DEFAULT = new Go(41943040, Go.DEFAULT_COLLECTION_PERCENTILE, Go.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),
  7736. Go.DISABLED = new Go(-1, 0, 0);
  7737. var Qo = /** @class */ function() {
  7738. function t(
  7739. /**
  7740. * The normalized userId (e.g. null UID => "" userId) used to store /
  7741. * retrieve mutations.
  7742. */
  7743. t, e, n, r) {
  7744. this.userId = t, this.yt = e, this.indexManager = n, this.referenceDelegate = r,
  7745. /**
  7746. * Caches the document keys for pending mutation batches. If the mutation
  7747. * has been removed from IndexedDb, the cached value may continue to
  7748. * be used to retrieve the batch's document keys. To remove a cached value
  7749. * locally, `removeCachedMutationKeys()` should be invoked either directly
  7750. * or through `removeMutationBatches()`.
  7751. *
  7752. * With multi-tab, when the primary client acknowledges or rejects a mutation,
  7753. * this cache is used by secondary clients to invalidate the local
  7754. * view of the documents that were previously affected by the mutation.
  7755. */
  7756. // PORTING NOTE: Multi-tab only.
  7757. this.In = {}
  7758. /**
  7759. * Creates a new mutation queue for the given user.
  7760. * @param user - The user for which to create a mutation queue.
  7761. * @param serializer - The serializer to use when persisting to IndexedDb.
  7762. */;
  7763. }
  7764. return t.re = function(e, n, r, i) {
  7765. // TODO(mcg): Figure out what constraints there are on userIDs
  7766. // In particular, are there any reserved characters? are empty ids allowed?
  7767. // For the moment store these together in the same mutations table assuming
  7768. // that empty userIDs aren't allowed.
  7769. return U("" !== e.uid), new t(e.isAuthenticated() ? e.uid : "", n, r, i);
  7770. }, t.prototype.checkEmpty = function(t) {
  7771. var e = !0, n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);
  7772. return Wo(t).Z({
  7773. index: "userMutationsIndex",
  7774. range: n
  7775. }, (function(t, n, r) {
  7776. e = !1, r.done();
  7777. })).next((function() {
  7778. return e;
  7779. }));
  7780. }, t.prototype.addMutationBatch = function(t, e, n, r) {
  7781. var i = this, o = Ho(t), u = Wo(t);
  7782. // The IndexedDb implementation in Chrome (and Firefox) does not handle
  7783. // compound indices that include auto-generated keys correctly. To ensure
  7784. // that the index entry is added correctly in all browsers, we perform two
  7785. // writes: The first write is used to retrieve the next auto-generated Batch
  7786. // ID, and the second write populates the index and stores the actual
  7787. // mutation batch.
  7788. // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972
  7789. // We write an empty object to obtain key
  7790. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  7791. return u.add({}).next((function(a) {
  7792. U("number" == typeof a);
  7793. for (var s = new ji(a, e, n, r), c = function(t, e, n) {
  7794. var r = n.baseMutations.map((function(e) {
  7795. return ei(t.ie, e);
  7796. })), i = n.mutations.map((function(e) {
  7797. return ei(t.ie, e);
  7798. }));
  7799. return {
  7800. userId: e,
  7801. batchId: n.batchId,
  7802. localWriteTimeMs: n.localWriteTime.toMillis(),
  7803. baseMutations: r,
  7804. mutations: i
  7805. };
  7806. }(i.yt, i.userId, s), l = [], h = new Ze((function(t, e) {
  7807. return rt(t.canonicalString(), e.canonicalString());
  7808. })), f = 0, d = r; f < d.length; f++) {
  7809. var p = d[f], y = Ii(i.userId, p.key.path, a);
  7810. h = h.add(p.key.path.popLast()), l.push(u.put(c)), l.push(o.put(y, Ti));
  7811. }
  7812. return h.forEach((function(e) {
  7813. l.push(i.indexManager.addToCollectionParentIndex(t, e));
  7814. })), t.addOnCommittedListener((function() {
  7815. i.In[a] = s.keys();
  7816. })), xt.waitFor(l).next((function() {
  7817. return s;
  7818. }));
  7819. }));
  7820. }, t.prototype.lookupMutationBatch = function(t, e) {
  7821. var n = this;
  7822. return Wo(t).get(e).next((function(t) {
  7823. return t ? (U(t.userId === n.userId), $i(n.yt, t)) : null;
  7824. }));
  7825. },
  7826. /**
  7827. * Returns the document keys for the mutation batch with the given batchId.
  7828. * For primary clients, this method returns `null` after
  7829. * `removeMutationBatches()` has been called. Secondary clients return a
  7830. * cached result until `removeCachedMutationKeys()` is invoked.
  7831. */
  7832. // PORTING NOTE: Multi-tab only.
  7833. t.prototype.Tn = function(t, e) {
  7834. var n = this;
  7835. return this.In[e] ? xt.resolve(this.In[e]) : this.lookupMutationBatch(t, e).next((function(t) {
  7836. if (t) {
  7837. var r = t.keys();
  7838. return n.In[e] = r, r;
  7839. }
  7840. return null;
  7841. }));
  7842. }, t.prototype.getNextMutationBatchAfterBatchId = function(t, e) {
  7843. var n = this, r = e + 1, i = IDBKeyRange.lowerBound([ this.userId, r ]), o = null;
  7844. return Wo(t).Z({
  7845. index: "userMutationsIndex",
  7846. range: i
  7847. }, (function(t, e, i) {
  7848. e.userId === n.userId && (U(e.batchId >= r), o = $i(n.yt, e)), i.done();
  7849. })).next((function() {
  7850. return o;
  7851. }));
  7852. }, t.prototype.getHighestUnacknowledgedBatchId = function(t) {
  7853. var e = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]), n = -1;
  7854. return Wo(t).Z({
  7855. index: "userMutationsIndex",
  7856. range: e,
  7857. reverse: !0
  7858. }, (function(t, e, r) {
  7859. n = e.batchId, r.done();
  7860. })).next((function() {
  7861. return n;
  7862. }));
  7863. }, t.prototype.getAllMutationBatches = function(t) {
  7864. var e = this, n = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);
  7865. return Wo(t).W("userMutationsIndex", n).next((function(t) {
  7866. return t.map((function(t) {
  7867. return $i(e.yt, t);
  7868. }));
  7869. }));
  7870. }, t.prototype.getAllMutationBatchesAffectingDocumentKey = function(t, e) {
  7871. var n = this, r = bi(this.userId, e.path), i = IDBKeyRange.lowerBound(r), o = [];
  7872. // Scan the document-mutation index starting with a prefix starting with
  7873. // the given documentKey.
  7874. return Ho(t).Z({
  7875. range: i
  7876. }, (function(r, i, u) {
  7877. var a = r[0], s = r[1], c = r[2], l = gi(s);
  7878. // Only consider rows matching exactly the specific key of
  7879. // interest. Note that because we order by path first, and we
  7880. // order terminators before path separators, we'll encounter all
  7881. // the index rows for documentKey contiguously. In particular, all
  7882. // the rows for documentKey will occur before any rows for
  7883. // documents nested in a subcollection beneath documentKey so we
  7884. // can stop as soon as we hit any such row.
  7885. if (a === n.userId && e.path.isEqual(l))
  7886. // Look up the mutation batch in the store.
  7887. return Wo(t).get(c).next((function(t) {
  7888. if (!t) throw q();
  7889. U(t.userId === n.userId), o.push($i(n.yt, t));
  7890. }));
  7891. u.done();
  7892. })).next((function() {
  7893. return o;
  7894. }));
  7895. }, t.prototype.getAllMutationBatchesAffectingDocumentKeys = function(t, e) {
  7896. var n = this, r = new Ze(rt), i = [];
  7897. return e.forEach((function(e) {
  7898. var o = bi(n.userId, e.path), u = IDBKeyRange.lowerBound(o), a = Ho(t).Z({
  7899. range: u
  7900. }, (function(t, i, o) {
  7901. var u = t[0], a = t[1], s = t[2], c = gi(a);
  7902. // Only consider rows matching exactly the specific key of
  7903. // interest. Note that because we order by path first, and we
  7904. // order terminators before path separators, we'll encounter all
  7905. // the index rows for documentKey contiguously. In particular, all
  7906. // the rows for documentKey will occur before any rows for
  7907. // documents nested in a subcollection beneath documentKey so we
  7908. // can stop as soon as we hit any such row.
  7909. u === n.userId && e.path.isEqual(c) ? r = r.add(s) : o.done();
  7910. }));
  7911. i.push(a);
  7912. })), xt.waitFor(i).next((function() {
  7913. return n.En(t, r);
  7914. }));
  7915. }, t.prototype.getAllMutationBatchesAffectingQuery = function(t, e) {
  7916. var n = this, r = e.path, i = r.length + 1, o = bi(this.userId, r), u = IDBKeyRange.lowerBound(o), a = new Ze(rt);
  7917. return Ho(t).Z({
  7918. range: u
  7919. }, (function(t, e, o) {
  7920. var u = t[0], s = t[1], c = t[2], l = gi(s);
  7921. u === n.userId && r.isPrefixOf(l) ?
  7922. // Rows with document keys more than one segment longer than the
  7923. // query path can't be matches. For example, a query on 'rooms'
  7924. // can't match the document /rooms/abc/messages/xyx.
  7925. // TODO(mcg): we'll need a different scanner when we implement
  7926. // ancestor queries.
  7927. l.length === i && (a = a.add(c)) : o.done();
  7928. })).next((function() {
  7929. return n.En(t, a);
  7930. }));
  7931. }, t.prototype.En = function(t, e) {
  7932. var n = this, r = [], i = [];
  7933. // TODO(rockwood): Implement this using iterate.
  7934. return e.forEach((function(e) {
  7935. i.push(Wo(t).get(e).next((function(t) {
  7936. if (null === t) throw q();
  7937. U(t.userId === n.userId), r.push($i(n.yt, t));
  7938. })));
  7939. })), xt.waitFor(i).next((function() {
  7940. return r;
  7941. }));
  7942. }, t.prototype.removeMutationBatch = function(t, e) {
  7943. var n = this;
  7944. return Ko(t.se, this.userId, e).next((function(r) {
  7945. return t.addOnCommittedListener((function() {
  7946. n.An(e.batchId);
  7947. })), xt.forEach(r, (function(e) {
  7948. return n.referenceDelegate.markPotentiallyOrphaned(t, e);
  7949. }));
  7950. }));
  7951. },
  7952. /**
  7953. * Clears the cached keys for a mutation batch. This method should be
  7954. * called by secondary clients after they process mutation updates.
  7955. *
  7956. * Note that this method does not have to be called from primary clients as
  7957. * the corresponding cache entries are cleared when an acknowledged or
  7958. * rejected batch is removed from the mutation queue.
  7959. */
  7960. // PORTING NOTE: Multi-tab only
  7961. t.prototype.An = function(t) {
  7962. delete this.In[t];
  7963. }, t.prototype.performConsistencyCheck = function(t) {
  7964. var e = this;
  7965. return this.checkEmpty(t).next((function(n) {
  7966. if (!n) return xt.resolve();
  7967. // Verify that there are no entries in the documentMutations index if
  7968. // the queue is empty.
  7969. var r = IDBKeyRange.lowerBound([ e.userId ]), i = [];
  7970. return Ho(t).Z({
  7971. range: r
  7972. }, (function(t, n, r) {
  7973. if (t[0] === e.userId) {
  7974. var o = gi(t[1]);
  7975. i.push(o);
  7976. } else r.done();
  7977. })).next((function() {
  7978. U(0 === i.length);
  7979. }));
  7980. }));
  7981. }, t.prototype.containsKey = function(t, e) {
  7982. return zo(t, this.userId, e);
  7983. },
  7984. // PORTING NOTE: Multi-tab only (state is held in memory in other clients).
  7985. /** Returns the mutation queue's metadata from IndexedDb. */
  7986. t.prototype.Rn = function(t) {
  7987. var e = this;
  7988. return Yo(t).get(this.userId).next((function(t) {
  7989. return t || {
  7990. userId: e.userId,
  7991. lastAcknowledgedBatchId: -1,
  7992. lastStreamToken: ""
  7993. };
  7994. }));
  7995. }, t;
  7996. }();
  7997. /**
  7998. * @returns true if the mutation queue for the given user contains a pending
  7999. * mutation for the given key.
  8000. */ function zo(t, e, n) {
  8001. var r = bi(e, n.path), i = r[1], o = IDBKeyRange.lowerBound(r), u = !1;
  8002. return Ho(t).Z({
  8003. range: o,
  8004. X: !0
  8005. }, (function(t, n, r) {
  8006. var o = t[0], a = t[1];
  8007. /*batchID*/ t[2], o === e && a === i && (u = !0),
  8008. r.done();
  8009. })).next((function() {
  8010. return u;
  8011. }));
  8012. }
  8013. /** Returns true if any mutation queue contains the given document. */
  8014. /**
  8015. * Helper to get a typed SimpleDbStore for the mutations object store.
  8016. */ function Wo(t) {
  8017. return Ki(t, "mutations");
  8018. }
  8019. /**
  8020. * Helper to get a typed SimpleDbStore for the mutationQueues object store.
  8021. */ function Ho(t) {
  8022. return Ki(t, "documentMutations");
  8023. }
  8024. /**
  8025. * Helper to get a typed SimpleDbStore for the mutationQueues object store.
  8026. */ function Yo(t) {
  8027. return Ki(t, "mutationQueues");
  8028. }
  8029. /**
  8030. * @license
  8031. * Copyright 2017 Google LLC
  8032. *
  8033. * Licensed under the Apache License, Version 2.0 (the "License");
  8034. * you may not use this file except in compliance with the License.
  8035. * You may obtain a copy of the License at
  8036. *
  8037. * http://www.apache.org/licenses/LICENSE-2.0
  8038. *
  8039. * Unless required by applicable law or agreed to in writing, software
  8040. * distributed under the License is distributed on an "AS IS" BASIS,
  8041. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8042. * See the License for the specific language governing permissions and
  8043. * limitations under the License.
  8044. */
  8045. /** Offset to ensure non-overlapping target ids. */
  8046. /**
  8047. * Generates monotonically increasing target IDs for sending targets to the
  8048. * watch stream.
  8049. *
  8050. * The client constructs two generators, one for the target cache, and one for
  8051. * for the sync engine (to generate limbo documents targets). These
  8052. * generators produce non-overlapping IDs (by using even and odd IDs
  8053. * respectively).
  8054. *
  8055. * By separating the target ID space, the query cache can generate target IDs
  8056. * that persist across client restarts, while sync engine can independently
  8057. * generate in-memory target IDs that are transient and can be reused after a
  8058. * restart.
  8059. */ var Xo = /** @class */ function() {
  8060. function t(t) {
  8061. this.bn = t;
  8062. }
  8063. return t.prototype.next = function() {
  8064. return this.bn += 2, this.bn;
  8065. }, t.Pn = function() {
  8066. // The target cache generator must return '2' in its first call to `next()`
  8067. // as there is no differentiation in the protocol layer between an unset
  8068. // number and the number '0'. If we were to sent a target with target ID
  8069. // '0', the backend would consider it unset and replace it with its own ID.
  8070. return new t(0);
  8071. }, t.vn = function() {
  8072. // Sync engine assigns target IDs for limbo document detection.
  8073. return new t(-1);
  8074. }, t;
  8075. }(), Zo = /** @class */ function() {
  8076. function t(t, e) {
  8077. this.referenceDelegate = t, this.yt = e;
  8078. }
  8079. // PORTING NOTE: We don't cache global metadata for the target cache, since
  8080. // some of it (in particular `highestTargetId`) can be modified by secondary
  8081. // tabs. We could perhaps be more granular (and e.g. still cache
  8082. // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go
  8083. // to IndexedDb whenever we need to read metadata. We can revisit if it turns
  8084. // out to have a meaningful performance impact.
  8085. return t.prototype.allocateTargetId = function(t) {
  8086. var e = this;
  8087. return this.Vn(t).next((function(n) {
  8088. var r = new Xo(n.highestTargetId);
  8089. return n.highestTargetId = r.next(), e.Sn(t, n).next((function() {
  8090. return n.highestTargetId;
  8091. }));
  8092. }));
  8093. }, t.prototype.getLastRemoteSnapshotVersion = function(t) {
  8094. return this.Vn(t).next((function(t) {
  8095. return at.fromTimestamp(new ut(t.lastRemoteSnapshotVersion.seconds, t.lastRemoteSnapshotVersion.nanoseconds));
  8096. }));
  8097. }, t.prototype.getHighestSequenceNumber = function(t) {
  8098. return this.Vn(t).next((function(t) {
  8099. return t.highestListenSequenceNumber;
  8100. }));
  8101. }, t.prototype.setTargetsMetadata = function(t, e, n) {
  8102. var r = this;
  8103. return this.Vn(t).next((function(i) {
  8104. return i.highestListenSequenceNumber = e, n && (i.lastRemoteSnapshotVersion = n.toTimestamp()),
  8105. e > i.highestListenSequenceNumber && (i.highestListenSequenceNumber = e), r.Sn(t, i);
  8106. }));
  8107. }, t.prototype.addTargetData = function(t, e) {
  8108. var n = this;
  8109. return this.Dn(t, e).next((function() {
  8110. return n.Vn(t).next((function(r) {
  8111. return r.targetCount += 1, n.Cn(e, r), n.Sn(t, r);
  8112. }));
  8113. }));
  8114. }, t.prototype.updateTargetData = function(t, e) {
  8115. return this.Dn(t, e);
  8116. }, t.prototype.removeTargetData = function(t, e) {
  8117. var n = this;
  8118. return this.removeMatchingKeysForTargetId(t, e.targetId).next((function() {
  8119. return Jo(t).delete(e.targetId);
  8120. })).next((function() {
  8121. return n.Vn(t);
  8122. })).next((function(e) {
  8123. return U(e.targetCount > 0), e.targetCount -= 1, n.Sn(t, e);
  8124. }));
  8125. },
  8126. /**
  8127. * Drops any targets with sequence number less than or equal to the upper bound, excepting those
  8128. * present in `activeTargetIds`. Document associations for the removed targets are also removed.
  8129. * Returns the number of targets removed.
  8130. */
  8131. t.prototype.removeTargets = function(t, e, n) {
  8132. var r = this, i = 0, o = [];
  8133. return Jo(t).Z((function(u, a) {
  8134. var s = to(a);
  8135. s.sequenceNumber <= e && null === n.get(s.targetId) && (i++, o.push(r.removeTargetData(t, s)));
  8136. })).next((function() {
  8137. return xt.waitFor(o);
  8138. })).next((function() {
  8139. return i;
  8140. }));
  8141. },
  8142. /**
  8143. * Call provided function with each `TargetData` that we have cached.
  8144. */
  8145. t.prototype.forEachTarget = function(t, e) {
  8146. return Jo(t).Z((function(t, n) {
  8147. var r = to(n);
  8148. e(r);
  8149. }));
  8150. }, t.prototype.Vn = function(t) {
  8151. return $o(t).get("targetGlobalKey").next((function(t) {
  8152. return U(null !== t), t;
  8153. }));
  8154. }, t.prototype.Sn = function(t, e) {
  8155. return $o(t).put("targetGlobalKey", e);
  8156. }, t.prototype.Dn = function(t, e) {
  8157. return Jo(t).put(eo(this.yt, e));
  8158. },
  8159. /**
  8160. * In-place updates the provided metadata to account for values in the given
  8161. * TargetData. Saving is done separately. Returns true if there were any
  8162. * changes to the metadata.
  8163. */
  8164. t.prototype.Cn = function(t, e) {
  8165. var n = !1;
  8166. return t.targetId > e.highestTargetId && (e.highestTargetId = t.targetId, n = !0),
  8167. t.sequenceNumber > e.highestListenSequenceNumber && (e.highestListenSequenceNumber = t.sequenceNumber,
  8168. n = !0), n;
  8169. }, t.prototype.getTargetCount = function(t) {
  8170. return this.Vn(t).next((function(t) {
  8171. return t.targetCount;
  8172. }));
  8173. }, t.prototype.getTargetData = function(t, e) {
  8174. // Iterating by the canonicalId may yield more than one result because
  8175. // canonicalId values are not required to be unique per target. This query
  8176. // depends on the queryTargets index to be efficient.
  8177. var n = an(e), r = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]), i = null;
  8178. return Jo(t).Z({
  8179. range: r,
  8180. index: "queryTargetsIndex"
  8181. }, (function(t, n, r) {
  8182. var o = to(n);
  8183. // After finding a potential match, check that the target is
  8184. // actually equal to the requested target.
  8185. sn(e, o.target) && (i = o, r.done());
  8186. })).next((function() {
  8187. return i;
  8188. }));
  8189. }, t.prototype.addMatchingKeys = function(t, e, n) {
  8190. var r = this, i = [], o = tu(t);
  8191. // PORTING NOTE: The reverse index (documentsTargets) is maintained by
  8192. // IndexedDb.
  8193. return e.forEach((function(e) {
  8194. var u = yi(e.path);
  8195. i.push(o.put({
  8196. targetId: n,
  8197. path: u
  8198. })), i.push(r.referenceDelegate.addReference(t, n, e));
  8199. })), xt.waitFor(i);
  8200. }, t.prototype.removeMatchingKeys = function(t, e, n) {
  8201. var r = this, i = tu(t);
  8202. // PORTING NOTE: The reverse index (documentsTargets) is maintained by
  8203. // IndexedDb.
  8204. return xt.forEach(e, (function(e) {
  8205. var o = yi(e.path);
  8206. return xt.waitFor([ i.delete([ n, o ]), r.referenceDelegate.removeReference(t, n, e) ]);
  8207. }));
  8208. }, t.prototype.removeMatchingKeysForTargetId = function(t, e) {
  8209. var n = tu(t), r = IDBKeyRange.bound([ e ], [ e + 1 ],
  8210. /*lowerOpen=*/ !1,
  8211. /*upperOpen=*/ !0);
  8212. return n.delete(r);
  8213. }, t.prototype.getMatchingKeysForTargetId = function(t, e) {
  8214. var n = IDBKeyRange.bound([ e ], [ e + 1 ],
  8215. /*lowerOpen=*/ !1,
  8216. /*upperOpen=*/ !0), r = tu(t), i = _r();
  8217. return r.Z({
  8218. range: n,
  8219. X: !0
  8220. }, (function(t, e, n) {
  8221. var r = gi(t[1]), o = new ft(r);
  8222. i = i.add(o);
  8223. })).next((function() {
  8224. return i;
  8225. }));
  8226. }, t.prototype.containsKey = function(t, e) {
  8227. var n = yi(e.path), r = IDBKeyRange.bound([ n ], [ ot(n) ],
  8228. /*lowerOpen=*/ !1,
  8229. /*upperOpen=*/ !0), i = 0;
  8230. return tu(t).Z({
  8231. index: "documentTargetsIndex",
  8232. X: !0,
  8233. range: r
  8234. }, (function(t, e, n) {
  8235. var r = t[0];
  8236. t[1],
  8237. // Having a sentinel row for a document does not count as containing that document;
  8238. // For the target cache, containing the document means the document is part of some
  8239. // target.
  8240. 0 !== r && (i++, n.done());
  8241. })).next((function() {
  8242. return i > 0;
  8243. }));
  8244. },
  8245. /**
  8246. * Looks up a TargetData entry by target ID.
  8247. *
  8248. * @param targetId - The target ID of the TargetData entry to look up.
  8249. * @returns The cached TargetData entry, or null if the cache has no entry for
  8250. * the target.
  8251. */
  8252. // PORTING NOTE: Multi-tab only.
  8253. t.prototype.ne = function(t, e) {
  8254. return Jo(t).get(e).next((function(t) {
  8255. return t ? to(t) : null;
  8256. }));
  8257. }, t;
  8258. }();
  8259. /**
  8260. * @license
  8261. * Copyright 2017 Google LLC
  8262. *
  8263. * Licensed under the Apache License, Version 2.0 (the "License");
  8264. * you may not use this file except in compliance with the License.
  8265. * You may obtain a copy of the License at
  8266. *
  8267. * http://www.apache.org/licenses/LICENSE-2.0
  8268. *
  8269. * Unless required by applicable law or agreed to in writing, software
  8270. * distributed under the License is distributed on an "AS IS" BASIS,
  8271. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8272. * See the License for the specific language governing permissions and
  8273. * limitations under the License.
  8274. */
  8275. /**
  8276. * Helper to get a typed SimpleDbStore for the queries object store.
  8277. */
  8278. function Jo(t) {
  8279. return Ki(t, "targets");
  8280. }
  8281. /**
  8282. * Helper to get a typed SimpleDbStore for the target globals object store.
  8283. */ function $o(t) {
  8284. return Ki(t, "targetGlobal");
  8285. }
  8286. /**
  8287. * Helper to get a typed SimpleDbStore for the document target object store.
  8288. */ function tu(t) {
  8289. return Ki(t, "targetDocuments");
  8290. }
  8291. /**
  8292. * @license
  8293. * Copyright 2020 Google LLC
  8294. *
  8295. * Licensed under the Apache License, Version 2.0 (the "License");
  8296. * you may not use this file except in compliance with the License.
  8297. * You may obtain a copy of the License at
  8298. *
  8299. * http://www.apache.org/licenses/LICENSE-2.0
  8300. *
  8301. * Unless required by applicable law or agreed to in writing, software
  8302. * distributed under the License is distributed on an "AS IS" BASIS,
  8303. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8304. * See the License for the specific language governing permissions and
  8305. * limitations under the License.
  8306. */ function eu(t, e) {
  8307. var n = t[0], r = t[1], i = e[0], o = e[1], u = rt(n, i);
  8308. return 0 === u ? rt(r, o) : u;
  8309. }
  8310. /**
  8311. * Used to calculate the nth sequence number. Keeps a rolling buffer of the
  8312. * lowest n values passed to `addElement`, and finally reports the largest of
  8313. * them in `maxValue`.
  8314. */ var nu = /** @class */ function() {
  8315. function t(t) {
  8316. this.xn = t, this.buffer = new Ze(eu), this.Nn = 0;
  8317. }
  8318. return t.prototype.kn = function() {
  8319. return ++this.Nn;
  8320. }, t.prototype.On = function(t) {
  8321. var e = [ t, this.kn() ];
  8322. if (this.buffer.size < this.xn) this.buffer = this.buffer.add(e); else {
  8323. var n = this.buffer.last();
  8324. eu(e, n) < 0 && (this.buffer = this.buffer.delete(n).add(e));
  8325. }
  8326. }, Object.defineProperty(t.prototype, "maxValue", {
  8327. get: function() {
  8328. // Guaranteed to be non-empty. If we decide we are not collecting any
  8329. // sequence numbers, nthSequenceNumber below short-circuits. If we have
  8330. // decided that we are collecting n sequence numbers, it's because n is some
  8331. // percentage of the existing sequence numbers. That means we should never
  8332. // be in a situation where we are collecting sequence numbers but don't
  8333. // actually have any.
  8334. return this.buffer.last()[0];
  8335. },
  8336. enumerable: !1,
  8337. configurable: !0
  8338. }), t;
  8339. }(), ru = /** @class */ function() {
  8340. function t(t, e, n) {
  8341. this.garbageCollector = t, this.asyncQueue = e, this.localStore = n, this.Mn = null;
  8342. }
  8343. return t.prototype.start = function() {
  8344. -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Fn(6e4);
  8345. }, t.prototype.stop = function() {
  8346. this.Mn && (this.Mn.cancel(), this.Mn = null);
  8347. }, Object.defineProperty(t.prototype, "started", {
  8348. get: function() {
  8349. return null !== this.Mn;
  8350. },
  8351. enumerable: !1,
  8352. configurable: !0
  8353. }), t.prototype.Fn = function(t) {
  8354. var r = this;
  8355. V("LruGarbageCollector", "Garbage collection scheduled in ".concat(t, "ms")), this.Mn = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection" /* TimerId.LruGarbageCollection */ , t, (function() {
  8356. return e(r, void 0, void 0, (function() {
  8357. var t;
  8358. return n(this, (function(e) {
  8359. switch (e.label) {
  8360. case 0:
  8361. this.Mn = null, e.label = 1;
  8362. case 1:
  8363. return e.trys.push([ 1, 3, , 7 ]), [ 4 /*yield*/ , this.localStore.collectGarbage(this.garbageCollector) ];
  8364. case 2:
  8365. return e.sent(), [ 3 /*break*/ , 7 ];
  8366. case 3:
  8367. return Ft(t = e.sent()) ? (V("LruGarbageCollector", "Ignoring IndexedDB error during garbage collection: ", t),
  8368. [ 3 /*break*/ , 6 ]) : [ 3 /*break*/ , 4 ];
  8369. case 4:
  8370. return [ 4 /*yield*/ , Dt(t) ];
  8371. case 5:
  8372. e.sent(), e.label = 6;
  8373. case 6:
  8374. return [ 3 /*break*/ , 7 ];
  8375. case 7:
  8376. return [ 4 /*yield*/ , this.Fn(3e5) ];
  8377. case 8:
  8378. return e.sent(), [ 2 /*return*/ ];
  8379. }
  8380. }));
  8381. }));
  8382. }));
  8383. }, t;
  8384. }(), iu = /** @class */ function() {
  8385. function t(t, e) {
  8386. this.$n = t, this.params = e;
  8387. }
  8388. return t.prototype.calculateTargetCount = function(t, e) {
  8389. return this.$n.Bn(t).next((function(t) {
  8390. return Math.floor(e / 100 * t);
  8391. }));
  8392. }, t.prototype.nthSequenceNumber = function(t, e) {
  8393. var n = this;
  8394. if (0 === e) return xt.resolve(qt.at);
  8395. var r = new nu(e);
  8396. return this.$n.forEachTarget(t, (function(t) {
  8397. return r.On(t.sequenceNumber);
  8398. })).next((function() {
  8399. return n.$n.Ln(t, (function(t) {
  8400. return r.On(t);
  8401. }));
  8402. })).next((function() {
  8403. return r.maxValue;
  8404. }));
  8405. }, t.prototype.removeTargets = function(t, e, n) {
  8406. return this.$n.removeTargets(t, e, n);
  8407. }, t.prototype.removeOrphanedDocuments = function(t, e) {
  8408. return this.$n.removeOrphanedDocuments(t, e);
  8409. }, t.prototype.collect = function(t, e) {
  8410. var n = this;
  8411. return -1 === this.params.cacheSizeCollectionThreshold ? (V("LruGarbageCollector", "Garbage collection skipped; disabled"),
  8412. xt.resolve(Bo)) : this.getCacheSize(t).next((function(r) {
  8413. return r < n.params.cacheSizeCollectionThreshold ? (V("LruGarbageCollector", "Garbage collection skipped; Cache size ".concat(r, " is lower than threshold ").concat(n.params.cacheSizeCollectionThreshold)),
  8414. Bo) : n.qn(t, e);
  8415. }));
  8416. }, t.prototype.getCacheSize = function(t) {
  8417. return this.$n.getCacheSize(t);
  8418. }, t.prototype.qn = function(t, e) {
  8419. var n, r, i, o, u, a, s, c = this, l = Date.now();
  8420. return this.calculateTargetCount(t, this.params.percentileToCollect).next((function(e) {
  8421. // Cap at the configured max
  8422. return e > c.params.maximumSequenceNumbersToCollect ? (V("LruGarbageCollector", "Capping sequence numbers to collect down to the maximum of ".concat(c.params.maximumSequenceNumbersToCollect, " from ").concat(e)),
  8423. r = c.params.maximumSequenceNumbersToCollect) : r = e, o = Date.now(), c.nthSequenceNumber(t, r);
  8424. })).next((function(r) {
  8425. return n = r, u = Date.now(), c.removeTargets(t, n, e);
  8426. })).next((function(e) {
  8427. return i = e, a = Date.now(), c.removeOrphanedDocuments(t, n);
  8428. })).next((function(t) {
  8429. return s = Date.now(), O() <= h.DEBUG && V("LruGarbageCollector", "LRU Garbage Collection\n\tCounted targets in ".concat(o - l, "ms\n\tDetermined least recently used ").concat(r, " in ") + (u - o) + "ms\n" + "\tRemoved ".concat(i, " targets in ") + (a - u) + "ms\n" + "\tRemoved ".concat(t, " documents in ") + (s - a) + "ms\n" + "Total Duration: ".concat(s - l, "ms")),
  8430. xt.resolve({
  8431. didRun: !0,
  8432. sequenceNumbersCollected: r,
  8433. targetsRemoved: i,
  8434. documentsRemoved: t
  8435. });
  8436. }));
  8437. }, t;
  8438. }(), ou = /** @class */ function() {
  8439. function t(t, e) {
  8440. this.db = t, this.garbageCollector = function(t, e) {
  8441. return new iu(t, e);
  8442. }(this, e);
  8443. }
  8444. return t.prototype.Bn = function(t) {
  8445. var e = this.Un(t);
  8446. return this.db.getTargetCache().getTargetCount(t).next((function(t) {
  8447. return e.next((function(e) {
  8448. return t + e;
  8449. }));
  8450. }));
  8451. }, t.prototype.Un = function(t) {
  8452. var e = 0;
  8453. return this.Ln(t, (function(t) {
  8454. e++;
  8455. })).next((function() {
  8456. return e;
  8457. }));
  8458. }, t.prototype.forEachTarget = function(t, e) {
  8459. return this.db.getTargetCache().forEachTarget(t, e);
  8460. }, t.prototype.Ln = function(t, e) {
  8461. return this.Kn(t, (function(t, n) {
  8462. return e(n);
  8463. }));
  8464. }, t.prototype.addReference = function(t, e, n) {
  8465. return uu(t, n);
  8466. }, t.prototype.removeReference = function(t, e, n) {
  8467. return uu(t, n);
  8468. }, t.prototype.removeTargets = function(t, e, n) {
  8469. return this.db.getTargetCache().removeTargets(t, e, n);
  8470. }, t.prototype.markPotentiallyOrphaned = function(t, e) {
  8471. return uu(t, e);
  8472. },
  8473. /**
  8474. * Returns true if anything would prevent this document from being garbage
  8475. * collected, given that the document in question is not present in any
  8476. * targets and has a sequence number less than or equal to the upper bound for
  8477. * the collection run.
  8478. */
  8479. t.prototype.Gn = function(t, e) {
  8480. return function(t, e) {
  8481. var n = !1;
  8482. return Yo(t).tt((function(r) {
  8483. return zo(t, r, e).next((function(t) {
  8484. return t && (n = !0), xt.resolve(!t);
  8485. }));
  8486. })).next((function() {
  8487. return n;
  8488. }));
  8489. }(t, e);
  8490. }, t.prototype.removeOrphanedDocuments = function(t, e) {
  8491. var n = this, r = this.db.getRemoteDocumentCache().newChangeBuffer(), i = [], o = 0;
  8492. return this.Kn(t, (function(u, a) {
  8493. if (a <= e) {
  8494. var s = n.Gn(t, u).next((function(e) {
  8495. if (!e)
  8496. // Our size accounting requires us to read all documents before
  8497. // removing them.
  8498. return o++, r.getEntry(t, u).next((function() {
  8499. return r.removeEntry(u, at.min()), tu(t).delete([ 0, yi(u.path) ]);
  8500. }));
  8501. }));
  8502. i.push(s);
  8503. }
  8504. })).next((function() {
  8505. return xt.waitFor(i);
  8506. })).next((function() {
  8507. return r.apply(t);
  8508. })).next((function() {
  8509. return o;
  8510. }));
  8511. }, t.prototype.removeTarget = function(t, e) {
  8512. var n = e.withSequenceNumber(t.currentSequenceNumber);
  8513. return this.db.getTargetCache().updateTargetData(t, n);
  8514. }, t.prototype.updateLimboDocument = function(t, e) {
  8515. return uu(t, e);
  8516. },
  8517. /**
  8518. * Call provided function for each document in the cache that is 'orphaned'. Orphaned
  8519. * means not a part of any target, so the only entry in the target-document index for
  8520. * that document will be the sentinel row (targetId 0), which will also have the sequence
  8521. * number for the last time the document was accessed.
  8522. */
  8523. t.prototype.Kn = function(t, e) {
  8524. var n, r = tu(t), i = qt.at;
  8525. return r.Z({
  8526. index: "documentTargetsIndex"
  8527. }, (function(t, r) {
  8528. var o = t[0];
  8529. t[1];
  8530. var u = r.path, a = r.sequenceNumber;
  8531. 0 === o ? (
  8532. // if nextToReport is valid, report it, this is a new key so the
  8533. // last one must not be a member of any targets.
  8534. i !== qt.at && e(new ft(gi(n)), i),
  8535. // set nextToReport to be this sequence number. It's the next one we
  8536. // might report, if we don't find any targets for this document.
  8537. // Note that the sequence number must be defined when the targetId
  8538. // is 0.
  8539. i = a, n = u) :
  8540. // set nextToReport to be invalid, we know we don't need to report
  8541. // this one since we found a target for it.
  8542. i = qt.at;
  8543. })).next((function() {
  8544. // Since we report sequence numbers after getting to the next key, we
  8545. // need to check if the last key we iterated over was an orphaned
  8546. // document and report it.
  8547. i !== qt.at && e(new ft(gi(n)), i);
  8548. }));
  8549. }, t.prototype.getCacheSize = function(t) {
  8550. return this.db.getRemoteDocumentCache().getSize(t);
  8551. }, t;
  8552. }();
  8553. /**
  8554. * This class is responsible for the scheduling of LRU garbage collection. It handles checking
  8555. * whether or not GC is enabled, as well as which delay to use before the next run.
  8556. */ function uu(t, e) {
  8557. return tu(t).put(
  8558. /**
  8559. * @returns A value suitable for writing a sentinel row in the target-document
  8560. * store.
  8561. */
  8562. function(t, e) {
  8563. return {
  8564. targetId: 0,
  8565. path: yi(t.path),
  8566. sequenceNumber: e
  8567. };
  8568. }(e, t.currentSequenceNumber));
  8569. }
  8570. /**
  8571. * @license
  8572. * Copyright 2017 Google LLC
  8573. *
  8574. * Licensed under the Apache License, Version 2.0 (the "License");
  8575. * you may not use this file except in compliance with the License.
  8576. * You may obtain a copy of the License at
  8577. *
  8578. * http://www.apache.org/licenses/LICENSE-2.0
  8579. *
  8580. * Unless required by applicable law or agreed to in writing, software
  8581. * distributed under the License is distributed on an "AS IS" BASIS,
  8582. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8583. * See the License for the specific language governing permissions and
  8584. * limitations under the License.
  8585. */
  8586. /**
  8587. * An in-memory buffer of entries to be written to a RemoteDocumentCache.
  8588. * It can be used to batch up a set of changes to be written to the cache, but
  8589. * additionally supports reading entries back with the `getEntry()` method,
  8590. * falling back to the underlying RemoteDocumentCache if no entry is
  8591. * buffered.
  8592. *
  8593. * Entries added to the cache *must* be read first. This is to facilitate
  8594. * calculating the size delta of the pending changes.
  8595. *
  8596. * PORTING NOTE: This class was implemented then removed from other platforms.
  8597. * If byte-counting ends up being needed on the other platforms, consider
  8598. * porting this class as part of that implementation work.
  8599. */ var au = /** @class */ function() {
  8600. function t() {
  8601. // A mapping of document key to the new cache entry that should be written.
  8602. this.changes = new pr((function(t) {
  8603. return t.toString();
  8604. }), (function(t, e) {
  8605. return t.isEqual(e);
  8606. })), this.changesApplied = !1
  8607. /**
  8608. * Buffers a `RemoteDocumentCache.addEntry()` call.
  8609. *
  8610. * You can only modify documents that have already been retrieved via
  8611. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  8612. */;
  8613. }
  8614. return t.prototype.addEntry = function(t) {
  8615. this.assertNotApplied(), this.changes.set(t.key, t);
  8616. },
  8617. /**
  8618. * Buffers a `RemoteDocumentCache.removeEntry()` call.
  8619. *
  8620. * You can only remove documents that have already been retrieved via
  8621. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  8622. */
  8623. t.prototype.removeEntry = function(t, e) {
  8624. this.assertNotApplied(), this.changes.set(t, rn.newInvalidDocument(t).setReadTime(e));
  8625. },
  8626. /**
  8627. * Looks up an entry in the cache. The buffered changes will first be checked,
  8628. * and if no buffered change applies, this will forward to
  8629. * `RemoteDocumentCache.getEntry()`.
  8630. *
  8631. * @param transaction - The transaction in which to perform any persistence
  8632. * operations.
  8633. * @param documentKey - The key of the entry to look up.
  8634. * @returns The cached document or an invalid document if we have nothing
  8635. * cached.
  8636. */
  8637. t.prototype.getEntry = function(t, e) {
  8638. this.assertNotApplied();
  8639. var n = this.changes.get(e);
  8640. return void 0 !== n ? xt.resolve(n) : this.getFromCache(t, e);
  8641. },
  8642. /**
  8643. * Looks up several entries in the cache, forwarding to
  8644. * `RemoteDocumentCache.getEntry()`.
  8645. *
  8646. * @param transaction - The transaction in which to perform any persistence
  8647. * operations.
  8648. * @param documentKeys - The keys of the entries to look up.
  8649. * @returns A map of cached documents, indexed by key. If an entry cannot be
  8650. * found, the corresponding key will be mapped to an invalid document.
  8651. */
  8652. t.prototype.getEntries = function(t, e) {
  8653. return this.getAllFromCache(t, e);
  8654. },
  8655. /**
  8656. * Applies buffered changes to the underlying RemoteDocumentCache, using
  8657. * the provided transaction.
  8658. */
  8659. t.prototype.apply = function(t) {
  8660. return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(t);
  8661. },
  8662. /** Helper to assert this.changes is not null */ t.prototype.assertNotApplied = function() {},
  8663. t;
  8664. }(), su = /** @class */ function() {
  8665. function t(t) {
  8666. this.yt = t;
  8667. }
  8668. return t.prototype.setIndexManager = function(t) {
  8669. this.indexManager = t;
  8670. },
  8671. /**
  8672. * Adds the supplied entries to the cache.
  8673. *
  8674. * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
  8675. * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
  8676. */
  8677. t.prototype.addEntry = function(t, e, n) {
  8678. return fu(t).put(n);
  8679. },
  8680. /**
  8681. * Removes a document from the cache.
  8682. *
  8683. * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
  8684. * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
  8685. */
  8686. t.prototype.removeEntry = function(t, e, n) {
  8687. return fu(t).delete(
  8688. /**
  8689. * Returns a key that can be used for document lookups via the primary key of
  8690. * the DbRemoteDocument object store.
  8691. */
  8692. function(t, e) {
  8693. var n = t.path.toArray();
  8694. return [
  8695. /* prefix path */ n.slice(0, n.length - 2),
  8696. /* collection id */ n[n.length - 2], Xi(e),
  8697. /* document id */ n[n.length - 1] ];
  8698. }(e, n));
  8699. },
  8700. /**
  8701. * Updates the current cache size.
  8702. *
  8703. * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the
  8704. * cache's metadata.
  8705. */
  8706. t.prototype.updateMetadata = function(t, e) {
  8707. var n = this;
  8708. return this.getMetadata(t).next((function(r) {
  8709. return r.byteSize += e, n.Qn(t, r);
  8710. }));
  8711. }, t.prototype.getEntry = function(t, e) {
  8712. var n = this, r = rn.newInvalidDocument(e);
  8713. return fu(t).Z({
  8714. index: "documentKeyIndex",
  8715. range: IDBKeyRange.only(du(e))
  8716. }, (function(t, i) {
  8717. r = n.jn(e, i);
  8718. })).next((function() {
  8719. return r;
  8720. }));
  8721. },
  8722. /**
  8723. * Looks up an entry in the cache.
  8724. *
  8725. * @param documentKey - The key of the entry to look up.
  8726. * @returns The cached document entry and its size.
  8727. */
  8728. t.prototype.Wn = function(t, e) {
  8729. var n = this, r = {
  8730. size: 0,
  8731. document: rn.newInvalidDocument(e)
  8732. };
  8733. return fu(t).Z({
  8734. index: "documentKeyIndex",
  8735. range: IDBKeyRange.only(du(e))
  8736. }, (function(t, i) {
  8737. r = {
  8738. document: n.jn(e, i),
  8739. size: jo(i)
  8740. };
  8741. })).next((function() {
  8742. return r;
  8743. }));
  8744. }, t.prototype.getEntries = function(t, e) {
  8745. var n = this, r = vr();
  8746. return this.zn(t, e, (function(t, e) {
  8747. var i = n.jn(t, e);
  8748. r = r.insert(t, i);
  8749. })).next((function() {
  8750. return r;
  8751. }));
  8752. },
  8753. /**
  8754. * Looks up several entries in the cache.
  8755. *
  8756. * @param documentKeys - The set of keys entries to look up.
  8757. * @returns A map of documents indexed by key and a map of sizes indexed by
  8758. * key (zero if the document does not exist).
  8759. */
  8760. t.prototype.Hn = function(t, e) {
  8761. var n = this, r = vr(), i = new He(ft.comparator);
  8762. return this.zn(t, e, (function(t, e) {
  8763. var o = n.jn(t, e);
  8764. r = r.insert(t, o), i = i.insert(t, jo(e));
  8765. })).next((function() {
  8766. return {
  8767. documents: r,
  8768. Jn: i
  8769. };
  8770. }));
  8771. }, t.prototype.zn = function(t, e, n) {
  8772. if (e.isEmpty()) return xt.resolve();
  8773. var i = new Ze(yu);
  8774. e.forEach((function(t) {
  8775. return i = i.add(t);
  8776. }));
  8777. var o = IDBKeyRange.bound(du(i.first()), du(i.last())), u = i.getIterator(), a = u.getNext();
  8778. return fu(t).Z({
  8779. index: "documentKeyIndex",
  8780. range: o
  8781. }, (function(t, e, i) {
  8782. // Go through keys not found in cache.
  8783. for (var o = ft.fromSegments(r(r([], e.prefixPath, !0), [ e.collectionGroup, e.documentId ], !1)); a && yu(a, o) < 0; ) n(a, null),
  8784. a = u.getNext();
  8785. a && a.isEqual(o) && (
  8786. // Key found in cache.
  8787. n(a, e), a = u.hasNext() ? u.getNext() : null),
  8788. // Skip to the next key (if there is one).
  8789. a ? i.j(du(a)) : i.done();
  8790. })).next((function() {
  8791. // The rest of the keys are not in the cache. One case where `iterate`
  8792. // above won't go through them is when the cache is empty.
  8793. for (;a; ) n(a, null), a = u.hasNext() ? u.getNext() : null;
  8794. }));
  8795. }, t.prototype.getAllFromCollection = function(t, e, n) {
  8796. var r = this, i = [ e.popLast().toArray(), e.lastSegment(), Xi(n.readTime), n.documentKey.path.isEmpty() ? "" : n.documentKey.path.lastSegment() ], o = [ e.popLast().toArray(), e.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], "" ];
  8797. return fu(t).W(IDBKeyRange.bound(i, o, !0)).next((function(t) {
  8798. for (var e = vr(), n = 0, i = t; n < i.length; n++) {
  8799. var o = i[n], u = r.jn(ft.fromSegments(o.prefixPath.concat(o.collectionGroup, o.documentId)), o);
  8800. e = e.insert(u.key, u);
  8801. }
  8802. return e;
  8803. }));
  8804. }, t.prototype.getAllFromCollectionGroup = function(t, e, n, r) {
  8805. var i = this, o = vr(), u = pu(e, n), a = pu(e, Tt.max());
  8806. return fu(t).Z({
  8807. index: "collectionGroupIndex",
  8808. range: IDBKeyRange.bound(u, a, !0)
  8809. }, (function(t, e, n) {
  8810. var u = i.jn(ft.fromSegments(e.prefixPath.concat(e.collectionGroup, e.documentId)), e);
  8811. (o = o.insert(u.key, u)).size === r && n.done();
  8812. })).next((function() {
  8813. return o;
  8814. }));
  8815. }, t.prototype.newChangeBuffer = function(t) {
  8816. return new lu(this, !!t && t.trackRemovals);
  8817. }, t.prototype.getSize = function(t) {
  8818. return this.getMetadata(t).next((function(t) {
  8819. return t.byteSize;
  8820. }));
  8821. }, t.prototype.getMetadata = function(t) {
  8822. return hu(t).get("remoteDocumentGlobalKey").next((function(t) {
  8823. return U(!!t), t;
  8824. }));
  8825. }, t.prototype.Qn = function(t, e) {
  8826. return hu(t).put("remoteDocumentGlobalKey", e);
  8827. },
  8828. /**
  8829. * Decodes `dbRemoteDoc` and returns the document (or an invalid document if
  8830. * the document corresponds to the format used for sentinel deletes).
  8831. */
  8832. t.prototype.jn = function(t, e) {
  8833. if (e) {
  8834. var n =
  8835. /** Decodes a remote document from storage locally to a Document. */ function(t, e) {
  8836. var n;
  8837. if (e.document) n = ti(t.ie, e.document, !!e.hasCommittedMutations); else if (e.noDocument) {
  8838. var r = ft.fromSegments(e.noDocument.path), i = Ji(e.noDocument.readTime);
  8839. n = rn.newNoDocument(r, i), e.hasCommittedMutations && n.setHasCommittedMutations();
  8840. } else {
  8841. if (!e.unknownDocument) return q();
  8842. var o = ft.fromSegments(e.unknownDocument.path), u = Ji(e.unknownDocument.version);
  8843. n = rn.newUnknownDocument(o, u);
  8844. }
  8845. return e.readTime && n.setReadTime(function(t) {
  8846. var e = new ut(t[0], t[1]);
  8847. return at.fromTimestamp(e);
  8848. }(e.readTime)), n;
  8849. }(this.yt, e);
  8850. // Whether the document is a sentinel removal and should only be used in the
  8851. // `getNewDocumentChanges()`
  8852. if (!n.isNoDocument() || !n.version.isEqual(at.min())) return n;
  8853. }
  8854. return rn.newInvalidDocument(t);
  8855. }, t;
  8856. }();
  8857. /**
  8858. * @license
  8859. * Copyright 2017 Google LLC
  8860. *
  8861. * Licensed under the Apache License, Version 2.0 (the "License");
  8862. * you may not use this file except in compliance with the License.
  8863. * You may obtain a copy of the License at
  8864. *
  8865. * http://www.apache.org/licenses/LICENSE-2.0
  8866. *
  8867. * Unless required by applicable law or agreed to in writing, software
  8868. * distributed under the License is distributed on an "AS IS" BASIS,
  8869. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8870. * See the License for the specific language governing permissions and
  8871. * limitations under the License.
  8872. */
  8873. /**
  8874. * The RemoteDocumentCache for IndexedDb. To construct, invoke
  8875. * `newIndexedDbRemoteDocumentCache()`.
  8876. */
  8877. /** Creates a new IndexedDbRemoteDocumentCache. */ function cu(t) {
  8878. return new su(t);
  8879. }
  8880. /**
  8881. * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.
  8882. *
  8883. * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size
  8884. * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb
  8885. * when we apply the changes.
  8886. */ var lu = /** @class */ function(e) {
  8887. /**
  8888. * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.
  8889. * @param trackRemovals - Whether to create sentinel deletes that can be tracked by
  8890. * `getNewDocumentChanges()`.
  8891. */
  8892. function n(t, n) {
  8893. var r = this;
  8894. return (r = e.call(this) || this).Yn = t, r.trackRemovals = n,
  8895. // A map of document sizes and read times prior to applying the changes in
  8896. // this buffer.
  8897. r.Xn = new pr((function(t) {
  8898. return t.toString();
  8899. }), (function(t, e) {
  8900. return t.isEqual(e);
  8901. })), r;
  8902. }
  8903. return t(n, e), n.prototype.applyChanges = function(t) {
  8904. var e = this, n = [], r = 0, i = new Ze((function(t, e) {
  8905. return rt(t.canonicalString(), e.canonicalString());
  8906. }));
  8907. return this.changes.forEach((function(o, u) {
  8908. var a = e.Xn.get(o);
  8909. if (n.push(e.Yn.removeEntry(t, o, a.readTime)), u.isValidDocument()) {
  8910. var s = Yi(e.Yn.yt, u);
  8911. i = i.add(o.path.popLast());
  8912. var c = jo(s);
  8913. r += c - a.size, n.push(e.Yn.addEntry(t, o, s));
  8914. } else if (r -= a.size, e.trackRemovals) {
  8915. // In order to track removals, we store a "sentinel delete" in the
  8916. // RemoteDocumentCache. This entry is represented by a NoDocument
  8917. // with a version of 0 and ignored by `maybeDecodeDocument()` but
  8918. // preserved in `getNewDocumentChanges()`.
  8919. var l = Yi(e.Yn.yt, u.convertToNoDocument(at.min()));
  8920. n.push(e.Yn.addEntry(t, o, l));
  8921. }
  8922. })), i.forEach((function(r) {
  8923. n.push(e.Yn.indexManager.addToCollectionParentIndex(t, r));
  8924. })), n.push(this.Yn.updateMetadata(t, r)), xt.waitFor(n);
  8925. }, n.prototype.getFromCache = function(t, e) {
  8926. var n = this;
  8927. // Record the size of everything we load from the cache so we can compute a delta later.
  8928. return this.Yn.Wn(t, e).next((function(t) {
  8929. return n.Xn.set(e, {
  8930. size: t.size,
  8931. readTime: t.document.readTime
  8932. }), t.document;
  8933. }));
  8934. }, n.prototype.getAllFromCache = function(t, e) {
  8935. var n = this;
  8936. // Record the size of everything we load from the cache so we can compute
  8937. // a delta later.
  8938. return this.Yn.Hn(t, e).next((function(t) {
  8939. var e = t.documents;
  8940. // Note: `getAllFromCache` returns two maps instead of a single map from
  8941. // keys to `DocumentSizeEntry`s. This is to allow returning the
  8942. // `MutableDocumentMap` directly, without a conversion.
  8943. return t.Jn.forEach((function(t, r) {
  8944. n.Xn.set(t, {
  8945. size: r,
  8946. readTime: e.get(t).readTime
  8947. });
  8948. })), e;
  8949. }));
  8950. }, n;
  8951. }(au);
  8952. function hu(t) {
  8953. return Ki(t, "remoteDocumentGlobal");
  8954. }
  8955. /**
  8956. * Helper to get a typed SimpleDbStore for the remoteDocuments object store.
  8957. */ function fu(t) {
  8958. return Ki(t, "remoteDocumentsV14");
  8959. }
  8960. /**
  8961. * Returns a key that can be used for document lookups on the
  8962. * `DbRemoteDocumentDocumentKeyIndex` index.
  8963. */ function du(t) {
  8964. var e = t.path.toArray();
  8965. return [
  8966. /* prefix path */ e.slice(0, e.length - 2),
  8967. /* collection id */ e[e.length - 2],
  8968. /* document id */ e[e.length - 1] ];
  8969. }
  8970. function pu(t, e) {
  8971. var n = e.documentKey.path.toArray();
  8972. return [
  8973. /* collection id */ t, Xi(e.readTime),
  8974. /* prefix path */ n.slice(0, n.length - 2),
  8975. /* document id */ n.length > 0 ? n[n.length - 1] : "" ];
  8976. }
  8977. /**
  8978. * Comparator that compares document keys according to the primary key sorting
  8979. * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id
  8980. * and then document ID).
  8981. *
  8982. * Visible for testing.
  8983. */ function yu(t, e) {
  8984. for (var n = t.path.toArray(), r = e.path.toArray(), i = 0, o = 0
  8985. // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74
  8986. ; o < n.length - 2 && o < r.length - 2; ++o) if (i = rt(n[o], r[o])) return i;
  8987. return (i = rt(n.length, r.length)) || ((i = rt(n[n.length - 2], r[r.length - 2])) || rt(n[n.length - 1], r[r.length - 1]));
  8988. }
  8989. /**
  8990. * @license
  8991. * Copyright 2017 Google LLC
  8992. *
  8993. * Licensed under the Apache License, Version 2.0 (the "License");
  8994. * you may not use this file except in compliance with the License.
  8995. * You may obtain a copy of the License at
  8996. *
  8997. * http://www.apache.org/licenses/LICENSE-2.0
  8998. *
  8999. * Unless required by applicable law or agreed to in writing, software
  9000. * distributed under the License is distributed on an "AS IS" BASIS,
  9001. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9002. * See the License for the specific language governing permissions and
  9003. * limitations under the License.
  9004. */
  9005. /**
  9006. * Schema Version for the Web client:
  9007. * 1. Initial version including Mutation Queue, Query Cache, and Remote
  9008. * Document Cache
  9009. * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No
  9010. * longer required because migration 3 unconditionally clears it.
  9011. * 3. Dropped and re-created Query Cache to deal with cache corruption related
  9012. * to limbo resolution. Addresses
  9013. * https://github.com/firebase/firebase-ios-sdk/issues/1548
  9014. * 4. Multi-Tab Support.
  9015. * 5. Removal of held write acks.
  9016. * 6. Create document global for tracking document cache size.
  9017. * 7. Ensure every cached document has a sentinel row with a sequence number.
  9018. * 8. Add collection-parent index for Collection Group queries.
  9019. * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than
  9020. * an auto-incrementing ID. This is required for Index-Free queries.
  9021. * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.
  9022. * 11. Add bundles and named_queries for bundle support.
  9023. * 12. Add document overlays.
  9024. * 13. Rewrite the keys of the remote document cache to allow for efficient
  9025. * document lookup via `getAll()`.
  9026. * 14. Add overlays.
  9027. * 15. Add indexing support.
  9028. */
  9029. /**
  9030. * @license
  9031. * Copyright 2022 Google LLC
  9032. *
  9033. * Licensed under the Apache License, Version 2.0 (the "License");
  9034. * you may not use this file except in compliance with the License.
  9035. * You may obtain a copy of the License at
  9036. *
  9037. * http://www.apache.org/licenses/LICENSE-2.0
  9038. *
  9039. * Unless required by applicable law or agreed to in writing, software
  9040. * distributed under the License is distributed on an "AS IS" BASIS,
  9041. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9042. * See the License for the specific language governing permissions and
  9043. * limitations under the License.
  9044. */
  9045. /**
  9046. * Represents a local view (overlay) of a document, and the fields that are
  9047. * locally mutated.
  9048. */ var vu = function(t,
  9049. /**
  9050. * The fields that are locally mutated by patch mutations.
  9051. *
  9052. * If the overlayed document is from set or delete mutations, this is `null`.
  9053. * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.
  9054. */
  9055. e) {
  9056. this.overlayedDocument = t, this.mutatedFields = e;
  9057. }, mu = /** @class */ function() {
  9058. function t(t, e, n, r) {
  9059. this.remoteDocumentCache = t, this.mutationQueue = e, this.documentOverlayCache = n,
  9060. this.indexManager = r
  9061. /**
  9062. * Get the local view of the document identified by `key`.
  9063. *
  9064. * @returns Local view of the document or null if we don't have any cached
  9065. * state for it.
  9066. */;
  9067. }
  9068. return t.prototype.getDocument = function(t, e) {
  9069. var n = this, r = null;
  9070. return this.documentOverlayCache.getOverlay(t, e).next((function(i) {
  9071. return r = i, n.remoteDocumentCache.getEntry(t, e);
  9072. })).next((function(t) {
  9073. return null !== r && $n(r.mutation, t, tn.empty(), ut.now()), t;
  9074. }));
  9075. },
  9076. /**
  9077. * Gets the local view of the documents identified by `keys`.
  9078. *
  9079. * If we don't have cached state for a document in `keys`, a NoDocument will
  9080. * be stored for that key in the resulting set.
  9081. */
  9082. t.prototype.getDocuments = function(t, e) {
  9083. var n = this;
  9084. return this.remoteDocumentCache.getEntries(t, e).next((function(e) {
  9085. return n.getLocalViewOfDocuments(t, e, _r()).next((function() {
  9086. return e;
  9087. }));
  9088. }));
  9089. },
  9090. /**
  9091. * Similar to `getDocuments`, but creates the local view from the given
  9092. * `baseDocs` without retrieving documents from the local store.
  9093. *
  9094. * @param transaction - The transaction this operation is scoped to.
  9095. * @param docs - The documents to apply local mutations to get the local views.
  9096. * @param existenceStateChanged - The set of document keys whose existence state
  9097. * is changed. This is useful to determine if some documents overlay needs
  9098. * to be recalculated.
  9099. */
  9100. t.prototype.getLocalViewOfDocuments = function(t, e, n) {
  9101. var r = this;
  9102. void 0 === n && (n = _r());
  9103. var i = br();
  9104. return this.populateOverlays(t, i, e).next((function() {
  9105. return r.computeViews(t, e, i, n).next((function(t) {
  9106. var e = gr();
  9107. return t.forEach((function(t, n) {
  9108. e = e.insert(t, n.overlayedDocument);
  9109. })), e;
  9110. }));
  9111. }));
  9112. },
  9113. /**
  9114. * Gets the overlayed documents for the given document map, which will include
  9115. * the local view of those documents and a `FieldMask` indicating which fields
  9116. * are mutated locally, `null` if overlay is a Set or Delete mutation.
  9117. */
  9118. t.prototype.getOverlayedDocuments = function(t, e) {
  9119. var n = this, r = br();
  9120. return this.populateOverlays(t, r, e).next((function() {
  9121. return n.computeViews(t, e, r, _r());
  9122. }));
  9123. },
  9124. /**
  9125. * Fetches the overlays for {@code docs} and adds them to provided overlay map
  9126. * if the map does not already contain an entry for the given document key.
  9127. */
  9128. t.prototype.populateOverlays = function(t, e, n) {
  9129. var r = [];
  9130. return n.forEach((function(t) {
  9131. e.has(t) || r.push(t);
  9132. })), this.documentOverlayCache.getOverlays(t, r).next((function(t) {
  9133. t.forEach((function(t, n) {
  9134. e.set(t, n);
  9135. }));
  9136. }));
  9137. },
  9138. /**
  9139. * Computes the local view for the given documents.
  9140. *
  9141. * @param docs - The documents to compute views for. It also has the base
  9142. * version of the documents.
  9143. * @param overlays - The overlays that need to be applied to the given base
  9144. * version of the documents.
  9145. * @param existenceStateChanged - A set of documents whose existence states
  9146. * might have changed. This is used to determine if we need to re-calculate
  9147. * overlays from mutation queues.
  9148. * @return A map represents the local documents view.
  9149. */
  9150. t.prototype.computeViews = function(t, e, n, r) {
  9151. var i = vr(), o = Tr(), u = Tr();
  9152. return e.forEach((function(t, e) {
  9153. var u = n.get(e.key);
  9154. // Recalculate an overlay if the document's existence state changed due to
  9155. // a remote event *and* the overlay is a PatchMutation. This is because
  9156. // document existence state can change if some patch mutation's
  9157. // preconditions are met.
  9158. // NOTE: we recalculate when `overlay` is undefined as well, because there
  9159. // might be a patch mutation whose precondition does not match before the
  9160. // change (hence overlay is undefined), but would now match.
  9161. r.has(e.key) && (void 0 === u || u.mutation instanceof rr) ? i = i.insert(e.key, e) : void 0 !== u ? (o.set(e.key, u.mutation.getFieldMask()),
  9162. $n(u.mutation, e, u.mutation.getFieldMask(), ut.now())) :
  9163. // no overlay exists
  9164. // Using EMPTY to indicate there is no overlay for the document.
  9165. o.set(e.key, tn.empty());
  9166. })), this.recalculateAndSaveOverlays(t, i).next((function(t) {
  9167. return t.forEach((function(t, e) {
  9168. return o.set(t, e);
  9169. })), e.forEach((function(t, e) {
  9170. var n;
  9171. return u.set(t, new vu(e, null !== (n = o.get(t)) && void 0 !== n ? n : null));
  9172. })), u;
  9173. }));
  9174. }, t.prototype.recalculateAndSaveOverlays = function(t, e) {
  9175. var n = this, r = Tr(), i = new He((function(t, e) {
  9176. return t - e;
  9177. })), o = _r();
  9178. return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(t, e).next((function(t) {
  9179. for (var n = function(t) {
  9180. t.keys().forEach((function(n) {
  9181. var o = e.get(n);
  9182. if (null !== o) {
  9183. var u = r.get(n) || tn.empty();
  9184. u = t.applyToLocalView(o, u), r.set(n, u);
  9185. var a = (i.get(t.batchId) || _r()).add(n);
  9186. i = i.insert(t.batchId, a);
  9187. }
  9188. }));
  9189. }, o = 0, u = t; o < u.length; o++) {
  9190. n(u[o]);
  9191. }
  9192. })).next((function() {
  9193. // Iterate in descending order of batch IDs, and skip documents that are
  9194. // already saved.
  9195. for (var u = [], a = i.getReverseIterator(), s = function() {
  9196. var i = a.getNext(), s = i.key, c = i.value, l = Ir();
  9197. c.forEach((function(t) {
  9198. if (!o.has(t)) {
  9199. var n = Zn(e.get(t), r.get(t));
  9200. null !== n && l.set(t, n), o = o.add(t);
  9201. }
  9202. })), u.push(n.documentOverlayCache.saveOverlays(t, s, l));
  9203. }; a.hasNext(); ) s();
  9204. return xt.waitFor(u);
  9205. })).next((function() {
  9206. return r;
  9207. }));
  9208. },
  9209. /**
  9210. * Recalculates overlays by reading the documents from remote document cache
  9211. * first, and saves them after they are calculated.
  9212. */
  9213. t.prototype.recalculateAndSaveOverlaysForDocumentKeys = function(t, e) {
  9214. var n = this;
  9215. return this.remoteDocumentCache.getEntries(t, e).next((function(e) {
  9216. return n.recalculateAndSaveOverlays(t, e);
  9217. }));
  9218. },
  9219. /**
  9220. * Performs a query against the local view of all documents.
  9221. *
  9222. * @param transaction - The persistence transaction.
  9223. * @param query - The query to match documents against.
  9224. * @param offset - Read time and key to start scanning by (exclusive).
  9225. */
  9226. t.prototype.getDocumentsMatchingQuery = function(t, e, n) {
  9227. /**
  9228. * Returns whether the query matches a single document by path (rather than a
  9229. * collection).
  9230. */
  9231. return function(t) {
  9232. return ft.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
  9233. }(e) ? this.getDocumentsMatchingDocumentQuery(t, e.path) : wn(e) ? this.getDocumentsMatchingCollectionGroupQuery(t, e, n) : this.getDocumentsMatchingCollectionQuery(t, e, n);
  9234. },
  9235. /**
  9236. * Given a collection group, returns the next documents that follow the provided offset, along
  9237. * with an updated batch ID.
  9238. *
  9239. * <p>The documents returned by this method are ordered by remote version from the provided
  9240. * offset. If there are no more remote documents after the provided offset, documents with
  9241. * mutations in order of batch id from the offset are returned. Since all documents in a batch are
  9242. * returned together, the total number of documents returned can exceed {@code count}.
  9243. *
  9244. * @param transaction
  9245. * @param collectionGroup The collection group for the documents.
  9246. * @param offset The offset to index into.
  9247. * @param count The number of documents to return
  9248. * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.
  9249. */
  9250. t.prototype.getNextDocuments = function(t, e, n, r) {
  9251. var i = this;
  9252. return this.remoteDocumentCache.getAllFromCollectionGroup(t, e, n, r).next((function(o) {
  9253. var u = r - o.size > 0 ? i.documentOverlayCache.getOverlaysForCollectionGroup(t, e, n.largestBatchId, r - o.size) : xt.resolve(br()), a = -1, s = o;
  9254. // The callsite will use the largest batch ID together with the latest read time to create
  9255. // a new index offset. Since we only process batch IDs if all remote documents have been read,
  9256. // no overlay will increase the overall read time. This is why we only need to special case
  9257. // the batch id.
  9258. return u.next((function(e) {
  9259. return xt.forEach(e, (function(e, n) {
  9260. return a < n.largestBatchId && (a = n.largestBatchId), o.get(e) ? xt.resolve() : i.remoteDocumentCache.getEntry(t, e).next((function(t) {
  9261. s = s.insert(e, t);
  9262. }));
  9263. })).next((function() {
  9264. return i.populateOverlays(t, e, o);
  9265. })).next((function() {
  9266. return i.computeViews(t, s, e, _r());
  9267. })).next((function(t) {
  9268. return {
  9269. batchId: a,
  9270. changes: wr(t)
  9271. };
  9272. }));
  9273. }));
  9274. }));
  9275. }, t.prototype.getDocumentsMatchingDocumentQuery = function(t, e) {
  9276. // Just do a simple document lookup.
  9277. return this.getDocument(t, new ft(e)).next((function(t) {
  9278. var e = gr();
  9279. return t.isFoundDocument() && (e = e.insert(t.key, t)), e;
  9280. }));
  9281. }, t.prototype.getDocumentsMatchingCollectionGroupQuery = function(t, e, n) {
  9282. var r = this, i = e.collectionGroup, o = gr();
  9283. return this.indexManager.getCollectionParents(t, i).next((function(u) {
  9284. return xt.forEach(u, (function(u) {
  9285. var a = function(t, e) {
  9286. return new dn(e,
  9287. /*collectionGroup=*/ null, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  9288. }(e, u.child(i));
  9289. return r.getDocumentsMatchingCollectionQuery(t, a, n).next((function(t) {
  9290. t.forEach((function(t, e) {
  9291. o = o.insert(t, e);
  9292. }));
  9293. }));
  9294. })).next((function() {
  9295. return o;
  9296. }));
  9297. }));
  9298. }, t.prototype.getDocumentsMatchingCollectionQuery = function(t, e, n) {
  9299. var r, i = this;
  9300. // Query the remote documents and overlay mutations.
  9301. return this.remoteDocumentCache.getAllFromCollection(t, e.path, n).next((function(o) {
  9302. return r = o, i.documentOverlayCache.getOverlaysForCollection(t, e.path, n.largestBatchId);
  9303. })).next((function(t) {
  9304. // As documents might match the query because of their overlay we need to
  9305. // include documents for all overlays in the initial document set.
  9306. t.forEach((function(t, e) {
  9307. var n = e.getKey();
  9308. null === r.get(n) && (r = r.insert(n, rn.newInvalidDocument(n)));
  9309. }));
  9310. // Apply the overlays and match against the query.
  9311. var n = gr();
  9312. return r.forEach((function(r, i) {
  9313. var o = t.get(r);
  9314. void 0 !== o && $n(o.mutation, i, tn.empty(), ut.now()),
  9315. // Finally, insert the documents that still match the query
  9316. xn(e, i) && (n = n.insert(r, i));
  9317. })), n;
  9318. }));
  9319. }, t;
  9320. }(), gu = /** @class */ function() {
  9321. function t(t) {
  9322. this.yt = t, this.Zn = new Map, this.ts = new Map;
  9323. }
  9324. return t.prototype.getBundleMetadata = function(t, e) {
  9325. return xt.resolve(this.Zn.get(e));
  9326. }, t.prototype.saveBundleMetadata = function(t, e) {
  9327. /** Decodes a BundleMetadata proto into a BundleMetadata object. */
  9328. var n;
  9329. return this.Zn.set(e.id, {
  9330. id: (n = e).id,
  9331. version: n.version,
  9332. createTime: jr(n.createTime)
  9333. }), xt.resolve();
  9334. }, t.prototype.getNamedQuery = function(t, e) {
  9335. return xt.resolve(this.ts.get(e));
  9336. }, t.prototype.saveNamedQuery = function(t, e) {
  9337. return this.ts.set(e.name, function(t) {
  9338. return {
  9339. name: t.name,
  9340. query: no(t.bundledQuery),
  9341. readTime: jr(t.readTime)
  9342. };
  9343. }(e)), xt.resolve();
  9344. }, t;
  9345. }(), wu = /** @class */ function() {
  9346. function t() {
  9347. // A map sorted by DocumentKey, whose value is a pair of the largest batch id
  9348. // for the overlay and the overlay itself.
  9349. this.overlays = new He(ft.comparator), this.es = new Map;
  9350. }
  9351. return t.prototype.getOverlay = function(t, e) {
  9352. return xt.resolve(this.overlays.get(e));
  9353. }, t.prototype.getOverlays = function(t, e) {
  9354. var n = this, r = br();
  9355. return xt.forEach(e, (function(e) {
  9356. return n.getOverlay(t, e).next((function(t) {
  9357. null !== t && r.set(e, t);
  9358. }));
  9359. })).next((function() {
  9360. return r;
  9361. }));
  9362. }, t.prototype.saveOverlays = function(t, e, n) {
  9363. var r = this;
  9364. return n.forEach((function(n, i) {
  9365. r.oe(t, e, i);
  9366. })), xt.resolve();
  9367. }, t.prototype.removeOverlaysForBatchId = function(t, e, n) {
  9368. var r = this, i = this.es.get(n);
  9369. return void 0 !== i && (i.forEach((function(t) {
  9370. return r.overlays = r.overlays.remove(t);
  9371. })), this.es.delete(n)), xt.resolve();
  9372. }, t.prototype.getOverlaysForCollection = function(t, e, n) {
  9373. for (var r = br(), i = e.length + 1, o = new ft(e.child("")), u = this.overlays.getIteratorFrom(o); u.hasNext(); ) {
  9374. var a = u.getNext().value, s = a.getKey();
  9375. if (!e.isPrefixOf(s.path)) break;
  9376. // Documents from sub-collections
  9377. s.path.length === i && a.largestBatchId > n && r.set(a.getKey(), a);
  9378. }
  9379. return xt.resolve(r);
  9380. }, t.prototype.getOverlaysForCollectionGroup = function(t, e, n, r) {
  9381. for (var i = new He((function(t, e) {
  9382. return t - e;
  9383. })), o = this.overlays.getIterator(); o.hasNext(); ) {
  9384. var u = o.getNext().value;
  9385. if (u.getKey().getCollectionGroup() === e && u.largestBatchId > n) {
  9386. var a = i.get(u.largestBatchId);
  9387. null === a && (a = br(), i = i.insert(u.largestBatchId, a)), a.set(u.getKey(), u);
  9388. }
  9389. }
  9390. for (var s = br(), c = i.getIterator(); c.hasNext() && (c.getNext().value.forEach((function(t, e) {
  9391. return s.set(t, e);
  9392. })), !(s.size() >= r)); ) ;
  9393. return xt.resolve(s);
  9394. }, t.prototype.oe = function(t, e, n) {
  9395. // Remove the association of the overlay to its batch id.
  9396. var r = this.overlays.get(n.key);
  9397. if (null !== r) {
  9398. var i = this.es.get(r.largestBatchId).delete(n.key);
  9399. this.es.set(r.largestBatchId, i);
  9400. }
  9401. this.overlays = this.overlays.insert(n.key, new zi(e, n));
  9402. // Create the association of this overlay to the given largestBatchId.
  9403. var o = this.es.get(e);
  9404. void 0 === o && (o = _r(), this.es.set(e, o)), this.es.set(e, o.add(n.key));
  9405. }, t;
  9406. }(), bu = /** @class */ function() {
  9407. function t() {
  9408. // A set of outstanding references to a document sorted by key.
  9409. this.ns = new Ze(Iu.ss),
  9410. // A set of outstanding references to a document sorted by target id.
  9411. this.rs = new Ze(Iu.os)
  9412. /** Returns true if the reference set contains no references. */;
  9413. }
  9414. return t.prototype.isEmpty = function() {
  9415. return this.ns.isEmpty();
  9416. },
  9417. /** Adds a reference to the given document key for the given ID. */ t.prototype.addReference = function(t, e) {
  9418. var n = new Iu(t, e);
  9419. this.ns = this.ns.add(n), this.rs = this.rs.add(n);
  9420. },
  9421. /** Add references to the given document keys for the given ID. */ t.prototype.us = function(t, e) {
  9422. var n = this;
  9423. t.forEach((function(t) {
  9424. return n.addReference(t, e);
  9425. }));
  9426. },
  9427. /**
  9428. * Removes a reference to the given document key for the given
  9429. * ID.
  9430. */
  9431. t.prototype.removeReference = function(t, e) {
  9432. this.cs(new Iu(t, e));
  9433. }, t.prototype.hs = function(t, e) {
  9434. var n = this;
  9435. t.forEach((function(t) {
  9436. return n.removeReference(t, e);
  9437. }));
  9438. },
  9439. /**
  9440. * Clears all references with a given ID. Calls removeRef() for each key
  9441. * removed.
  9442. */
  9443. t.prototype.ls = function(t) {
  9444. var e = this, n = new ft(new ct([])), r = new Iu(n, t), i = new Iu(n, t + 1), o = [];
  9445. return this.rs.forEachInRange([ r, i ], (function(t) {
  9446. e.cs(t), o.push(t.key);
  9447. })), o;
  9448. }, t.prototype.fs = function() {
  9449. var t = this;
  9450. this.ns.forEach((function(e) {
  9451. return t.cs(e);
  9452. }));
  9453. }, t.prototype.cs = function(t) {
  9454. this.ns = this.ns.delete(t), this.rs = this.rs.delete(t);
  9455. }, t.prototype.ds = function(t) {
  9456. var e = new ft(new ct([])), n = new Iu(e, t), r = new Iu(e, t + 1), i = _r();
  9457. return this.rs.forEachInRange([ n, r ], (function(t) {
  9458. i = i.add(t.key);
  9459. })), i;
  9460. }, t.prototype.containsKey = function(t) {
  9461. var e = new Iu(t, 0), n = this.ns.firstAfterOrEqual(e);
  9462. return null !== n && t.isEqual(n.key);
  9463. }, t;
  9464. }(), Iu = /** @class */ function() {
  9465. function t(t, e) {
  9466. this.key = t, this._s = e
  9467. /** Compare by key then by ID */;
  9468. }
  9469. return t.ss = function(t, e) {
  9470. return ft.comparator(t.key, e.key) || rt(t._s, e._s);
  9471. },
  9472. /** Compare by ID then by key */ t.os = function(t, e) {
  9473. return rt(t._s, e._s) || ft.comparator(t.key, e.key);
  9474. }, t;
  9475. }(), Tu = /** @class */ function() {
  9476. function t(t, e) {
  9477. this.indexManager = t, this.referenceDelegate = e,
  9478. /**
  9479. * The set of all mutations that have been sent but not yet been applied to
  9480. * the backend.
  9481. */
  9482. this.mutationQueue = [],
  9483. /** Next value to use when assigning sequential IDs to each mutation batch. */
  9484. this.ws = 1,
  9485. /** An ordered mapping between documents and the mutations batch IDs. */
  9486. this.gs = new Ze(Iu.ss);
  9487. }
  9488. return t.prototype.checkEmpty = function(t) {
  9489. return xt.resolve(0 === this.mutationQueue.length);
  9490. }, t.prototype.addMutationBatch = function(t, e, n, r) {
  9491. var i = this.ws;
  9492. this.ws++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];
  9493. var o = new ji(i, e, n, r);
  9494. this.mutationQueue.push(o);
  9495. // Track references by document key and index collection parents.
  9496. for (var u = 0, a = r; u < a.length; u++) {
  9497. var s = a[u];
  9498. this.gs = this.gs.add(new Iu(s.key, i)), this.indexManager.addToCollectionParentIndex(t, s.key.path.popLast());
  9499. }
  9500. return xt.resolve(o);
  9501. }, t.prototype.lookupMutationBatch = function(t, e) {
  9502. return xt.resolve(this.ys(e));
  9503. }, t.prototype.getNextMutationBatchAfterBatchId = function(t, e) {
  9504. var n = e + 1, r = this.ps(n), i = r < 0 ? 0 : r;
  9505. // The requested batchId may still be out of range so normalize it to the
  9506. // start of the queue.
  9507. return xt.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);
  9508. }, t.prototype.getHighestUnacknowledgedBatchId = function() {
  9509. return xt.resolve(0 === this.mutationQueue.length ? -1 : this.ws - 1);
  9510. }, t.prototype.getAllMutationBatches = function(t) {
  9511. return xt.resolve(this.mutationQueue.slice());
  9512. }, t.prototype.getAllMutationBatchesAffectingDocumentKey = function(t, e) {
  9513. var n = this, r = new Iu(e, 0), i = new Iu(e, Number.POSITIVE_INFINITY), o = [];
  9514. return this.gs.forEachInRange([ r, i ], (function(t) {
  9515. var e = n.ys(t._s);
  9516. o.push(e);
  9517. })), xt.resolve(o);
  9518. }, t.prototype.getAllMutationBatchesAffectingDocumentKeys = function(t, e) {
  9519. var n = this, r = new Ze(rt);
  9520. return e.forEach((function(t) {
  9521. var e = new Iu(t, 0), i = new Iu(t, Number.POSITIVE_INFINITY);
  9522. n.gs.forEachInRange([ e, i ], (function(t) {
  9523. r = r.add(t._s);
  9524. }));
  9525. })), xt.resolve(this.Is(r));
  9526. }, t.prototype.getAllMutationBatchesAffectingQuery = function(t, e) {
  9527. // Use the query path as a prefix for testing if a document matches the
  9528. // query.
  9529. var n = e.path, r = n.length + 1, i = n;
  9530. // Construct a document reference for actually scanning the index. Unlike
  9531. // the prefix the document key in this reference must have an even number of
  9532. // segments. The empty segment can be used a suffix of the query path
  9533. // because it precedes all other segments in an ordered traversal.
  9534. ft.isDocumentKey(i) || (i = i.child(""));
  9535. var o = new Iu(new ft(i), 0), u = new Ze(rt);
  9536. // Find unique batchIDs referenced by all documents potentially matching the
  9537. // query.
  9538. return this.gs.forEachWhile((function(t) {
  9539. var e = t.key.path;
  9540. return !!n.isPrefixOf(e) && (
  9541. // Rows with document keys more than one segment longer than the query
  9542. // path can't be matches. For example, a query on 'rooms' can't match
  9543. // the document /rooms/abc/messages/xyx.
  9544. // TODO(mcg): we'll need a different scanner when we implement
  9545. // ancestor queries.
  9546. e.length === r && (u = u.add(t._s)), !0);
  9547. }), o), xt.resolve(this.Is(u));
  9548. }, t.prototype.Is = function(t) {
  9549. var e = this, n = [];
  9550. // Construct an array of matching batches, sorted by batchID to ensure that
  9551. // multiple mutations affecting the same document key are applied in order.
  9552. return t.forEach((function(t) {
  9553. var r = e.ys(t);
  9554. null !== r && n.push(r);
  9555. })), n;
  9556. }, t.prototype.removeMutationBatch = function(t, e) {
  9557. var n = this;
  9558. U(0 === this.Ts(e.batchId, "removed")), this.mutationQueue.shift();
  9559. var r = this.gs;
  9560. return xt.forEach(e.mutations, (function(i) {
  9561. var o = new Iu(i.key, e.batchId);
  9562. return r = r.delete(o), n.referenceDelegate.markPotentiallyOrphaned(t, i.key);
  9563. })).next((function() {
  9564. n.gs = r;
  9565. }));
  9566. }, t.prototype.An = function(t) {
  9567. // No-op since the memory mutation queue does not maintain a separate cache.
  9568. }, t.prototype.containsKey = function(t, e) {
  9569. var n = new Iu(e, 0), r = this.gs.firstAfterOrEqual(n);
  9570. return xt.resolve(e.isEqual(r && r.key));
  9571. }, t.prototype.performConsistencyCheck = function(t) {
  9572. return this.mutationQueue.length, xt.resolve();
  9573. },
  9574. /**
  9575. * Finds the index of the given batchId in the mutation queue and asserts that
  9576. * the resulting index is within the bounds of the queue.
  9577. *
  9578. * @param batchId - The batchId to search for
  9579. * @param action - A description of what the caller is doing, phrased in passive
  9580. * form (e.g. "acknowledged" in a routine that acknowledges batches).
  9581. */
  9582. t.prototype.Ts = function(t, e) {
  9583. return this.ps(t);
  9584. },
  9585. /**
  9586. * Finds the index of the given batchId in the mutation queue. This operation
  9587. * is O(1).
  9588. *
  9589. * @returns The computed index of the batch with the given batchId, based on
  9590. * the state of the queue. Note this index can be negative if the requested
  9591. * batchId has already been remvoed from the queue or past the end of the
  9592. * queue if the batchId is larger than the last added batch.
  9593. */
  9594. t.prototype.ps = function(t) {
  9595. return 0 === this.mutationQueue.length ? 0 : t - this.mutationQueue[0].batchId;
  9596. // Examine the front of the queue to figure out the difference between the
  9597. // batchId and indexes in the array. Note that since the queue is ordered
  9598. // by batchId, if the first batch has a larger batchId then the requested
  9599. // batchId doesn't exist in the queue.
  9600. },
  9601. /**
  9602. * A version of lookupMutationBatch that doesn't return a promise, this makes
  9603. * other functions that uses this code easier to read and more efficent.
  9604. */
  9605. t.prototype.ys = function(t) {
  9606. var e = this.ps(t);
  9607. return e < 0 || e >= this.mutationQueue.length ? null : this.mutationQueue[e];
  9608. }, t;
  9609. }(), Eu = /** @class */ function() {
  9610. /**
  9611. * @param sizer - Used to assess the size of a document. For eager GC, this is
  9612. * expected to just return 0 to avoid unnecessarily doing the work of
  9613. * calculating the size.
  9614. */
  9615. function t(t) {
  9616. this.Es = t,
  9617. /** Underlying cache of documents and their read times. */
  9618. this.docs = new He(ft.comparator),
  9619. /** Size of all cached documents. */
  9620. this.size = 0;
  9621. }
  9622. return t.prototype.setIndexManager = function(t) {
  9623. this.indexManager = t;
  9624. },
  9625. /**
  9626. * Adds the supplied entry to the cache and updates the cache size as appropriate.
  9627. *
  9628. * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
  9629. * returned by `newChangeBuffer()`.
  9630. */
  9631. t.prototype.addEntry = function(t, e) {
  9632. var n = e.key, r = this.docs.get(n), i = r ? r.size : 0, o = this.Es(e);
  9633. return this.docs = this.docs.insert(n, {
  9634. document: e.mutableCopy(),
  9635. size: o
  9636. }), this.size += o - i, this.indexManager.addToCollectionParentIndex(t, n.path.popLast());
  9637. },
  9638. /**
  9639. * Removes the specified entry from the cache and updates the cache size as appropriate.
  9640. *
  9641. * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
  9642. * returned by `newChangeBuffer()`.
  9643. */
  9644. t.prototype.removeEntry = function(t) {
  9645. var e = this.docs.get(t);
  9646. e && (this.docs = this.docs.remove(t), this.size -= e.size);
  9647. }, t.prototype.getEntry = function(t, e) {
  9648. var n = this.docs.get(e);
  9649. return xt.resolve(n ? n.document.mutableCopy() : rn.newInvalidDocument(e));
  9650. }, t.prototype.getEntries = function(t, e) {
  9651. var n = this, r = vr();
  9652. return e.forEach((function(t) {
  9653. var e = n.docs.get(t);
  9654. r = r.insert(t, e ? e.document.mutableCopy() : rn.newInvalidDocument(t));
  9655. })), xt.resolve(r);
  9656. }, t.prototype.getAllFromCollection = function(t, e, n) {
  9657. for (var r = vr(), i = new ft(e.child("")), o = this.docs.getIteratorFrom(i)
  9658. // Documents are ordered by key, so we can use a prefix scan to narrow down
  9659. // the documents we need to match the query against.
  9660. ; o.hasNext(); ) {
  9661. var u = o.getNext(), a = u.key, s = u.value.document;
  9662. if (!e.isPrefixOf(a.path)) break;
  9663. a.path.length > e.length + 1 || Et(It(s), n) <= 0 || (r = r.insert(s.key, s.mutableCopy()));
  9664. }
  9665. return xt.resolve(r);
  9666. }, t.prototype.getAllFromCollectionGroup = function(t, e, n, r) {
  9667. // This method should only be called from the IndexBackfiller if persistence
  9668. // is enabled.
  9669. q();
  9670. }, t.prototype.As = function(t, e) {
  9671. return xt.forEach(this.docs, (function(t) {
  9672. return e(t);
  9673. }));
  9674. }, t.prototype.newChangeBuffer = function(t) {
  9675. // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps
  9676. // a separate changelog and does not need special handling for removals.
  9677. return new Su(this);
  9678. }, t.prototype.getSize = function(t) {
  9679. return xt.resolve(this.size);
  9680. }, t;
  9681. }(), Su = /** @class */ function(e) {
  9682. function n(t) {
  9683. var n = this;
  9684. return (n = e.call(this) || this).Yn = t, n;
  9685. }
  9686. return t(n, e), n.prototype.applyChanges = function(t) {
  9687. var e = this, n = [];
  9688. return this.changes.forEach((function(r, i) {
  9689. i.isValidDocument() ? n.push(e.Yn.addEntry(t, i)) : e.Yn.removeEntry(r);
  9690. })), xt.waitFor(n);
  9691. }, n.prototype.getFromCache = function(t, e) {
  9692. return this.Yn.getEntry(t, e);
  9693. }, n.prototype.getAllFromCache = function(t, e) {
  9694. return this.Yn.getEntries(t, e);
  9695. }, n;
  9696. }(au), _u = /** @class */ function() {
  9697. function t(t) {
  9698. this.persistence = t,
  9699. /**
  9700. * Maps a target to the data about that target
  9701. */
  9702. this.Rs = new pr((function(t) {
  9703. return an(t);
  9704. }), sn),
  9705. /** The last received snapshot version. */
  9706. this.lastRemoteSnapshotVersion = at.min(),
  9707. /** The highest numbered target ID encountered. */
  9708. this.highestTargetId = 0,
  9709. /** The highest sequence number encountered. */
  9710. this.bs = 0,
  9711. /**
  9712. * A ordered bidirectional mapping between documents and the remote target
  9713. * IDs.
  9714. */
  9715. this.Ps = new bu, this.targetCount = 0, this.vs = Xo.Pn();
  9716. }
  9717. return t.prototype.forEachTarget = function(t, e) {
  9718. return this.Rs.forEach((function(t, n) {
  9719. return e(n);
  9720. })), xt.resolve();
  9721. }, t.prototype.getLastRemoteSnapshotVersion = function(t) {
  9722. return xt.resolve(this.lastRemoteSnapshotVersion);
  9723. }, t.prototype.getHighestSequenceNumber = function(t) {
  9724. return xt.resolve(this.bs);
  9725. }, t.prototype.allocateTargetId = function(t) {
  9726. return this.highestTargetId = this.vs.next(), xt.resolve(this.highestTargetId);
  9727. }, t.prototype.setTargetsMetadata = function(t, e, n) {
  9728. return n && (this.lastRemoteSnapshotVersion = n), e > this.bs && (this.bs = e),
  9729. xt.resolve();
  9730. }, t.prototype.Dn = function(t) {
  9731. this.Rs.set(t.target, t);
  9732. var e = t.targetId;
  9733. e > this.highestTargetId && (this.vs = new Xo(e), this.highestTargetId = e), t.sequenceNumber > this.bs && (this.bs = t.sequenceNumber);
  9734. }, t.prototype.addTargetData = function(t, e) {
  9735. return this.Dn(e), this.targetCount += 1, xt.resolve();
  9736. }, t.prototype.updateTargetData = function(t, e) {
  9737. return this.Dn(e), xt.resolve();
  9738. }, t.prototype.removeTargetData = function(t, e) {
  9739. return this.Rs.delete(e.target), this.Ps.ls(e.targetId), this.targetCount -= 1,
  9740. xt.resolve();
  9741. }, t.prototype.removeTargets = function(t, e, n) {
  9742. var r = this, i = 0, o = [];
  9743. return this.Rs.forEach((function(u, a) {
  9744. a.sequenceNumber <= e && null === n.get(a.targetId) && (r.Rs.delete(u), o.push(r.removeMatchingKeysForTargetId(t, a.targetId)),
  9745. i++);
  9746. })), xt.waitFor(o).next((function() {
  9747. return i;
  9748. }));
  9749. }, t.prototype.getTargetCount = function(t) {
  9750. return xt.resolve(this.targetCount);
  9751. }, t.prototype.getTargetData = function(t, e) {
  9752. var n = this.Rs.get(e) || null;
  9753. return xt.resolve(n);
  9754. }, t.prototype.addMatchingKeys = function(t, e, n) {
  9755. return this.Ps.us(e, n), xt.resolve();
  9756. }, t.prototype.removeMatchingKeys = function(t, e, n) {
  9757. this.Ps.hs(e, n);
  9758. var r = this.persistence.referenceDelegate, i = [];
  9759. return r && e.forEach((function(e) {
  9760. i.push(r.markPotentiallyOrphaned(t, e));
  9761. })), xt.waitFor(i);
  9762. }, t.prototype.removeMatchingKeysForTargetId = function(t, e) {
  9763. return this.Ps.ls(e), xt.resolve();
  9764. }, t.prototype.getMatchingKeysForTargetId = function(t, e) {
  9765. var n = this.Ps.ds(e);
  9766. return xt.resolve(n);
  9767. }, t.prototype.containsKey = function(t, e) {
  9768. return xt.resolve(this.Ps.containsKey(e));
  9769. }, t;
  9770. }(), Du = /** @class */ function() {
  9771. /**
  9772. * The constructor accepts a factory for creating a reference delegate. This
  9773. * allows both the delegate and this instance to have strong references to
  9774. * each other without having nullable fields that would then need to be
  9775. * checked or asserted on every access.
  9776. */
  9777. function t(t, e) {
  9778. var n = this;
  9779. this.Vs = {}, this.overlays = {}, this.Ss = new qt(0), this.Ds = !1, this.Ds = !0,
  9780. this.referenceDelegate = t(this), this.Cs = new _u(this), this.indexManager = new Fo,
  9781. this.remoteDocumentCache = new Eu((function(t) {
  9782. return n.referenceDelegate.xs(t);
  9783. })), this.yt = new Hi(e), this.Ns = new gu(this.yt);
  9784. }
  9785. return t.prototype.start = function() {
  9786. return Promise.resolve();
  9787. }, t.prototype.shutdown = function() {
  9788. // No durable state to ensure is closed on shutdown.
  9789. return this.Ds = !1, Promise.resolve();
  9790. }, Object.defineProperty(t.prototype, "started", {
  9791. get: function() {
  9792. return this.Ds;
  9793. },
  9794. enumerable: !1,
  9795. configurable: !0
  9796. }), t.prototype.setDatabaseDeletedListener = function() {
  9797. // No op.
  9798. }, t.prototype.setNetworkEnabled = function() {
  9799. // No op.
  9800. }, t.prototype.getIndexManager = function(t) {
  9801. // We do not currently support indices for memory persistence, so we can
  9802. // return the same shared instance of the memory index manager.
  9803. return this.indexManager;
  9804. }, t.prototype.getDocumentOverlayCache = function(t) {
  9805. var e = this.overlays[t.toKey()];
  9806. return e || (e = new wu, this.overlays[t.toKey()] = e), e;
  9807. }, t.prototype.getMutationQueue = function(t, e) {
  9808. var n = this.Vs[t.toKey()];
  9809. return n || (n = new Tu(e, this.referenceDelegate), this.Vs[t.toKey()] = n), n;
  9810. }, t.prototype.getTargetCache = function() {
  9811. return this.Cs;
  9812. }, t.prototype.getRemoteDocumentCache = function() {
  9813. return this.remoteDocumentCache;
  9814. }, t.prototype.getBundleCache = function() {
  9815. return this.Ns;
  9816. }, t.prototype.runTransaction = function(t, e, n) {
  9817. var r = this;
  9818. V("MemoryPersistence", "Starting transaction:", t);
  9819. var i = new xu(this.Ss.next());
  9820. return this.referenceDelegate.ks(), n(i).next((function(t) {
  9821. return r.referenceDelegate.Os(i).next((function() {
  9822. return t;
  9823. }));
  9824. })).toPromise().then((function(t) {
  9825. return i.raiseOnCommittedEvent(), t;
  9826. }));
  9827. }, t.prototype.Ms = function(t, e) {
  9828. return xt.or(Object.values(this.Vs).map((function(n) {
  9829. return function() {
  9830. return n.containsKey(t, e);
  9831. };
  9832. })));
  9833. }, t;
  9834. }(), xu = /** @class */ function(e) {
  9835. function n(t) {
  9836. var n = this;
  9837. return (n = e.call(this) || this).currentSequenceNumber = t, n;
  9838. }
  9839. return t(n, e), n;
  9840. }(_t), Au = /** @class */ function() {
  9841. function t(t) {
  9842. this.persistence = t,
  9843. /** Tracks all documents that are active in Query views. */
  9844. this.Fs = new bu,
  9845. /** The list of documents that are potentially GCed after each transaction. */
  9846. this.$s = null;
  9847. }
  9848. return t.Bs = function(e) {
  9849. return new t(e);
  9850. }, Object.defineProperty(t.prototype, "Ls", {
  9851. get: function() {
  9852. if (this.$s) return this.$s;
  9853. throw q();
  9854. },
  9855. enumerable: !1,
  9856. configurable: !0
  9857. }), t.prototype.addReference = function(t, e, n) {
  9858. return this.Fs.addReference(n, e), this.Ls.delete(n.toString()), xt.resolve();
  9859. }, t.prototype.removeReference = function(t, e, n) {
  9860. return this.Fs.removeReference(n, e), this.Ls.add(n.toString()), xt.resolve();
  9861. }, t.prototype.markPotentiallyOrphaned = function(t, e) {
  9862. return this.Ls.add(e.toString()), xt.resolve();
  9863. }, t.prototype.removeTarget = function(t, e) {
  9864. var n = this;
  9865. this.Fs.ls(e.targetId).forEach((function(t) {
  9866. return n.Ls.add(t.toString());
  9867. }));
  9868. var r = this.persistence.getTargetCache();
  9869. return r.getMatchingKeysForTargetId(t, e.targetId).next((function(t) {
  9870. t.forEach((function(t) {
  9871. return n.Ls.add(t.toString());
  9872. }));
  9873. })).next((function() {
  9874. return r.removeTargetData(t, e);
  9875. }));
  9876. }, t.prototype.ks = function() {
  9877. this.$s = new Set;
  9878. }, t.prototype.Os = function(t) {
  9879. var e = this, n = this.persistence.getRemoteDocumentCache().newChangeBuffer();
  9880. // Remove newly orphaned documents.
  9881. return xt.forEach(this.Ls, (function(r) {
  9882. var i = ft.fromPath(r);
  9883. return e.qs(t, i).next((function(t) {
  9884. t || n.removeEntry(i, at.min());
  9885. }));
  9886. })).next((function() {
  9887. return e.$s = null, n.apply(t);
  9888. }));
  9889. }, t.prototype.updateLimboDocument = function(t, e) {
  9890. var n = this;
  9891. return this.qs(t, e).next((function(t) {
  9892. t ? n.Ls.delete(e.toString()) : n.Ls.add(e.toString());
  9893. }));
  9894. }, t.prototype.xs = function(t) {
  9895. // For eager GC, we don't care about the document size, there are no size thresholds.
  9896. return 0;
  9897. }, t.prototype.qs = function(t, e) {
  9898. var n = this;
  9899. return xt.or([ function() {
  9900. return xt.resolve(n.Fs.containsKey(e));
  9901. }, function() {
  9902. return n.persistence.getTargetCache().containsKey(t, e);
  9903. }, function() {
  9904. return n.persistence.Ms(t, e);
  9905. } ]);
  9906. }, t;
  9907. }(), Cu = /** @class */ function() {
  9908. function t(t) {
  9909. this.yt = t;
  9910. }
  9911. /**
  9912. * Performs database creation and schema upgrades.
  9913. *
  9914. * Note that in production, this method is only ever used to upgrade the schema
  9915. * to SCHEMA_VERSION. Different values of toVersion are only used for testing
  9916. * and local feature development.
  9917. */ return t.prototype.$ = function(t, e, n, r) {
  9918. var i = this, o = new At("createOrUpgrade", e);
  9919. n < 1 && r >= 1 && (function(t) {
  9920. t.createObjectStore("owner");
  9921. }(t), function(t) {
  9922. t.createObjectStore("mutationQueues", {
  9923. keyPath: "userId"
  9924. }), t.createObjectStore("mutations", {
  9925. keyPath: "batchId",
  9926. autoIncrement: !0
  9927. }).createIndex("userMutationsIndex", wi, {
  9928. unique: !0
  9929. }), t.createObjectStore("documentMutations");
  9930. }(t), Nu(t), function(t) {
  9931. t.createObjectStore("remoteDocuments");
  9932. }(t));
  9933. // Migration 2 to populate the targetGlobal object no longer needed since
  9934. // migration 3 unconditionally clears it.
  9935. var u = xt.resolve();
  9936. return n < 3 && r >= 3 && (
  9937. // Brand new clients don't need to drop and recreate--only clients that
  9938. // potentially have corrupt data.
  9939. 0 !== n && (function(t) {
  9940. t.deleteObjectStore("targetDocuments"), t.deleteObjectStore("targets"), t.deleteObjectStore("targetGlobal");
  9941. }(t), Nu(t)), u = u.next((function() {
  9942. /**
  9943. * Creates the target global singleton row.
  9944. *
  9945. * @param txn - The version upgrade transaction for indexeddb
  9946. */
  9947. return function(t) {
  9948. var e = t.store("targetGlobal"), n = {
  9949. highestTargetId: 0,
  9950. highestListenSequenceNumber: 0,
  9951. lastRemoteSnapshotVersion: at.min().toTimestamp(),
  9952. targetCount: 0
  9953. };
  9954. return e.put("targetGlobalKey", n);
  9955. }(o);
  9956. }))), n < 4 && r >= 4 && (0 !== n && (
  9957. // Schema version 3 uses auto-generated keys to generate globally unique
  9958. // mutation batch IDs (this was previously ensured internally by the
  9959. // client). To migrate to the new schema, we have to read all mutations
  9960. // and write them back out. We preserve the existing batch IDs to guarantee
  9961. // consistency with other object stores. Any further mutation batch IDs will
  9962. // be auto-generated.
  9963. u = u.next((function() {
  9964. return function(t, e) {
  9965. return e.store("mutations").W().next((function(n) {
  9966. t.deleteObjectStore("mutations"), t.createObjectStore("mutations", {
  9967. keyPath: "batchId",
  9968. autoIncrement: !0
  9969. }).createIndex("userMutationsIndex", wi, {
  9970. unique: !0
  9971. });
  9972. var r = e.store("mutations"), i = n.map((function(t) {
  9973. return r.put(t);
  9974. }));
  9975. return xt.waitFor(i);
  9976. }));
  9977. }(t, o);
  9978. }))), u = u.next((function() {
  9979. !function(t) {
  9980. t.createObjectStore("clientMetadata", {
  9981. keyPath: "clientId"
  9982. });
  9983. }(t);
  9984. }))), n < 5 && r >= 5 && (u = u.next((function() {
  9985. return i.Us(o);
  9986. }))), n < 6 && r >= 6 && (u = u.next((function() {
  9987. return function(t) {
  9988. t.createObjectStore("remoteDocumentGlobal");
  9989. }(t), i.Ks(o);
  9990. }))), n < 7 && r >= 7 && (u = u.next((function() {
  9991. return i.Gs(o);
  9992. }))), n < 8 && r >= 8 && (u = u.next((function() {
  9993. return i.Qs(t, o);
  9994. }))), n < 9 && r >= 9 && (u = u.next((function() {
  9995. // Multi-Tab used to manage its own changelog, but this has been moved
  9996. // to the DbRemoteDocument object store itself. Since the previous change
  9997. // log only contained transient data, we can drop its object store.
  9998. !function(t) {
  9999. t.objectStoreNames.contains("remoteDocumentChanges") && t.deleteObjectStore("remoteDocumentChanges");
  10000. }(t);
  10001. // Note: Schema version 9 used to create a read time index for the
  10002. // RemoteDocumentCache. This is now done with schema version 13.
  10003. }))), n < 10 && r >= 10 && (u = u.next((function() {
  10004. return i.js(o);
  10005. }))), n < 11 && r >= 11 && (u = u.next((function() {
  10006. !function(t) {
  10007. t.createObjectStore("bundles", {
  10008. keyPath: "bundleId"
  10009. });
  10010. }(t), function(t) {
  10011. t.createObjectStore("namedQueries", {
  10012. keyPath: "name"
  10013. });
  10014. }(t);
  10015. }))), n < 12 && r >= 12 && (u = u.next((function() {
  10016. !function(t) {
  10017. var e = t.createObjectStore("documentOverlays", {
  10018. keyPath: Ri
  10019. });
  10020. e.createIndex("collectionPathOverlayIndex", Vi, {
  10021. unique: !1
  10022. }), e.createIndex("collectionGroupOverlayIndex", Mi, {
  10023. unique: !1
  10024. });
  10025. }(t);
  10026. }))), n < 13 && r >= 13 && (u = u.next((function() {
  10027. return function(t) {
  10028. var e = t.createObjectStore("remoteDocumentsV14", {
  10029. keyPath: Ei
  10030. });
  10031. e.createIndex("documentKeyIndex", Si), e.createIndex("collectionGroupIndex", _i);
  10032. }(t);
  10033. })).next((function() {
  10034. return i.Ws(t, o);
  10035. })).next((function() {
  10036. return t.deleteObjectStore("remoteDocuments");
  10037. }))), n < 14 && r >= 14 && (u = u.next((function() {
  10038. return i.zs(t, o);
  10039. }))), n < 15 && r >= 15 && (u = u.next((function() {
  10040. return function(t) {
  10041. t.createObjectStore("indexConfiguration", {
  10042. keyPath: "indexId",
  10043. autoIncrement: !0
  10044. }).createIndex("collectionGroupIndex", "collectionGroup", {
  10045. unique: !1
  10046. }), t.createObjectStore("indexState", {
  10047. keyPath: Ni
  10048. }).createIndex("sequenceNumberIndex", ki, {
  10049. unique: !1
  10050. }), t.createObjectStore("indexEntries", {
  10051. keyPath: Fi
  10052. }).createIndex("documentKeyIndex", Oi, {
  10053. unique: !1
  10054. });
  10055. }(t);
  10056. }))), u;
  10057. }, t.prototype.Ks = function(t) {
  10058. var e = 0;
  10059. return t.store("remoteDocuments").Z((function(t, n) {
  10060. e += jo(n);
  10061. })).next((function() {
  10062. var n = {
  10063. byteSize: e
  10064. };
  10065. return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey", n);
  10066. }));
  10067. }, t.prototype.Us = function(t) {
  10068. var e = this, n = t.store("mutationQueues"), r = t.store("mutations");
  10069. return n.W().next((function(n) {
  10070. return xt.forEach(n, (function(n) {
  10071. var i = IDBKeyRange.bound([ n.userId, -1 ], [ n.userId, n.lastAcknowledgedBatchId ]);
  10072. return r.W("userMutationsIndex", i).next((function(r) {
  10073. return xt.forEach(r, (function(r) {
  10074. U(r.userId === n.userId);
  10075. var i = $i(e.yt, r);
  10076. return Ko(t, n.userId, i).next((function() {}));
  10077. }));
  10078. }));
  10079. }));
  10080. }));
  10081. },
  10082. /**
  10083. * Ensures that every document in the remote document cache has a corresponding sentinel row
  10084. * with a sequence number. Missing rows are given the most recently used sequence number.
  10085. */
  10086. t.prototype.Gs = function(t) {
  10087. var e = t.store("targetDocuments"), n = t.store("remoteDocuments");
  10088. return t.store("targetGlobal").get("targetGlobalKey").next((function(t) {
  10089. var r = [];
  10090. return n.Z((function(n, i) {
  10091. var o = new ct(n), u = function(t) {
  10092. return [ 0, yi(t) ];
  10093. }(o);
  10094. r.push(e.get(u).next((function(n) {
  10095. return n ? xt.resolve() : function(n) {
  10096. return e.put({
  10097. targetId: 0,
  10098. path: yi(n),
  10099. sequenceNumber: t.highestListenSequenceNumber
  10100. });
  10101. }(o);
  10102. })));
  10103. })).next((function() {
  10104. return xt.waitFor(r);
  10105. }));
  10106. }));
  10107. }, t.prototype.Qs = function(t, e) {
  10108. // Create the index.
  10109. t.createObjectStore("collectionParents", {
  10110. keyPath: Ci
  10111. });
  10112. var n = e.store("collectionParents"), r = new Oo, i = function(t) {
  10113. if (r.add(t)) {
  10114. var e = t.lastSegment(), i = t.popLast();
  10115. return n.put({
  10116. collectionId: e,
  10117. parent: yi(i)
  10118. });
  10119. }
  10120. };
  10121. // Helper to add an index entry iff we haven't already written it.
  10122. // Index existing remote documents.
  10123. return e.store("remoteDocuments").Z({
  10124. X: !0
  10125. }, (function(t, e) {
  10126. var n = new ct(t);
  10127. return i(n.popLast());
  10128. })).next((function() {
  10129. return e.store("documentMutations").Z({
  10130. X: !0
  10131. }, (function(t, e) {
  10132. t[0];
  10133. var n = t[1];
  10134. t[2];
  10135. var r = gi(n);
  10136. return i(r.popLast());
  10137. }));
  10138. }));
  10139. }, t.prototype.js = function(t) {
  10140. var e = this, n = t.store("targets");
  10141. return n.Z((function(t, r) {
  10142. var i = to(r), o = eo(e.yt, i);
  10143. return n.put(o);
  10144. }));
  10145. }, t.prototype.Ws = function(t, e) {
  10146. var n = e.store("remoteDocuments"), r = [];
  10147. return n.Z((function(t, n) {
  10148. var i, o = e.store("remoteDocumentsV14"), u = (i = n, i.document ? new ft(ct.fromString(i.document.name).popFirst(5)) : i.noDocument ? ft.fromSegments(i.noDocument.path) : i.unknownDocument ? ft.fromSegments(i.unknownDocument.path) : q()).path.toArray(), a = {
  10149. prefixPath: u.slice(0, u.length - 2),
  10150. collectionGroup: u[u.length - 2],
  10151. documentId: u[u.length - 1],
  10152. readTime: n.readTime || [ 0, 0 ],
  10153. unknownDocument: n.unknownDocument,
  10154. noDocument: n.noDocument,
  10155. document: n.document,
  10156. hasCommittedMutations: !!n.hasCommittedMutations
  10157. };
  10158. r.push(o.put(a));
  10159. })).next((function() {
  10160. return xt.waitFor(r);
  10161. }));
  10162. }, t.prototype.zs = function(t, e) {
  10163. var n = this, r = e.store("mutations"), i = cu(this.yt), o = new Du(Au.Bs, this.yt.ie);
  10164. return r.W().next((function(t) {
  10165. var r = new Map;
  10166. return t.forEach((function(t) {
  10167. var e, i = null !== (e = r.get(t.userId)) && void 0 !== e ? e : _r();
  10168. $i(n.yt, t).keys().forEach((function(t) {
  10169. return i = i.add(t);
  10170. })), r.set(t.userId, i);
  10171. })), xt.forEach(r, (function(t, r) {
  10172. var u = new N(r), a = co.re(n.yt, u), s = o.getIndexManager(u), c = Qo.re(u, n.yt, s, o.referenceDelegate);
  10173. return new mu(i, c, a, s).recalculateAndSaveOverlaysForDocumentKeys(new Gi(e, qt.at), t).next();
  10174. }));
  10175. }));
  10176. }, t;
  10177. }();
  10178. /**
  10179. * @license
  10180. * Copyright 2017 Google LLC
  10181. *
  10182. * Licensed under the Apache License, Version 2.0 (the "License");
  10183. * you may not use this file except in compliance with the License.
  10184. * You may obtain a copy of the License at
  10185. *
  10186. * http://www.apache.org/licenses/LICENSE-2.0
  10187. *
  10188. * Unless required by applicable law or agreed to in writing, software
  10189. * distributed under the License is distributed on an "AS IS" BASIS,
  10190. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10191. * See the License for the specific language governing permissions and
  10192. * limitations under the License.
  10193. */
  10194. /**
  10195. * A readonly view of the local state of all documents we're tracking (i.e. we
  10196. * have a cached version in remoteDocumentCache or local mutations for the
  10197. * document). The view is computed by applying the mutations in the
  10198. * MutationQueue to the RemoteDocumentCache.
  10199. */ function Nu(t) {
  10200. t.createObjectStore("targetDocuments", {
  10201. keyPath: xi
  10202. }).createIndex("documentTargetsIndex", Ai, {
  10203. unique: !0
  10204. }),
  10205. // NOTE: This is unique only because the TargetId is the suffix.
  10206. t.createObjectStore("targets", {
  10207. keyPath: "targetId"
  10208. }).createIndex("queryTargetsIndex", Di, {
  10209. unique: !0
  10210. }), t.createObjectStore("targetGlobal");
  10211. }
  10212. var ku = "Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.", Fu = /** @class */ function() {
  10213. function t(
  10214. /**
  10215. * Whether to synchronize the in-memory state of multiple tabs and share
  10216. * access to local persistence.
  10217. */
  10218. e, n, r, i, o, u, a, s, c,
  10219. /**
  10220. * If set to true, forcefully obtains database access. Existing tabs will
  10221. * no longer be able to access IndexedDB.
  10222. */
  10223. l, h) {
  10224. if (void 0 === h && (h = 15), this.allowTabSynchronization = e, this.persistenceKey = n,
  10225. this.clientId = r, this.Hs = o, this.window = u, this.document = a, this.Js = c,
  10226. this.Ys = l, this.Xs = h, this.Ss = null, this.Ds = !1, this.isPrimary = !1, this.networkEnabled = !0,
  10227. /** Our window.unload handler, if registered. */
  10228. this.Zs = null, this.inForeground = !1,
  10229. /** Our 'visibilitychange' listener if registered. */
  10230. this.ti = null,
  10231. /** The client metadata refresh task. */
  10232. this.ei = null,
  10233. /** The last time we garbage collected the client metadata object store. */
  10234. this.ni = Number.NEGATIVE_INFINITY,
  10235. /** A listener to notify on primary state changes. */
  10236. this.si = function(t) {
  10237. return Promise.resolve();
  10238. }, !t.C()) throw new j(K.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");
  10239. this.referenceDelegate = new ou(this, i), this.ii = n + "main", this.yt = new Hi(s),
  10240. this.ri = new Ct(this.ii, this.Xs, new Cu(this.yt)), this.Cs = new Zo(this.referenceDelegate, this.yt),
  10241. this.remoteDocumentCache = cu(this.yt), this.Ns = new uo, this.window && this.window.localStorage ? this.oi = this.window.localStorage : (this.oi = null,
  10242. !1 === l && M("IndexedDbPersistence", "LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."));
  10243. }
  10244. /**
  10245. * Attempt to start IndexedDb persistence.
  10246. *
  10247. * @returns Whether persistence was enabled.
  10248. */ return t.prototype.start = function() {
  10249. var t = this;
  10250. // NOTE: This is expected to fail sometimes (in the case of another tab
  10251. // already having the persistence lock), so it's the first thing we should
  10252. // do.
  10253. return this.ui().then((function() {
  10254. if (!t.isPrimary && !t.allowTabSynchronization)
  10255. // Fail `start()` if `synchronizeTabs` is disabled and we cannot
  10256. // obtain the primary lease.
  10257. throw new j(K.FAILED_PRECONDITION, ku);
  10258. return t.ci(), t.ai(), t.hi(), t.runTransaction("getHighestListenSequenceNumber", "readonly", (function(e) {
  10259. return t.Cs.getHighestSequenceNumber(e);
  10260. }));
  10261. })).then((function(e) {
  10262. t.Ss = new qt(e, t.Js);
  10263. })).then((function() {
  10264. t.Ds = !0;
  10265. })).catch((function(e) {
  10266. return t.ri && t.ri.close(), Promise.reject(e);
  10267. }));
  10268. },
  10269. /**
  10270. * Registers a listener that gets called when the primary state of the
  10271. * instance changes. Upon registering, this listener is invoked immediately
  10272. * with the current primary state.
  10273. *
  10274. * PORTING NOTE: This is only used for Web multi-tab.
  10275. */
  10276. t.prototype.li = function(t) {
  10277. var r = this;
  10278. return this.si = function(i) {
  10279. return e(r, void 0, void 0, (function() {
  10280. return n(this, (function(e) {
  10281. return this.started ? [ 2 /*return*/ , t(i) ] : [ 2 /*return*/ ];
  10282. }));
  10283. }));
  10284. }, t(this.isPrimary);
  10285. },
  10286. /**
  10287. * Registers a listener that gets called when the database receives a
  10288. * version change event indicating that it has deleted.
  10289. *
  10290. * PORTING NOTE: This is only used for Web multi-tab.
  10291. */
  10292. t.prototype.setDatabaseDeletedListener = function(t) {
  10293. var r = this;
  10294. this.ri.L((function(i) {
  10295. return e(r, void 0, void 0, (function() {
  10296. return n(this, (function(e) {
  10297. switch (e.label) {
  10298. case 0:
  10299. return null === i.newVersion ? [ 4 /*yield*/ , t() ] : [ 3 /*break*/ , 2 ];
  10300. case 1:
  10301. e.sent(), e.label = 2;
  10302. case 2:
  10303. return [ 2 /*return*/ ];
  10304. }
  10305. }));
  10306. }));
  10307. }));
  10308. },
  10309. /**
  10310. * Adjusts the current network state in the client's metadata, potentially
  10311. * affecting the primary lease.
  10312. *
  10313. * PORTING NOTE: This is only used for Web multi-tab.
  10314. */
  10315. t.prototype.setNetworkEnabled = function(t) {
  10316. var r = this;
  10317. this.networkEnabled !== t && (this.networkEnabled = t,
  10318. // Schedule a primary lease refresh for immediate execution. The eventual
  10319. // lease update will be propagated via `primaryStateListener`.
  10320. this.Hs.enqueueAndForget((function() {
  10321. return e(r, void 0, void 0, (function() {
  10322. return n(this, (function(t) {
  10323. switch (t.label) {
  10324. case 0:
  10325. return this.started ? [ 4 /*yield*/ , this.ui() ] : [ 3 /*break*/ , 2 ];
  10326. case 1:
  10327. t.sent(), t.label = 2;
  10328. case 2:
  10329. return [ 2 /*return*/ ];
  10330. }
  10331. }));
  10332. }));
  10333. })));
  10334. },
  10335. /**
  10336. * Updates the client metadata in IndexedDb and attempts to either obtain or
  10337. * extend the primary lease for the local client. Asynchronously notifies the
  10338. * primary state listener if the client either newly obtained or released its
  10339. * primary lease.
  10340. */
  10341. t.prototype.ui = function() {
  10342. var t = this;
  10343. return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", (function(e) {
  10344. return Ru(e).put({
  10345. clientId: t.clientId,
  10346. updateTimeMs: Date.now(),
  10347. networkEnabled: t.networkEnabled,
  10348. inForeground: t.inForeground
  10349. }).next((function() {
  10350. if (t.isPrimary) return t.fi(e).next((function(e) {
  10351. e || (t.isPrimary = !1, t.Hs.enqueueRetryable((function() {
  10352. return t.si(!1);
  10353. })));
  10354. }));
  10355. })).next((function() {
  10356. return t.di(e);
  10357. })).next((function(n) {
  10358. return t.isPrimary && !n ? t._i(e).next((function() {
  10359. return !1;
  10360. })) : !!n && t.wi(e).next((function() {
  10361. return !0;
  10362. }));
  10363. }));
  10364. })).catch((function(e) {
  10365. if (Ft(e))
  10366. // Proceed with the existing state. Any subsequent access to
  10367. // IndexedDB will verify the lease.
  10368. return V("IndexedDbPersistence", "Failed to extend owner lease: ", e), t.isPrimary;
  10369. if (!t.allowTabSynchronization) throw e;
  10370. return V("IndexedDbPersistence", "Releasing owner lease after error during lease refresh", e),
  10371. /* isPrimary= */ !1;
  10372. })).then((function(e) {
  10373. t.isPrimary !== e && t.Hs.enqueueRetryable((function() {
  10374. return t.si(e);
  10375. })), t.isPrimary = e;
  10376. }));
  10377. }, t.prototype.fi = function(t) {
  10378. var e = this;
  10379. return Ou(t).get("owner").next((function(t) {
  10380. return xt.resolve(e.mi(t));
  10381. }));
  10382. }, t.prototype.gi = function(t) {
  10383. return Ru(t).delete(this.clientId);
  10384. },
  10385. /**
  10386. * If the garbage collection threshold has passed, prunes the
  10387. * RemoteDocumentChanges and the ClientMetadata store based on the last update
  10388. * time of all clients.
  10389. */
  10390. t.prototype.yi = function() {
  10391. return e(this, void 0, void 0, (function() {
  10392. var t, e, r, i, o = this;
  10393. return n(this, (function(n) {
  10394. switch (n.label) {
  10395. case 0:
  10396. return !this.isPrimary || this.pi(this.ni, 18e5) ? [ 3 /*break*/ , 2 ] : (this.ni = Date.now(),
  10397. [ 4 /*yield*/ , this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", (function(t) {
  10398. var e = Ki(t, "clientMetadata");
  10399. return e.W().next((function(t) {
  10400. var n = o.Ii(t, 18e5), r = t.filter((function(t) {
  10401. return -1 === n.indexOf(t);
  10402. }));
  10403. // Delete metadata for clients that are no longer considered active.
  10404. return xt.forEach(r, (function(t) {
  10405. return e.delete(t.clientId);
  10406. })).next((function() {
  10407. return r;
  10408. }));
  10409. }));
  10410. })).catch((function() {
  10411. return [];
  10412. })) ]);
  10413. case 1:
  10414. // Delete potential leftover entries that may continue to mark the
  10415. // inactive clients as zombied in LocalStorage.
  10416. // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for
  10417. // the client atomically, but we can't. So we opt to delete the IndexedDb
  10418. // entries first to avoid potentially reviving a zombied client.
  10419. if (t = n.sent(), this.oi) for (e = 0, r = t; e < r.length; e++) i = r[e], this.oi.removeItem(this.Ti(i.clientId));
  10420. n.label = 2;
  10421. case 2:
  10422. return [ 2 /*return*/ ];
  10423. }
  10424. }));
  10425. }));
  10426. },
  10427. /**
  10428. * Schedules a recurring timer to update the client metadata and to either
  10429. * extend or acquire the primary lease if the client is eligible.
  10430. */
  10431. t.prototype.hi = function() {
  10432. var t = this;
  10433. this.ei = this.Hs.enqueueAfterDelay("client_metadata_refresh" /* TimerId.ClientMetadataRefresh */ , 4e3, (function() {
  10434. return t.ui().then((function() {
  10435. return t.yi();
  10436. })).then((function() {
  10437. return t.hi();
  10438. }));
  10439. }));
  10440. },
  10441. /** Checks whether `client` is the local client. */ t.prototype.mi = function(t) {
  10442. return !!t && t.ownerId === this.clientId;
  10443. },
  10444. /**
  10445. * Evaluate the state of all active clients and determine whether the local
  10446. * client is or can act as the holder of the primary lease. Returns whether
  10447. * the client is eligible for the lease, but does not actually acquire it.
  10448. * May return 'false' even if there is no active leaseholder and another
  10449. * (foreground) client should become leaseholder instead.
  10450. */
  10451. t.prototype.di = function(t) {
  10452. var e = this;
  10453. return this.Ys ? xt.resolve(!0) : Ou(t).get("owner").next((function(n) {
  10454. // A client is eligible for the primary lease if:
  10455. // - its network is enabled and the client's tab is in the foreground.
  10456. // - its network is enabled and no other client's tab is in the
  10457. // foreground.
  10458. // - every clients network is disabled and the client's tab is in the
  10459. // foreground.
  10460. // - every clients network is disabled and no other client's tab is in
  10461. // the foreground.
  10462. // - the `forceOwningTab` setting was passed in.
  10463. if (null !== n && e.pi(n.leaseTimestampMs, 5e3) && !e.Ei(n.ownerId)) {
  10464. if (e.mi(n) && e.networkEnabled) return !0;
  10465. if (!e.mi(n)) {
  10466. if (!n.allowTabSynchronization)
  10467. // Fail the `canActAsPrimary` check if the current leaseholder has
  10468. // not opted into multi-tab synchronization. If this happens at
  10469. // client startup, we reject the Promise returned by
  10470. // `enablePersistence()` and the user can continue to use Firestore
  10471. // with in-memory persistence.
  10472. // If this fails during a lease refresh, we will instead block the
  10473. // AsyncQueue from executing further operations. Note that this is
  10474. // acceptable since mixing & matching different `synchronizeTabs`
  10475. // settings is not supported.
  10476. // TODO(b/114226234): Remove this check when `synchronizeTabs` can
  10477. // no longer be turned off.
  10478. throw new j(K.FAILED_PRECONDITION, ku);
  10479. return !1;
  10480. }
  10481. }
  10482. return !(!e.networkEnabled || !e.inForeground) || Ru(t).W().next((function(t) {
  10483. return void 0 === e.Ii(t, 5e3).find((function(t) {
  10484. if (e.clientId !== t.clientId) {
  10485. var n = !e.networkEnabled && t.networkEnabled, r = !e.inForeground && t.inForeground, i = e.networkEnabled === t.networkEnabled;
  10486. if (n || r && i) return !0;
  10487. }
  10488. return !1;
  10489. }));
  10490. }));
  10491. })).next((function(t) {
  10492. return e.isPrimary !== t && V("IndexedDbPersistence", "Client ".concat(t ? "is" : "is not", " eligible for a primary lease.")),
  10493. t;
  10494. }));
  10495. }, t.prototype.shutdown = function() {
  10496. return e(this, void 0, void 0, (function() {
  10497. var t = this;
  10498. return n(this, (function(e) {
  10499. switch (e.label) {
  10500. case 0:
  10501. // Use `SimpleDb.runTransaction` directly to avoid failing if another tab
  10502. // has obtained the primary lease.
  10503. // The shutdown() operations are idempotent and can be called even when
  10504. // start() aborted (e.g. because it couldn't acquire the persistence lease).
  10505. return this.Ds = !1, this.Ai(), this.ei && (this.ei.cancel(), this.ei = null), this.Ri(),
  10506. this.bi(), [ 4 /*yield*/ , this.ri.runTransaction("shutdown", "readwrite", [ "owner", "clientMetadata" ], (function(e) {
  10507. var n = new Gi(e, qt.at);
  10508. return t._i(n).next((function() {
  10509. return t.gi(n);
  10510. }));
  10511. })) ];
  10512. case 1:
  10513. // The shutdown() operations are idempotent and can be called even when
  10514. // start() aborted (e.g. because it couldn't acquire the persistence lease).
  10515. // Use `SimpleDb.runTransaction` directly to avoid failing if another tab
  10516. // has obtained the primary lease.
  10517. return e.sent(), this.ri.close(),
  10518. // Remove the entry marking the client as zombied from LocalStorage since
  10519. // we successfully deleted its metadata from IndexedDb.
  10520. this.Pi(), [ 2 /*return*/ ];
  10521. }
  10522. }));
  10523. }));
  10524. },
  10525. /**
  10526. * Returns clients that are not zombied and have an updateTime within the
  10527. * provided threshold.
  10528. */
  10529. t.prototype.Ii = function(t, e) {
  10530. var n = this;
  10531. return t.filter((function(t) {
  10532. return n.pi(t.updateTimeMs, e) && !n.Ei(t.clientId);
  10533. }));
  10534. },
  10535. /**
  10536. * Returns the IDs of the clients that are currently active. If multi-tab
  10537. * is not supported, returns an array that only contains the local client's
  10538. * ID.
  10539. *
  10540. * PORTING NOTE: This is only used for Web multi-tab.
  10541. */
  10542. t.prototype.vi = function() {
  10543. var t = this;
  10544. return this.runTransaction("getActiveClients", "readonly", (function(e) {
  10545. return Ru(e).W().next((function(e) {
  10546. return t.Ii(e, 18e5).map((function(t) {
  10547. return t.clientId;
  10548. }));
  10549. }));
  10550. }));
  10551. }, Object.defineProperty(t.prototype, "started", {
  10552. get: function() {
  10553. return this.Ds;
  10554. },
  10555. enumerable: !1,
  10556. configurable: !0
  10557. }), t.prototype.getMutationQueue = function(t, e) {
  10558. return Qo.re(t, this.yt, e, this.referenceDelegate);
  10559. }, t.prototype.getTargetCache = function() {
  10560. return this.Cs;
  10561. }, t.prototype.getRemoteDocumentCache = function() {
  10562. return this.remoteDocumentCache;
  10563. }, t.prototype.getIndexManager = function(t) {
  10564. return new Vo(t, this.yt.ie.databaseId);
  10565. }, t.prototype.getDocumentOverlayCache = function(t) {
  10566. return co.re(this.yt, t);
  10567. }, t.prototype.getBundleCache = function() {
  10568. return this.Ns;
  10569. }, t.prototype.runTransaction = function(t, e, n) {
  10570. var r = this;
  10571. V("IndexedDbPersistence", "Starting transaction:", t);
  10572. var i, o, u = "readonly" === e ? "readonly" : "readwrite", a = 15 === (i = this.Xs) ? Bi : 14 === i ? Ui : 13 === i ? qi : 12 === i ? Pi : 11 === i ? Li : void q();
  10573. /** Returns the object stores for the provided schema. */
  10574. // Do all transactions as readwrite against all object stores, since we
  10575. // are the only reader/writer.
  10576. return this.ri.runTransaction(t, u, a, (function(i) {
  10577. return o = new Gi(i, r.Ss ? r.Ss.next() : qt.at), "readwrite-primary" === e ? r.fi(o).next((function(t) {
  10578. return !!t || r.di(o);
  10579. })).next((function(e) {
  10580. if (!e) throw M("Failed to obtain primary lease for action '".concat(t, "'.")),
  10581. r.isPrimary = !1, r.Hs.enqueueRetryable((function() {
  10582. return r.si(!1);
  10583. })), new j(K.FAILED_PRECONDITION, St);
  10584. return n(o);
  10585. })).next((function(t) {
  10586. return r.wi(o).next((function() {
  10587. return t;
  10588. }));
  10589. })) : r.Vi(o).next((function() {
  10590. return n(o);
  10591. }));
  10592. })).then((function(t) {
  10593. return o.raiseOnCommittedEvent(), t;
  10594. }));
  10595. },
  10596. /**
  10597. * Verifies that the current tab is the primary leaseholder or alternatively
  10598. * that the leaseholder has opted into multi-tab synchronization.
  10599. */
  10600. // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer
  10601. // be turned off.
  10602. t.prototype.Vi = function(t) {
  10603. var e = this;
  10604. return Ou(t).get("owner").next((function(t) {
  10605. if (null !== t && e.pi(t.leaseTimestampMs, 5e3) && !e.Ei(t.ownerId) && !e.mi(t) && !(e.Ys || e.allowTabSynchronization && t.allowTabSynchronization)) throw new j(K.FAILED_PRECONDITION, ku);
  10606. }));
  10607. },
  10608. /**
  10609. * Obtains or extends the new primary lease for the local client. This
  10610. * method does not verify that the client is eligible for this lease.
  10611. */
  10612. t.prototype.wi = function(t) {
  10613. var e = {
  10614. ownerId: this.clientId,
  10615. allowTabSynchronization: this.allowTabSynchronization,
  10616. leaseTimestampMs: Date.now()
  10617. };
  10618. return Ou(t).put("owner", e);
  10619. }, t.C = function() {
  10620. return Ct.C();
  10621. },
  10622. /** Checks the primary lease and removes it if we are the current primary. */ t.prototype._i = function(t) {
  10623. var e = this, n = Ou(t);
  10624. return n.get("owner").next((function(t) {
  10625. return e.mi(t) ? (V("IndexedDbPersistence", "Releasing primary lease."), n.delete("owner")) : xt.resolve();
  10626. }));
  10627. },
  10628. /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ t.prototype.pi = function(t, e) {
  10629. var n = Date.now();
  10630. return !(t < n - e || t > n && (M("Detected an update time that is in the future: ".concat(t, " > ").concat(n)),
  10631. 1));
  10632. }, t.prototype.ci = function() {
  10633. var t = this;
  10634. null !== this.document && "function" == typeof this.document.addEventListener && (this.ti = function() {
  10635. t.Hs.enqueueAndForget((function() {
  10636. return t.inForeground = "visible" === t.document.visibilityState, t.ui();
  10637. }));
  10638. }, this.document.addEventListener("visibilitychange", this.ti), this.inForeground = "visible" === this.document.visibilityState);
  10639. }, t.prototype.Ri = function() {
  10640. this.ti && (this.document.removeEventListener("visibilitychange", this.ti), this.ti = null);
  10641. },
  10642. /**
  10643. * Attaches a window.unload handler that will synchronously write our
  10644. * clientId to a "zombie client id" location in LocalStorage. This can be used
  10645. * by tabs trying to acquire the primary lease to determine that the lease
  10646. * is no longer valid even if the timestamp is recent. This is particularly
  10647. * important for the refresh case (so the tab correctly re-acquires the
  10648. * primary lease). LocalStorage is used for this rather than IndexedDb because
  10649. * it is a synchronous API and so can be used reliably from an unload
  10650. * handler.
  10651. */
  10652. t.prototype.ai = function() {
  10653. var t, e = this;
  10654. "function" == typeof (null === (t = this.window) || void 0 === t ? void 0 : t.addEventListener) && (this.Zs = function() {
  10655. // Note: In theory, this should be scheduled on the AsyncQueue since it
  10656. // accesses internal state. We execute this code directly during shutdown
  10657. // to make sure it gets a chance to run.
  10658. e.Ai(), p() && navigator.appVersion.match(/Version\/1[45]/) &&
  10659. // On Safari 14 and 15, we do not run any cleanup actions as it might
  10660. // trigger a bug that prevents Safari from re-opening IndexedDB during
  10661. // the next page load.
  10662. // See https://bugs.webkit.org/show_bug.cgi?id=226547
  10663. e.Hs.enterRestrictedMode(/* purgeExistingTasks= */ !0), e.Hs.enqueueAndForget((function() {
  10664. return e.shutdown();
  10665. }));
  10666. }, this.window.addEventListener("pagehide", this.Zs));
  10667. }, t.prototype.bi = function() {
  10668. this.Zs && (this.window.removeEventListener("pagehide", this.Zs), this.Zs = null);
  10669. },
  10670. /**
  10671. * Returns whether a client is "zombied" based on its LocalStorage entry.
  10672. * Clients become zombied when their tab closes without running all of the
  10673. * cleanup logic in `shutdown()`.
  10674. */
  10675. t.prototype.Ei = function(t) {
  10676. var e;
  10677. try {
  10678. var n = null !== (null === (e = this.oi) || void 0 === e ? void 0 : e.getItem(this.Ti(t)));
  10679. return V("IndexedDbPersistence", "Client '".concat(t, "' ").concat(n ? "is" : "is not", " zombied in LocalStorage")),
  10680. n;
  10681. } catch (t) {
  10682. // Gracefully handle if LocalStorage isn't working.
  10683. return M("IndexedDbPersistence", "Failed to get zombied client id.", t), !1;
  10684. }
  10685. },
  10686. /**
  10687. * Record client as zombied (a client that had its tab closed). Zombied
  10688. * clients are ignored during primary tab selection.
  10689. */
  10690. t.prototype.Ai = function() {
  10691. if (this.oi) try {
  10692. this.oi.setItem(this.Ti(this.clientId), String(Date.now()));
  10693. } catch (t) {
  10694. // Gracefully handle if LocalStorage isn't available / working.
  10695. M("Failed to set zombie client id.", t);
  10696. }
  10697. },
  10698. /** Removes the zombied client entry if it exists. */ t.prototype.Pi = function() {
  10699. if (this.oi) try {
  10700. this.oi.removeItem(this.Ti(this.clientId));
  10701. } catch (t) {
  10702. // Ignore
  10703. }
  10704. }, t.prototype.Ti = function(t) {
  10705. return "firestore_zombie_".concat(this.persistenceKey, "_").concat(t);
  10706. }, t;
  10707. }();
  10708. /**
  10709. * Oldest acceptable age in milliseconds for client metadata before the client
  10710. * is considered inactive and its associated data is garbage collected.
  10711. */
  10712. /**
  10713. * An IndexedDB-backed instance of Persistence. Data is stored persistently
  10714. * across sessions.
  10715. *
  10716. * On Web only, the Firestore SDKs support shared access to its persistence
  10717. * layer. This allows multiple browser tabs to read and write to IndexedDb and
  10718. * to synchronize state even without network connectivity. Shared access is
  10719. * currently optional and not enabled unless all clients invoke
  10720. * `enablePersistence()` with `{synchronizeTabs:true}`.
  10721. *
  10722. * In multi-tab mode, if multiple clients are active at the same time, the SDK
  10723. * will designate one client as the primary client. An effort is made to pick
  10724. * a visible, network-connected and active client, and this client is
  10725. * responsible for letting other clients know about its presence. The primary
  10726. * client writes a unique client-generated identifier (the client ID) to
  10727. * IndexedDbs owner store every 4 seconds. If the primary client fails to
  10728. * update this entry, another client can acquire the lease and take over as
  10729. * primary.
  10730. *
  10731. * Some persistence operations in the SDK are designated as primary-client only
  10732. * operations. This includes the acknowledgment of mutations and all updates of
  10733. * remote documents. The effects of these operations are written to persistence
  10734. * and then broadcast to other tabs via LocalStorage (see
  10735. * `WebStorageSharedClientState`), which then refresh their state from
  10736. * persistence.
  10737. *
  10738. * Similarly, the primary client listens to notifications sent by secondary
  10739. * clients to discover persistence changes written by secondary clients, such as
  10740. * the addition of new mutations and query targets.
  10741. *
  10742. * If multi-tab is not enabled and another tab already obtained the primary
  10743. * lease, IndexedDbPersistence enters a failed state and all subsequent
  10744. * operations will automatically fail.
  10745. *
  10746. * Additionally, there is an optimization so that when a tab is closed, the
  10747. * primary lease is released immediately (this is especially important to make
  10748. * sure that a refreshed tab is able to immediately re-acquire the primary
  10749. * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload
  10750. * since it is an asynchronous API. So in addition to attempting to give up the
  10751. * lease, the leaseholder writes its client ID to a "zombiedClient" entry in
  10752. * LocalStorage which acts as an indicator that another tab should go ahead and
  10753. * take the primary lease immediately regardless of the current lease timestamp.
  10754. *
  10755. * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no
  10756. * longer optional.
  10757. */
  10758. /**
  10759. * Helper to get a typed SimpleDbStore for the primary client object store.
  10760. */
  10761. function Ou(t) {
  10762. return Ki(t, "owner");
  10763. }
  10764. /**
  10765. * Helper to get a typed SimpleDbStore for the client metadata object store.
  10766. */ function Ru(t) {
  10767. return Ki(t, "clientMetadata");
  10768. }
  10769. /**
  10770. * Generates a string used as a prefix when storing data in IndexedDB and
  10771. * LocalStorage.
  10772. */ function Vu(t, e) {
  10773. // Use two different prefix formats:
  10774. // * firestore / persistenceKey / projectID . databaseID / ...
  10775. // * firestore / persistenceKey / projectID / ...
  10776. // projectIDs are DNS-compatible names and cannot contain dots
  10777. // so there's no danger of collisions.
  10778. var n = t.projectId;
  10779. return t.isDefaultDatabase || (n += "." + t.database), "firestore/" + e + "/" + n + "/"
  10780. /**
  10781. * @license
  10782. * Copyright 2017 Google LLC
  10783. *
  10784. * Licensed under the Apache License, Version 2.0 (the "License");
  10785. * you may not use this file except in compliance with the License.
  10786. * You may obtain a copy of the License at
  10787. *
  10788. * http://www.apache.org/licenses/LICENSE-2.0
  10789. *
  10790. * Unless required by applicable law or agreed to in writing, software
  10791. * distributed under the License is distributed on an "AS IS" BASIS,
  10792. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10793. * See the License for the specific language governing permissions and
  10794. * limitations under the License.
  10795. */
  10796. /**
  10797. * A set of changes to what documents are currently in view and out of view for
  10798. * a given query. These changes are sent to the LocalStore by the View (via
  10799. * the SyncEngine) and are used to pin / unpin documents as appropriate.
  10800. */;
  10801. }
  10802. var Mu = /** @class */ function() {
  10803. function t(t, e, n, r) {
  10804. this.targetId = t, this.fromCache = e, this.Si = n, this.Di = r;
  10805. }
  10806. return t.Ci = function(e, n) {
  10807. for (var r = _r(), i = _r(), o = 0, u = n.docChanges; o < u.length; o++) {
  10808. var a = u[o];
  10809. switch (a.type) {
  10810. case 0 /* ChangeType.Added */ :
  10811. r = r.add(a.doc.key);
  10812. break;
  10813. case 1 /* ChangeType.Removed */ :
  10814. i = i.add(a.doc.key);
  10815. // do nothing
  10816. }
  10817. }
  10818. return new t(e, n.fromCache, r, i);
  10819. }, t;
  10820. }(), Lu = /** @class */ function() {
  10821. function t() {
  10822. this.xi = !1;
  10823. }
  10824. /** Sets the document view to query against. */ return t.prototype.initialize = function(t, e) {
  10825. this.Ni = t, this.indexManager = e, this.xi = !0;
  10826. },
  10827. /** Returns all local documents matching the specified query. */ t.prototype.getDocumentsMatchingQuery = function(t, e, n, r) {
  10828. var i = this;
  10829. return this.ki(t, e).next((function(o) {
  10830. return o || i.Oi(t, e, r, n);
  10831. })).next((function(n) {
  10832. return n || i.Mi(t, e);
  10833. }));
  10834. },
  10835. /**
  10836. * Performs an indexed query that evaluates the query based on a collection's
  10837. * persisted index values. Returns `null` if an index is not available.
  10838. */
  10839. t.prototype.ki = function(t, e) {
  10840. var n = this;
  10841. if (vn(e))
  10842. // Queries that match all documents don't benefit from using
  10843. // key-based lookups. It is more efficient to scan all documents in a
  10844. // collection, rather than to perform individual lookups.
  10845. return xt.resolve(null);
  10846. var r = In(e);
  10847. return this.indexManager.getIndexType(t, r).next((function(i) {
  10848. return 0 /* IndexType.NONE */ === i ? null : (null !== e.limit && 1 /* IndexType.PARTIAL */ === i && (
  10849. // We cannot apply a limit for targets that are served using a partial
  10850. // index. If a partial index will be used to serve the target, the
  10851. // query may return a superset of documents that match the target
  10852. // (e.g. if the index doesn't include all the target's filters), or
  10853. // may return the correct set of documents in the wrong order (e.g. if
  10854. // the index doesn't include a segment for one of the orderBys).
  10855. // Therefore, a limit should not be applied in such cases.
  10856. e = En(e, null, "F" /* LimitType.First */), r = In(e)), n.indexManager.getDocumentsMatchingTarget(t, r).next((function(i) {
  10857. var o = _r.apply(void 0, i);
  10858. return n.Ni.getDocuments(t, o).next((function(i) {
  10859. return n.indexManager.getMinOffset(t, r).next((function(r) {
  10860. var u = n.Fi(e, i);
  10861. return n.$i(e, u, o, r.readTime) ? n.ki(t, En(e, null, "F" /* LimitType.First */)) : n.Bi(t, u, e, r);
  10862. }));
  10863. }));
  10864. })));
  10865. }));
  10866. },
  10867. /**
  10868. * Performs a query based on the target's persisted query mapping. Returns
  10869. * `null` if the mapping is not available or cannot be used.
  10870. */
  10871. t.prototype.Oi = function(t, e, n, r) {
  10872. var i = this;
  10873. return vn(e) || r.isEqual(at.min()) ? this.Mi(t, e) : this.Ni.getDocuments(t, n).next((function(o) {
  10874. var u = i.Fi(e, o);
  10875. return i.$i(e, u, n, r) ? i.Mi(t, e) : (O() <= h.DEBUG && V("QueryEngine", "Re-using previous result from %s to execute query: %s", r.toString(), Dn(e)),
  10876. i.Bi(t, u, e, bt(r, -1)));
  10877. }));
  10878. // Queries that have never seen a snapshot without limbo free documents
  10879. // should also be run as a full collection scan.
  10880. },
  10881. /** Applies the query filter and sorting to the provided documents. */ t.prototype.Fi = function(t, e) {
  10882. // Sort the documents and re-apply the query filter since previously
  10883. // matching documents do not necessarily still match the query.
  10884. var n = new Ze(Cn(t));
  10885. return e.forEach((function(e, r) {
  10886. xn(t, r) && (n = n.add(r));
  10887. })), n;
  10888. },
  10889. /**
  10890. * Determines if a limit query needs to be refilled from cache, making it
  10891. * ineligible for index-free execution.
  10892. *
  10893. * @param query - The query.
  10894. * @param sortedPreviousResults - The documents that matched the query when it
  10895. * was last synchronized, sorted by the query's comparator.
  10896. * @param remoteKeys - The document keys that matched the query at the last
  10897. * snapshot.
  10898. * @param limboFreeSnapshotVersion - The version of the snapshot when the
  10899. * query was last synchronized.
  10900. */
  10901. t.prototype.$i = function(t, e, n, r) {
  10902. if (null === t.limit)
  10903. // Queries without limits do not need to be refilled.
  10904. return !1;
  10905. if (n.size !== e.size)
  10906. // The query needs to be refilled if a previously matching document no
  10907. // longer matches.
  10908. return !0;
  10909. // Limit queries are not eligible for index-free query execution if there is
  10910. // a potential that an older document from cache now sorts before a document
  10911. // that was previously part of the limit. This, however, can only happen if
  10912. // the document at the edge of the limit goes out of limit.
  10913. // If a document that is not the limit boundary sorts differently,
  10914. // the boundary of the limit itself did not change and documents from cache
  10915. // will continue to be "rejected" by this boundary. Therefore, we can ignore
  10916. // any modifications that don't affect the last document.
  10917. var i = "F" /* LimitType.First */ === t.limitType ? e.last() : e.first();
  10918. return !!i && (i.hasPendingWrites || i.version.compareTo(r) > 0);
  10919. }, t.prototype.Mi = function(t, e) {
  10920. return O() <= h.DEBUG && V("QueryEngine", "Using full collection scan to execute query:", Dn(e)),
  10921. this.Ni.getDocumentsMatchingQuery(t, e, Tt.min());
  10922. },
  10923. /**
  10924. * Combines the results from an indexed execution with the remaining documents
  10925. * that have not yet been indexed.
  10926. */
  10927. t.prototype.Bi = function(t, e, n, r) {
  10928. // Retrieve all results for documents that were updated since the offset.
  10929. return this.Ni.getDocumentsMatchingQuery(t, n, r).next((function(t) {
  10930. // Merge with existing results
  10931. return e.forEach((function(e) {
  10932. t = t.insert(e.key, e);
  10933. })), t;
  10934. }));
  10935. }, t;
  10936. }(), Pu = /** @class */ function() {
  10937. function t(
  10938. /** Manages our in-memory or durable persistence. */
  10939. t, e, n, r) {
  10940. this.persistence = t, this.Li = e, this.yt = r,
  10941. /**
  10942. * Maps a targetID to data about its target.
  10943. *
  10944. * PORTING NOTE: We are using an immutable data structure on Web to make re-runs
  10945. * of `applyRemoteEvent()` idempotent.
  10946. */
  10947. this.qi = new He(rt),
  10948. /** Maps a target to its targetID. */
  10949. // TODO(wuandy): Evaluate if TargetId can be part of Target.
  10950. this.Ui = new pr((function(t) {
  10951. return an(t);
  10952. }), sn),
  10953. /**
  10954. * A per collection group index of the last read time processed by
  10955. * `getNewDocumentChanges()`.
  10956. *
  10957. * PORTING NOTE: This is only used for multi-tab synchronization.
  10958. */
  10959. this.Ki = new Map, this.Gi = t.getRemoteDocumentCache(), this.Cs = t.getTargetCache(),
  10960. this.Ns = t.getBundleCache(), this.Qi(n);
  10961. }
  10962. return t.prototype.Qi = function(t) {
  10963. // TODO(indexing): Add spec tests that test these components change after a
  10964. // user change
  10965. this.documentOverlayCache = this.persistence.getDocumentOverlayCache(t), this.indexManager = this.persistence.getIndexManager(t),
  10966. this.mutationQueue = this.persistence.getMutationQueue(t, this.indexManager), this.localDocuments = new mu(this.Gi, this.mutationQueue, this.documentOverlayCache, this.indexManager),
  10967. this.Gi.setIndexManager(this.indexManager), this.Li.initialize(this.localDocuments, this.indexManager);
  10968. }, t.prototype.collectGarbage = function(t) {
  10969. var e = this;
  10970. return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (function(n) {
  10971. return t.collect(n, e.qi);
  10972. }));
  10973. }, t;
  10974. }();
  10975. /**
  10976. * @license
  10977. * Copyright 2019 Google LLC
  10978. *
  10979. * Licensed under the Apache License, Version 2.0 (the "License");
  10980. * you may not use this file except in compliance with the License.
  10981. * You may obtain a copy of the License at
  10982. *
  10983. * http://www.apache.org/licenses/LICENSE-2.0
  10984. *
  10985. * Unless required by applicable law or agreed to in writing, software
  10986. * distributed under the License is distributed on an "AS IS" BASIS,
  10987. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10988. * See the License for the specific language governing permissions and
  10989. * limitations under the License.
  10990. */
  10991. /**
  10992. * The Firestore query engine.
  10993. *
  10994. * Firestore queries can be executed in three modes. The Query Engine determines
  10995. * what mode to use based on what data is persisted. The mode only determines
  10996. * the runtime complexity of the query - the result set is equivalent across all
  10997. * implementations.
  10998. *
  10999. * The Query engine will use indexed-based execution if a user has configured
  11000. * any index that can be used to execute query (via `setIndexConfiguration()`).
  11001. * Otherwise, the engine will try to optimize the query by re-using a previously
  11002. * persisted query result. If that is not possible, the query will be executed
  11003. * via a full collection scan.
  11004. *
  11005. * Index-based execution is the default when available. The query engine
  11006. * supports partial indexed execution and merges the result from the index
  11007. * lookup with documents that have not yet been indexed. The index evaluation
  11008. * matches the backend's format and as such, the SDK can use indexing for all
  11009. * queries that the backend supports.
  11010. *
  11011. * If no index exists, the query engine tries to take advantage of the target
  11012. * document mapping in the TargetCache. These mappings exists for all queries
  11013. * that have been synced with the backend at least once and allow the query
  11014. * engine to only read documents that previously matched a query plus any
  11015. * documents that were edited after the query was last listened to.
  11016. *
  11017. * There are some cases when this optimization is not guaranteed to produce
  11018. * the same results as full collection scans. In these cases, query
  11019. * processing falls back to full scans. These cases are:
  11020. *
  11021. * - Limit queries where a document that matched the query previously no longer
  11022. * matches the query.
  11023. *
  11024. * - Limit queries where a document edit may cause the document to sort below
  11025. * another document that is in the local cache.
  11026. *
  11027. * - Queries that have never been CURRENT or free of limbo documents.
  11028. */ function qu(
  11029. /** Manages our in-memory or durable persistence. */
  11030. t, e, n, r) {
  11031. return new Pu(t, e, n, r);
  11032. }
  11033. /**
  11034. * Tells the LocalStore that the currently authenticated user has changed.
  11035. *
  11036. * In response the local store switches the mutation queue to the new user and
  11037. * returns any resulting document changes.
  11038. */
  11039. // PORTING NOTE: Android and iOS only return the documents affected by the
  11040. // change.
  11041. function Uu(t, r) {
  11042. return e(this, void 0, void 0, (function() {
  11043. var e;
  11044. return n(this, (function(n) {
  11045. switch (n.label) {
  11046. case 0:
  11047. return [ 4 /*yield*/ , (e = G(t)).persistence.runTransaction("Handle user change", "readonly", (function(t) {
  11048. // Swap out the mutation queue, grabbing the pending mutation batches
  11049. // before and after.
  11050. var n;
  11051. return e.mutationQueue.getAllMutationBatches(t).next((function(i) {
  11052. return n = i, e.Qi(r), e.mutationQueue.getAllMutationBatches(t);
  11053. })).next((function(r) {
  11054. for (var i = [], o = [], u = _r(), a = 0, s = n
  11055. // Union the old/new changed keys.
  11056. ; a < s.length; a++) {
  11057. var c = s[a];
  11058. i.push(c.batchId);
  11059. for (var l = 0, h = c.mutations; l < h.length; l++) {
  11060. var f = h[l];
  11061. u = u.add(f.key);
  11062. }
  11063. }
  11064. for (var d = 0, p = r; d < p.length; d++) {
  11065. var y = p[d];
  11066. o.push(y.batchId);
  11067. for (var v = 0, m = y.mutations; v < m.length; v++) {
  11068. var g = m[v];
  11069. u = u.add(g.key);
  11070. }
  11071. }
  11072. // Return the set of all (potentially) changed documents and the list
  11073. // of mutation batch IDs that were affected by change.
  11074. return e.localDocuments.getDocuments(t, u).next((function(t) {
  11075. return {
  11076. ji: t,
  11077. removedBatchIds: i,
  11078. addedBatchIds: o
  11079. };
  11080. }));
  11081. }));
  11082. })) ];
  11083. case 1:
  11084. return [ 2 /*return*/ , n.sent() ];
  11085. }
  11086. }));
  11087. }));
  11088. }
  11089. /* Accepts locally generated Mutations and commit them to storage. */
  11090. /**
  11091. * Acknowledges the given batch.
  11092. *
  11093. * On the happy path when a batch is acknowledged, the local store will
  11094. *
  11095. * + remove the batch from the mutation queue;
  11096. * + apply the changes to the remote document cache;
  11097. * + recalculate the latency compensated view implied by those changes (there
  11098. * may be mutations in the queue that affect the documents but haven't been
  11099. * acknowledged yet); and
  11100. * + give the changed documents back the sync engine
  11101. *
  11102. * @returns The resulting (modified) documents.
  11103. */ function Bu(t, e) {
  11104. var n = G(t);
  11105. return n.persistence.runTransaction("Acknowledge batch", "readwrite-primary", (function(t) {
  11106. var r = e.batch.keys(), i = n.Gi.newChangeBuffer({
  11107. trackRemovals: !0
  11108. });
  11109. return function(t, e, n, r) {
  11110. var i = n.batch, o = i.keys(), u = xt.resolve();
  11111. return o.forEach((function(t) {
  11112. u = u.next((function() {
  11113. return r.getEntry(e, t);
  11114. })).next((function(e) {
  11115. var o = n.docVersions.get(t);
  11116. U(null !== o), e.version.compareTo(o) < 0 && (i.applyToRemoteDocument(e, n), e.isValidDocument() && (
  11117. // We use the commitVersion as the readTime rather than the
  11118. // document's updateTime since the updateTime is not advanced
  11119. // for updates that do not modify the underlying document.
  11120. e.setReadTime(n.commitVersion), r.addEntry(e)));
  11121. }));
  11122. })), u.next((function() {
  11123. return t.mutationQueue.removeMutationBatch(e, i);
  11124. }));
  11125. }(n, t, e, i).next((function() {
  11126. return i.apply(t);
  11127. })).next((function() {
  11128. return n.mutationQueue.performConsistencyCheck(t);
  11129. })).next((function() {
  11130. return n.documentOverlayCache.removeOverlaysForBatchId(t, r, e.batch.batchId);
  11131. })).next((function() {
  11132. return n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, function(t) {
  11133. for (var e = _r(), n = 0; n < t.mutationResults.length; ++n) t.mutationResults[n].transformResults.length > 0 && (e = e.add(t.batch.mutations[n].key));
  11134. return e;
  11135. }(e));
  11136. })).next((function() {
  11137. return n.localDocuments.getDocuments(t, r);
  11138. }));
  11139. }));
  11140. }
  11141. /**
  11142. * Returns the last consistent snapshot processed (used by the RemoteStore to
  11143. * determine whether to buffer incoming snapshots from the backend).
  11144. */ function Gu(t) {
  11145. var e = G(t);
  11146. return e.persistence.runTransaction("Get last remote snapshot version", "readonly", (function(t) {
  11147. return e.Cs.getLastRemoteSnapshotVersion(t);
  11148. }));
  11149. }
  11150. /**
  11151. * Updates the "ground-state" (remote) documents. We assume that the remote
  11152. * event reflects any write batches that have been acknowledged or rejected
  11153. * (i.e. we do not re-apply local mutations to updates from this event).
  11154. *
  11155. * LocalDocuments are re-calculated if there are remaining mutations in the
  11156. * queue.
  11157. */ function Ku(t, e) {
  11158. var n = G(t), r = e.snapshotVersion, i = n.qi;
  11159. return n.persistence.runTransaction("Apply remote event", "readwrite-primary", (function(t) {
  11160. var o = n.Gi.newChangeBuffer({
  11161. trackRemovals: !0
  11162. });
  11163. // Reset newTargetDataByTargetMap in case this transaction gets re-run.
  11164. i = n.qi;
  11165. var u = [];
  11166. e.targetChanges.forEach((function(o, a) {
  11167. var s = i.get(a);
  11168. if (s) {
  11169. // Only update the remote keys if the target is still active. This
  11170. // ensures that we can persist the updated target data along with
  11171. // the updated assignment.
  11172. u.push(n.Cs.removeMatchingKeys(t, o.removedDocuments, a).next((function() {
  11173. return n.Cs.addMatchingKeys(t, o.addedDocuments, a);
  11174. })));
  11175. var c = s.withSequenceNumber(t.currentSequenceNumber);
  11176. e.targetMismatches.has(a) ? c = c.withResumeToken(Yt.EMPTY_BYTE_STRING, at.min()).withLastLimboFreeSnapshotVersion(at.min()) : o.resumeToken.approximateByteSize() > 0 && (c = c.withResumeToken(o.resumeToken, r)),
  11177. i = i.insert(a, c),
  11178. // Update the target data if there are target changes (or if
  11179. // sufficient time has passed since the last update).
  11180. /**
  11181. * Returns true if the newTargetData should be persisted during an update of
  11182. * an active target. TargetData should always be persisted when a target is
  11183. * being released and should not call this function.
  11184. *
  11185. * While the target is active, TargetData updates can be omitted when nothing
  11186. * about the target has changed except metadata like the resume token or
  11187. * snapshot version. Occasionally it's worth the extra write to prevent these
  11188. * values from getting too stale after a crash, but this doesn't have to be
  11189. * too frequent.
  11190. */
  11191. function(t, e, n) {
  11192. // Always persist target data if we don't already have a resume token.
  11193. return 0 === t.resumeToken.approximateByteSize() || (
  11194. // Don't allow resume token changes to be buffered indefinitely. This
  11195. // allows us to be reasonably up-to-date after a crash and avoids needing
  11196. // to loop over all active queries on shutdown. Especially in the browser
  11197. // we may not get time to do anything interesting while the current tab is
  11198. // closing.
  11199. e.snapshotVersion.toMicroseconds() - t.snapshotVersion.toMicroseconds() >= 3e8 || n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size > 0);
  11200. }(s, c, o) && u.push(n.Cs.updateTargetData(t, c));
  11201. }
  11202. }));
  11203. var a = vr(), s = _r();
  11204. // HACK: The only reason we allow a null snapshot version is so that we
  11205. // can synthesize remote events when we get permission denied errors while
  11206. // trying to resolve the state of a locally cached document that is in
  11207. // limbo.
  11208. if (e.documentUpdates.forEach((function(r) {
  11209. e.resolvedLimboDocuments.has(r) && u.push(n.persistence.referenceDelegate.updateLimboDocument(t, r));
  11210. })),
  11211. // Each loop iteration only affects its "own" doc, so it's safe to get all
  11212. // the remote documents in advance in a single call.
  11213. u.push(ju(t, o, e.documentUpdates).next((function(t) {
  11214. a = t.Wi, s = t.zi;
  11215. }))), !r.isEqual(at.min())) {
  11216. var c = n.Cs.getLastRemoteSnapshotVersion(t).next((function(e) {
  11217. return n.Cs.setTargetsMetadata(t, t.currentSequenceNumber, r);
  11218. }));
  11219. u.push(c);
  11220. }
  11221. return xt.waitFor(u).next((function() {
  11222. return o.apply(t);
  11223. })).next((function() {
  11224. return n.localDocuments.getLocalViewOfDocuments(t, a, s);
  11225. })).next((function() {
  11226. return a;
  11227. }));
  11228. })).then((function(t) {
  11229. return n.qi = i, t;
  11230. }));
  11231. }
  11232. /**
  11233. * Populates document change buffer with documents from backend or a bundle.
  11234. * Returns the document changes resulting from applying those documents, and
  11235. * also a set of documents whose existence state are changed as a result.
  11236. *
  11237. * @param txn - Transaction to use to read existing documents from storage.
  11238. * @param documentBuffer - Document buffer to collect the resulted changes to be
  11239. * applied to storage.
  11240. * @param documents - Documents to be applied.
  11241. */ function ju(t, e, n) {
  11242. var r = _r(), i = _r();
  11243. return n.forEach((function(t) {
  11244. return r = r.add(t);
  11245. })), e.getEntries(t, r).next((function(t) {
  11246. var r = vr();
  11247. return n.forEach((function(n, o) {
  11248. var u = t.get(n);
  11249. // Check if see if there is a existence state change for this document.
  11250. o.isFoundDocument() !== u.isFoundDocument() && (i = i.add(n)),
  11251. // Note: The order of the steps below is important, since we want
  11252. // to ensure that rejected limbo resolutions (which fabricate
  11253. // NoDocuments with SnapshotVersion.min()) never add documents to
  11254. // cache.
  11255. o.isNoDocument() && o.version.isEqual(at.min()) ? (
  11256. // NoDocuments with SnapshotVersion.min() are used in manufactured
  11257. // events. We remove these documents from cache since we lost
  11258. // access.
  11259. e.removeEntry(n, o.readTime), r = r.insert(n, o)) : !u.isValidDocument() || o.version.compareTo(u.version) > 0 || 0 === o.version.compareTo(u.version) && u.hasPendingWrites ? (e.addEntry(o),
  11260. r = r.insert(n, o)) : V("LocalStore", "Ignoring outdated watch update for ", n, ". Current version:", u.version, " Watch version:", o.version);
  11261. })), {
  11262. Wi: r,
  11263. zi: i
  11264. };
  11265. }))
  11266. /**
  11267. * Gets the mutation batch after the passed in batchId in the mutation queue
  11268. * or null if empty.
  11269. * @param afterBatchId - If provided, the batch to search after.
  11270. * @returns The next mutation or null if there wasn't one.
  11271. */;
  11272. }
  11273. function Qu(t, e) {
  11274. var n = G(t);
  11275. return n.persistence.runTransaction("Get next mutation batch", "readonly", (function(t) {
  11276. return void 0 === e && (e = -1), n.mutationQueue.getNextMutationBatchAfterBatchId(t, e);
  11277. }));
  11278. }
  11279. /**
  11280. * Reads the current value of a Document with a given key or null if not
  11281. * found - used for testing.
  11282. */
  11283. /**
  11284. * Assigns the given target an internal ID so that its results can be pinned so
  11285. * they don't get GC'd. A target must be allocated in the local store before
  11286. * the store can be used to manage its view.
  11287. *
  11288. * Allocating an already allocated `Target` will return the existing `TargetData`
  11289. * for that `Target`.
  11290. */ function zu(t, e) {
  11291. var n = G(t);
  11292. return n.persistence.runTransaction("Allocate target", "readwrite", (function(t) {
  11293. var r;
  11294. return n.Cs.getTargetData(t, e).next((function(i) {
  11295. return i ? (
  11296. // This target has been listened to previously, so reuse the
  11297. // previous targetID.
  11298. // TODO(mcg): freshen last accessed date?
  11299. r = i, xt.resolve(r)) : n.Cs.allocateTargetId(t).next((function(i) {
  11300. return r = new Wi(e, i, 0 /* TargetPurpose.Listen */ , t.currentSequenceNumber),
  11301. n.Cs.addTargetData(t, r).next((function() {
  11302. return r;
  11303. }));
  11304. }));
  11305. }));
  11306. })).then((function(t) {
  11307. // If Multi-Tab is enabled, the existing target data may be newer than
  11308. // the in-memory data
  11309. var r = n.qi.get(t.targetId);
  11310. return (null === r || t.snapshotVersion.compareTo(r.snapshotVersion) > 0) && (n.qi = n.qi.insert(t.targetId, t),
  11311. n.Ui.set(e, t.targetId)), t;
  11312. }));
  11313. }
  11314. /**
  11315. * Returns the TargetData as seen by the LocalStore, including updates that may
  11316. * have not yet been persisted to the TargetCache.
  11317. */
  11318. // Visible for testing.
  11319. /**
  11320. * Unpins all the documents associated with the given target. If
  11321. * `keepPersistedTargetData` is set to false and Eager GC enabled, the method
  11322. * directly removes the associated target data from the target cache.
  11323. *
  11324. * Releasing a non-existing `Target` is a no-op.
  11325. */
  11326. // PORTING NOTE: `keepPersistedTargetData` is multi-tab only.
  11327. function Wu(t, r, i) {
  11328. return e(this, void 0, void 0, (function() {
  11329. var e, o, u, a;
  11330. return n(this, (function(n) {
  11331. switch (n.label) {
  11332. case 0:
  11333. e = G(t), o = e.qi.get(r), u = i ? "readwrite" : "readwrite-primary", n.label = 1;
  11334. case 1:
  11335. return n.trys.push([ 1, 4, , 5 ]), i ? [ 3 /*break*/ , 3 ] : [ 4 /*yield*/ , e.persistence.runTransaction("Release target", u, (function(t) {
  11336. return e.persistence.referenceDelegate.removeTarget(t, o);
  11337. })) ];
  11338. case 2:
  11339. n.sent(), n.label = 3;
  11340. case 3:
  11341. return [ 3 /*break*/ , 5 ];
  11342. case 4:
  11343. if (!Ft(a = n.sent())) throw a;
  11344. // All `releaseTarget` does is record the final metadata state for the
  11345. // target, but we've been recording this periodically during target
  11346. // activity. If we lose this write this could cause a very slight
  11347. // difference in the order of target deletion during GC, but we
  11348. // don't define exact LRU semantics so this is acceptable.
  11349. return V("LocalStore", "Failed to update sequence numbers for target ".concat(r, ": ").concat(a)),
  11350. [ 3 /*break*/ , 5 ];
  11351. case 5:
  11352. return e.qi = e.qi.remove(r), e.Ui.delete(o.target), [ 2 /*return*/ ];
  11353. }
  11354. }));
  11355. }));
  11356. }
  11357. /**
  11358. * Runs the specified query against the local store and returns the results,
  11359. * potentially taking advantage of query data from previous executions (such
  11360. * as the set of remote keys).
  11361. *
  11362. * @param usePreviousResults - Whether results from previous executions can
  11363. * be used to optimize this query execution.
  11364. */ function Hu(t, e, n) {
  11365. var r = G(t), i = at.min(), o = _r();
  11366. return r.persistence.runTransaction("Execute query", "readonly", (function(t) {
  11367. return function(t, e, n) {
  11368. var r = G(t), i = r.Ui.get(n);
  11369. return void 0 !== i ? xt.resolve(r.qi.get(i)) : r.Cs.getTargetData(e, n);
  11370. }(r, t, In(e)).next((function(e) {
  11371. if (e) return i = e.lastLimboFreeSnapshotVersion, r.Cs.getMatchingKeysForTargetId(t, e.targetId).next((function(t) {
  11372. o = t;
  11373. }));
  11374. })).next((function() {
  11375. return r.Li.getDocumentsMatchingQuery(t, e, n ? i : at.min(), n ? o : _r());
  11376. })).next((function(t) {
  11377. return Zu(r, An(e), t), {
  11378. documents: t,
  11379. Hi: o
  11380. };
  11381. }));
  11382. }));
  11383. }
  11384. // PORTING NOTE: Multi-Tab only.
  11385. function Yu(t, e) {
  11386. var n = G(t), r = G(n.Cs), i = n.qi.get(e);
  11387. return i ? Promise.resolve(i.target) : n.persistence.runTransaction("Get target data", "readonly", (function(t) {
  11388. return r.ne(t, e).next((function(t) {
  11389. return t ? t.target : null;
  11390. }));
  11391. }));
  11392. }
  11393. /**
  11394. * Returns the set of documents that have been updated since the last call.
  11395. * If this is the first call, returns the set of changes since client
  11396. * initialization. Further invocations will return document that have changed
  11397. * since the prior call.
  11398. */
  11399. // PORTING NOTE: Multi-Tab only.
  11400. function Xu(t, e) {
  11401. var n = G(t), r = n.Ki.get(e) || at.min();
  11402. // Get the current maximum read time for the collection. This should always
  11403. // exist, but to reduce the chance for regressions we default to
  11404. // SnapshotVersion.Min()
  11405. // TODO(indexing): Consider removing the default value.
  11406. return n.persistence.runTransaction("Get new document changes", "readonly", (function(t) {
  11407. return n.Gi.getAllFromCollectionGroup(t, e, bt(r, -1),
  11408. /* limit= */ Number.MAX_SAFE_INTEGER);
  11409. })).then((function(t) {
  11410. return Zu(n, e, t), t;
  11411. }));
  11412. }
  11413. /** Sets the collection group's maximum read time from the given documents. */
  11414. // PORTING NOTE: Multi-Tab only.
  11415. function Zu(t, e, n) {
  11416. var r = t.Ki.get(e) || at.min();
  11417. n.forEach((function(t, e) {
  11418. e.readTime.compareTo(r) > 0 && (r = e.readTime);
  11419. })), t.Ki.set(e, r);
  11420. }
  11421. /**
  11422. * Creates a new target using the given bundle name, which will be used to
  11423. * hold the keys of all documents from the bundle in query-document mappings.
  11424. * This ensures that the loaded documents do not get garbage collected
  11425. * right away.
  11426. */
  11427. /**
  11428. * Applies the documents from a bundle to the "ground-state" (remote)
  11429. * documents.
  11430. *
  11431. * LocalDocuments are re-calculated if there are remaining mutations in the
  11432. * queue.
  11433. */ function Ju(t, r, i, o) {
  11434. return e(this, void 0, void 0, (function() {
  11435. var e, u, a, s, c, l, h, f, d, p;
  11436. return n(this, (function(n) {
  11437. switch (n.label) {
  11438. case 0:
  11439. for (e = G(t), u = _r(), a = vr(), s = 0, c = i; s < c.length; s++) l = c[s], h = r.Ji(l.metadata.name),
  11440. l.document && (u = u.add(h)), (f = r.Yi(l)).setReadTime(r.Xi(l.metadata.readTime)),
  11441. a = a.insert(h, f);
  11442. return d = e.Gi.newChangeBuffer({
  11443. trackRemovals: !0
  11444. }), [ 4 /*yield*/ , zu(e, function(t) {
  11445. // It is OK that the path used for the query is not valid, because this will
  11446. // not be read and queried.
  11447. return In(yn(ct.fromString("__bundle__/docs/".concat(t))));
  11448. }(o)) ];
  11449. case 1:
  11450. // Allocates a target to hold all document keys from the bundle, such that
  11451. // they will not get garbage collected right away.
  11452. return p = n.sent(), [ 2 /*return*/ , e.persistence.runTransaction("Apply bundle documents", "readwrite", (function(t) {
  11453. return ju(t, d, a).next((function(e) {
  11454. return d.apply(t), e;
  11455. })).next((function(n) {
  11456. return e.Cs.removeMatchingKeysForTargetId(t, p.targetId).next((function() {
  11457. return e.Cs.addMatchingKeys(t, u, p.targetId);
  11458. })).next((function() {
  11459. return e.localDocuments.getLocalViewOfDocuments(t, n.Wi, n.zi);
  11460. })).next((function() {
  11461. return n.Wi;
  11462. }));
  11463. }));
  11464. })) ];
  11465. }
  11466. }));
  11467. }));
  11468. }
  11469. /**
  11470. * Returns a promise of a boolean to indicate if the given bundle has already
  11471. * been loaded and the create time is newer than the current loading bundle.
  11472. */
  11473. /**
  11474. * Saves the given `NamedQuery` to local persistence.
  11475. */ function $u(t, r, i) {
  11476. return void 0 === i && (i = _r()), e(this, void 0, void 0, (function() {
  11477. var e, o;
  11478. return n(this, (function(n) {
  11479. switch (n.label) {
  11480. case 0:
  11481. return [ 4 /*yield*/ , zu(t, In(no(r.bundledQuery))) ];
  11482. case 1:
  11483. return e = n.sent(), [ 2 /*return*/ , (o = G(t)).persistence.runTransaction("Save named query", "readwrite", (function(t) {
  11484. var n = jr(r.readTime);
  11485. // Simply save the query itself if it is older than what the SDK already
  11486. // has.
  11487. if (e.snapshotVersion.compareTo(n) >= 0) return o.Ns.saveNamedQuery(t, r);
  11488. // Update existing target data because the query from the bundle is newer.
  11489. var u = e.withResumeToken(Yt.EMPTY_BYTE_STRING, n);
  11490. return o.qi = o.qi.insert(u.targetId, u), o.Cs.updateTargetData(t, u).next((function() {
  11491. return o.Cs.removeMatchingKeysForTargetId(t, e.targetId);
  11492. })).next((function() {
  11493. return o.Cs.addMatchingKeys(t, i, e.targetId);
  11494. })).next((function() {
  11495. return o.Ns.saveNamedQuery(t, r);
  11496. }));
  11497. })) ];
  11498. }
  11499. }));
  11500. }));
  11501. }
  11502. /** Assembles the key for a client state in WebStorage */ function ta(t, e) {
  11503. return "firestore_clients_".concat(t, "_").concat(e);
  11504. }
  11505. // The format of the WebStorage key that stores the mutation state is:
  11506. // firestore_mutations_<persistence_prefix>_<batch_id>
  11507. // (for unauthenticated users)
  11508. // or: firestore_mutations_<persistence_prefix>_<batch_id>_<user_uid>
  11509. // 'user_uid' is last to avoid needing to escape '_' characters that it might
  11510. // contain.
  11511. /** Assembles the key for a mutation batch in WebStorage */ function ea(t, e, n) {
  11512. var r = "firestore_mutations_".concat(t, "_").concat(n);
  11513. return e.isAuthenticated() && (r += "_".concat(e.uid)), r;
  11514. }
  11515. // The format of the WebStorage key that stores a query target's metadata is:
  11516. // firestore_targets_<persistence_prefix>_<target_id>
  11517. /** Assembles the key for a query state in WebStorage */ function na(t, e) {
  11518. return "firestore_targets_".concat(t, "_").concat(e);
  11519. }
  11520. // The WebStorage prefix that stores the primary tab's online state. The
  11521. // format of the key is:
  11522. // firestore_online_state_<persistence_prefix>
  11523. /**
  11524. * Holds the state of a mutation batch, including its user ID, batch ID and
  11525. * whether the batch is 'pending', 'acknowledged' or 'rejected'.
  11526. */
  11527. // Visible for testing
  11528. var ra = /** @class */ function() {
  11529. function t(t, e, n, r) {
  11530. this.user = t, this.batchId = e, this.state = n, this.error = r
  11531. /**
  11532. * Parses a MutationMetadata from its JSON representation in WebStorage.
  11533. * Logs a warning and returns null if the format of the data is not valid.
  11534. */;
  11535. }
  11536. return t.Zi = function(e, n, r) {
  11537. var i, o = JSON.parse(r), u = "object" == typeof o && -1 !== [ "pending", "acknowledged", "rejected" ].indexOf(o.state) && (void 0 === o.error || "object" == typeof o.error);
  11538. return u && o.error && ((u = "string" == typeof o.error.message && "string" == typeof o.error.code) && (i = new j(o.error.code, o.error.message))),
  11539. u ? new t(e, n, o.state, i) : (M("SharedClientState", "Failed to parse mutation state for ID '".concat(n, "': ").concat(r)),
  11540. null);
  11541. }, t.prototype.tr = function() {
  11542. var t = {
  11543. state: this.state,
  11544. updateTimeMs: Date.now()
  11545. };
  11546. return this.error && (t.error = {
  11547. code: this.error.code,
  11548. message: this.error.message
  11549. }), JSON.stringify(t);
  11550. }, t;
  11551. }(), ia = /** @class */ function() {
  11552. function t(t, e, n) {
  11553. this.targetId = t, this.state = e, this.error = n
  11554. /**
  11555. * Parses a QueryTargetMetadata from its JSON representation in WebStorage.
  11556. * Logs a warning and returns null if the format of the data is not valid.
  11557. */;
  11558. }
  11559. return t.Zi = function(e, n) {
  11560. var r, i = JSON.parse(n), o = "object" == typeof i && -1 !== [ "not-current", "current", "rejected" ].indexOf(i.state) && (void 0 === i.error || "object" == typeof i.error);
  11561. return o && i.error && ((o = "string" == typeof i.error.message && "string" == typeof i.error.code) && (r = new j(i.error.code, i.error.message))),
  11562. o ? new t(e, i.state, r) : (M("SharedClientState", "Failed to parse target state for ID '".concat(e, "': ").concat(n)),
  11563. null);
  11564. }, t.prototype.tr = function() {
  11565. var t = {
  11566. state: this.state,
  11567. updateTimeMs: Date.now()
  11568. };
  11569. return this.error && (t.error = {
  11570. code: this.error.code,
  11571. message: this.error.message
  11572. }), JSON.stringify(t);
  11573. }, t;
  11574. }(), oa = /** @class */ function() {
  11575. function t(t, e) {
  11576. this.clientId = t, this.activeTargetIds = e
  11577. /**
  11578. * Parses a RemoteClientState from the JSON representation in WebStorage.
  11579. * Logs a warning and returns null if the format of the data is not valid.
  11580. */;
  11581. }
  11582. return t.Zi = function(e, n) {
  11583. for (var r = JSON.parse(n), i = "object" == typeof r && r.activeTargetIds instanceof Array, o = xr(), u = 0; i && u < r.activeTargetIds.length; ++u) i = Wt(r.activeTargetIds[u]),
  11584. o = o.add(r.activeTargetIds[u]);
  11585. return i ? new t(e, o) : (M("SharedClientState", "Failed to parse client data for instance '".concat(e, "': ").concat(n)),
  11586. null);
  11587. }, t;
  11588. }(), ua = /** @class */ function() {
  11589. function t(t, e) {
  11590. this.clientId = t, this.onlineState = e
  11591. /**
  11592. * Parses a SharedOnlineState from its JSON representation in WebStorage.
  11593. * Logs a warning and returns null if the format of the data is not valid.
  11594. */;
  11595. }
  11596. return t.Zi = function(e) {
  11597. var n = JSON.parse(e);
  11598. return "object" == typeof n && -1 !== [ "Unknown", "Online", "Offline" ].indexOf(n.onlineState) && "string" == typeof n.clientId ? new t(n.clientId, n.onlineState) : (M("SharedClientState", "Failed to parse online state: ".concat(e)),
  11599. null);
  11600. }, t;
  11601. }(), aa = /** @class */ function() {
  11602. function t() {
  11603. this.activeTargetIds = xr();
  11604. }
  11605. return t.prototype.er = function(t) {
  11606. this.activeTargetIds = this.activeTargetIds.add(t);
  11607. }, t.prototype.nr = function(t) {
  11608. this.activeTargetIds = this.activeTargetIds.delete(t);
  11609. },
  11610. /**
  11611. * Converts this entry into a JSON-encoded format we can use for WebStorage.
  11612. * Does not encode `clientId` as it is part of the key in WebStorage.
  11613. */
  11614. t.prototype.tr = function() {
  11615. var t = {
  11616. activeTargetIds: this.activeTargetIds.toArray(),
  11617. updateTimeMs: Date.now()
  11618. };
  11619. return JSON.stringify(t);
  11620. }, t;
  11621. }(), sa = /** @class */ function() {
  11622. function t(t, e, n, r, i) {
  11623. this.window = t, this.Hs = e, this.persistenceKey = n, this.sr = r, this.syncEngine = null,
  11624. this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.ir = this.rr.bind(this),
  11625. this.ur = new He(rt), this.started = !1,
  11626. /**
  11627. * Captures WebStorage events that occur before `start()` is called. These
  11628. * events are replayed once `WebStorageSharedClientState` is started.
  11629. */
  11630. this.cr = [];
  11631. // Escape the special characters mentioned here:
  11632. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
  11633. var o = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  11634. this.storage = this.window.localStorage, this.currentUser = i, this.ar = ta(this.persistenceKey, this.sr),
  11635. this.hr =
  11636. /** Assembles the key for the current sequence number. */
  11637. function(t) {
  11638. return "firestore_sequence_number_".concat(t);
  11639. }(this.persistenceKey), this.ur = this.ur.insert(this.sr, new aa), this.lr = new RegExp("^firestore_clients_".concat(o, "_([^_]*)$")),
  11640. this.dr = new RegExp("^firestore_mutations_".concat(o, "_(\\d+)(?:_(.*))?$")), this._r = new RegExp("^firestore_targets_".concat(o, "_(\\d+)$")),
  11641. this.wr =
  11642. /** Assembles the key for the online state of the primary tab. */
  11643. function(t) {
  11644. return "firestore_online_state_".concat(t);
  11645. }(this.persistenceKey), this.mr = function(t) {
  11646. return "firestore_bundle_loaded_v2_".concat(t);
  11647. }(this.persistenceKey),
  11648. // Rather than adding the storage observer during start(), we add the
  11649. // storage observer during initialization. This ensures that we collect
  11650. // events before other components populate their initial state (during their
  11651. // respective start() calls). Otherwise, we might for example miss a
  11652. // mutation that is added after LocalStore's start() processed the existing
  11653. // mutations but before we observe WebStorage events.
  11654. this.window.addEventListener("storage", this.ir);
  11655. }
  11656. /** Returns 'true' if WebStorage is available in the current environment. */ return t.C = function(t) {
  11657. return !(!t || !t.localStorage);
  11658. }, t.prototype.start = function() {
  11659. return e(this, void 0, void 0, (function() {
  11660. var t, e, r, i, o, u, a, s, c, l, h, f = this;
  11661. return n(this, (function(n) {
  11662. switch (n.label) {
  11663. case 0:
  11664. return [ 4 /*yield*/ , this.syncEngine.vi() ];
  11665. case 1:
  11666. for (t = n.sent(), e = 0, r = t; e < r.length; e++) (i = r[e]) !== this.sr && (o = this.getItem(ta(this.persistenceKey, i))) && (u = oa.Zi(i, o)) && (this.ur = this.ur.insert(u.clientId, u));
  11667. for (this.gr(), (a = this.storage.getItem(this.wr)) && (s = this.yr(a)) && this.pr(s),
  11668. c = 0, l = this.cr; c < l.length; c++) h = l[c], this.rr(h);
  11669. return this.cr = [],
  11670. // Register a window unload hook to remove the client metadata entry from
  11671. // WebStorage even if `shutdown()` was not called.
  11672. this.window.addEventListener("pagehide", (function() {
  11673. return f.shutdown();
  11674. })), this.started = !0, [ 2 /*return*/ ];
  11675. }
  11676. }));
  11677. }));
  11678. }, t.prototype.writeSequenceNumber = function(t) {
  11679. this.setItem(this.hr, JSON.stringify(t));
  11680. }, t.prototype.getAllActiveQueryTargets = function() {
  11681. return this.Ir(this.ur);
  11682. }, t.prototype.isActiveQueryTarget = function(t) {
  11683. var e = !1;
  11684. return this.ur.forEach((function(n, r) {
  11685. r.activeTargetIds.has(t) && (e = !0);
  11686. })), e;
  11687. }, t.prototype.addPendingMutation = function(t) {
  11688. this.Tr(t, "pending");
  11689. }, t.prototype.updateMutationState = function(t, e, n) {
  11690. this.Tr(t, e, n),
  11691. // Once a final mutation result is observed by other clients, they no longer
  11692. // access the mutation's metadata entry. Since WebStorage replays events
  11693. // in order, it is safe to delete the entry right after updating it.
  11694. this.Er(t);
  11695. }, t.prototype.addLocalQueryTarget = function(t) {
  11696. var e = "not-current";
  11697. // Lookup an existing query state if the target ID was already registered
  11698. // by another tab
  11699. if (this.isActiveQueryTarget(t)) {
  11700. var n = this.storage.getItem(na(this.persistenceKey, t));
  11701. if (n) {
  11702. var r = ia.Zi(t, n);
  11703. r && (e = r.state);
  11704. }
  11705. }
  11706. return this.Ar.er(t), this.gr(), e;
  11707. }, t.prototype.removeLocalQueryTarget = function(t) {
  11708. this.Ar.nr(t), this.gr();
  11709. }, t.prototype.isLocalQueryTarget = function(t) {
  11710. return this.Ar.activeTargetIds.has(t);
  11711. }, t.prototype.clearQueryState = function(t) {
  11712. this.removeItem(na(this.persistenceKey, t));
  11713. }, t.prototype.updateQueryState = function(t, e, n) {
  11714. this.Rr(t, e, n);
  11715. }, t.prototype.handleUserChange = function(t, e, n) {
  11716. var r = this;
  11717. e.forEach((function(t) {
  11718. r.Er(t);
  11719. })), this.currentUser = t, n.forEach((function(t) {
  11720. r.addPendingMutation(t);
  11721. }));
  11722. }, t.prototype.setOnlineState = function(t) {
  11723. this.br(t);
  11724. }, t.prototype.notifyBundleLoaded = function(t) {
  11725. this.Pr(t);
  11726. }, t.prototype.shutdown = function() {
  11727. this.started && (this.window.removeEventListener("storage", this.ir), this.removeItem(this.ar),
  11728. this.started = !1);
  11729. }, t.prototype.getItem = function(t) {
  11730. var e = this.storage.getItem(t);
  11731. return V("SharedClientState", "READ", t, e), e;
  11732. }, t.prototype.setItem = function(t, e) {
  11733. V("SharedClientState", "SET", t, e), this.storage.setItem(t, e);
  11734. }, t.prototype.removeItem = function(t) {
  11735. V("SharedClientState", "REMOVE", t), this.storage.removeItem(t);
  11736. }, t.prototype.rr = function(t) {
  11737. var r = this, i = t;
  11738. // Note: The function is typed to take Event to be interface-compatible with
  11739. // `Window.addEventListener`.
  11740. if (i.storageArea === this.storage) {
  11741. if (V("SharedClientState", "EVENT", i.key, i.newValue), i.key === this.ar) return void M("Received WebStorage notification for local change. Another client might have garbage-collected our state");
  11742. this.Hs.enqueueRetryable((function() {
  11743. return e(r, void 0, void 0, (function() {
  11744. var t, e, r, o, u, a, s, c = this;
  11745. return n(this, (function(n) {
  11746. switch (n.label) {
  11747. case 0:
  11748. return this.started ? null === i.key ? [ 3 /*break*/ , 7 ] : this.lr.test(i.key) ? null == i.newValue ? (t = this.vr(i.key),
  11749. [ 2 /*return*/ , this.Vr(t, null) ]) : (e = this.Sr(i.key, i.newValue)) ? [ 2 /*return*/ , this.Vr(e.clientId, e) ] : [ 3 /*break*/ , 7 ] : [ 3 /*break*/ , 1 ] : [ 3 /*break*/ , 8 ];
  11750. case 1:
  11751. return this.dr.test(i.key) ? null !== i.newValue && (r = this.Dr(i.key, i.newValue)) ? [ 2 /*return*/ , this.Cr(r) ] : [ 3 /*break*/ , 7 ] : [ 3 /*break*/ , 2 ];
  11752. case 2:
  11753. return this._r.test(i.key) ? null !== i.newValue && (o = this.Nr(i.key, i.newValue)) ? [ 2 /*return*/ , this.kr(o) ] : [ 3 /*break*/ , 7 ] : [ 3 /*break*/ , 3 ];
  11754. case 3:
  11755. return i.key !== this.wr ? [ 3 /*break*/ , 4 ] : null !== i.newValue && (u = this.yr(i.newValue)) ? [ 2 /*return*/ , this.pr(u) ] : [ 3 /*break*/ , 7 ];
  11756. case 4:
  11757. return i.key !== this.hr ? [ 3 /*break*/ , 5 ] : (a = function(t) {
  11758. var e = qt.at;
  11759. if (null != t) try {
  11760. var n = JSON.parse(t);
  11761. U("number" == typeof n), e = n;
  11762. } catch (t) {
  11763. M("SharedClientState", "Failed to read sequence number from WebStorage", t);
  11764. }
  11765. return e;
  11766. }(i.newValue), a !== qt.at && this.sequenceNumberHandler(a), [ 3 /*break*/ , 7 ]);
  11767. case 5:
  11768. return i.key !== this.mr ? [ 3 /*break*/ , 7 ] : (s = this.Or(i.newValue), [ 4 /*yield*/ , Promise.all(s.map((function(t) {
  11769. return c.syncEngine.Mr(t);
  11770. }))) ]);
  11771. case 6:
  11772. n.sent(), n.label = 7;
  11773. case 7:
  11774. return [ 3 /*break*/ , 9 ];
  11775. case 8:
  11776. this.cr.push(i), n.label = 9;
  11777. case 9:
  11778. return [ 2 /*return*/ ];
  11779. }
  11780. }));
  11781. }));
  11782. }));
  11783. }
  11784. }, Object.defineProperty(t.prototype, "Ar", {
  11785. get: function() {
  11786. return this.ur.get(this.sr);
  11787. },
  11788. enumerable: !1,
  11789. configurable: !0
  11790. }), t.prototype.gr = function() {
  11791. this.setItem(this.ar, this.Ar.tr());
  11792. }, t.prototype.Tr = function(t, e, n) {
  11793. var r = new ra(this.currentUser, t, e, n), i = ea(this.persistenceKey, this.currentUser, t);
  11794. this.setItem(i, r.tr());
  11795. }, t.prototype.Er = function(t) {
  11796. var e = ea(this.persistenceKey, this.currentUser, t);
  11797. this.removeItem(e);
  11798. }, t.prototype.br = function(t) {
  11799. var e = {
  11800. clientId: this.sr,
  11801. onlineState: t
  11802. };
  11803. this.storage.setItem(this.wr, JSON.stringify(e));
  11804. }, t.prototype.Rr = function(t, e, n) {
  11805. var r = na(this.persistenceKey, t), i = new ia(t, e, n);
  11806. this.setItem(r, i.tr());
  11807. }, t.prototype.Pr = function(t) {
  11808. var e = JSON.stringify(Array.from(t));
  11809. this.setItem(this.mr, e);
  11810. },
  11811. /**
  11812. * Parses a client state key in WebStorage. Returns null if the key does not
  11813. * match the expected key format.
  11814. */
  11815. t.prototype.vr = function(t) {
  11816. var e = this.lr.exec(t);
  11817. return e ? e[1] : null;
  11818. },
  11819. /**
  11820. * Parses a client state in WebStorage. Returns 'null' if the value could not
  11821. * be parsed.
  11822. */
  11823. t.prototype.Sr = function(t, e) {
  11824. var n = this.vr(t);
  11825. return oa.Zi(n, e);
  11826. },
  11827. /**
  11828. * Parses a mutation batch state in WebStorage. Returns 'null' if the value
  11829. * could not be parsed.
  11830. */
  11831. t.prototype.Dr = function(t, e) {
  11832. var n = this.dr.exec(t), r = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;
  11833. return ra.Zi(new N(i), r, e);
  11834. },
  11835. /**
  11836. * Parses a query target state from WebStorage. Returns 'null' if the value
  11837. * could not be parsed.
  11838. */
  11839. t.prototype.Nr = function(t, e) {
  11840. var n = this._r.exec(t), r = Number(n[1]);
  11841. return ia.Zi(r, e);
  11842. },
  11843. /**
  11844. * Parses an online state from WebStorage. Returns 'null' if the value
  11845. * could not be parsed.
  11846. */
  11847. t.prototype.yr = function(t) {
  11848. return ua.Zi(t);
  11849. }, t.prototype.Or = function(t) {
  11850. return JSON.parse(t);
  11851. }, t.prototype.Cr = function(t) {
  11852. return e(this, void 0, void 0, (function() {
  11853. return n(this, (function(e) {
  11854. return t.user.uid === this.currentUser.uid ? [ 2 /*return*/ , this.syncEngine.Fr(t.batchId, t.state, t.error) ] : (V("SharedClientState", "Ignoring mutation for non-active user ".concat(t.user.uid)),
  11855. [ 2 /*return*/ ]);
  11856. }));
  11857. }));
  11858. }, t.prototype.kr = function(t) {
  11859. return this.syncEngine.$r(t.targetId, t.state, t.error);
  11860. }, t.prototype.Vr = function(t, e) {
  11861. var n = this, r = e ? this.ur.insert(t, e) : this.ur.remove(t), i = this.Ir(this.ur), o = this.Ir(r), u = [], a = [];
  11862. return o.forEach((function(t) {
  11863. i.has(t) || u.push(t);
  11864. })), i.forEach((function(t) {
  11865. o.has(t) || a.push(t);
  11866. })), this.syncEngine.Br(u, a).then((function() {
  11867. n.ur = r;
  11868. }));
  11869. }, t.prototype.pr = function(t) {
  11870. // We check whether the client that wrote this online state is still active
  11871. // by comparing its client ID to the list of clients kept active in
  11872. // IndexedDb. If a client does not update their IndexedDb client state
  11873. // within 5 seconds, it is considered inactive and we don't emit an online
  11874. // state event.
  11875. this.ur.get(t.clientId) && this.onlineStateHandler(t.onlineState);
  11876. }, t.prototype.Ir = function(t) {
  11877. var e = xr();
  11878. return t.forEach((function(t, n) {
  11879. e = e.unionWith(n.activeTargetIds);
  11880. })), e;
  11881. }, t;
  11882. }(), ca = /** @class */ function() {
  11883. function t() {
  11884. this.Lr = new aa, this.qr = {}, this.onlineStateHandler = null, this.sequenceNumberHandler = null;
  11885. }
  11886. return t.prototype.addPendingMutation = function(t) {
  11887. // No op.
  11888. }, t.prototype.updateMutationState = function(t, e, n) {
  11889. // No op.
  11890. }, t.prototype.addLocalQueryTarget = function(t) {
  11891. return this.Lr.er(t), this.qr[t] || "not-current";
  11892. }, t.prototype.updateQueryState = function(t, e, n) {
  11893. this.qr[t] = e;
  11894. }, t.prototype.removeLocalQueryTarget = function(t) {
  11895. this.Lr.nr(t);
  11896. }, t.prototype.isLocalQueryTarget = function(t) {
  11897. return this.Lr.activeTargetIds.has(t);
  11898. }, t.prototype.clearQueryState = function(t) {
  11899. delete this.qr[t];
  11900. }, t.prototype.getAllActiveQueryTargets = function() {
  11901. return this.Lr.activeTargetIds;
  11902. }, t.prototype.isActiveQueryTarget = function(t) {
  11903. return this.Lr.activeTargetIds.has(t);
  11904. }, t.prototype.start = function() {
  11905. return this.Lr = new aa, Promise.resolve();
  11906. }, t.prototype.handleUserChange = function(t, e, n) {
  11907. // No op.
  11908. }, t.prototype.setOnlineState = function(t) {
  11909. // No op.
  11910. }, t.prototype.shutdown = function() {}, t.prototype.writeSequenceNumber = function(t) {},
  11911. t.prototype.notifyBundleLoaded = function(t) {
  11912. // No op.
  11913. }, t;
  11914. }(), la = /** @class */ function() {
  11915. function t() {}
  11916. return t.prototype.Ur = function(t) {
  11917. // No-op.
  11918. }, t.prototype.shutdown = function() {
  11919. // No-op.
  11920. }, t;
  11921. }(), ha = /** @class */ function() {
  11922. function t() {
  11923. var t = this;
  11924. this.Kr = function() {
  11925. return t.Gr();
  11926. }, this.Qr = function() {
  11927. return t.jr();
  11928. }, this.Wr = [], this.zr();
  11929. }
  11930. return t.prototype.Ur = function(t) {
  11931. this.Wr.push(t);
  11932. }, t.prototype.shutdown = function() {
  11933. window.removeEventListener("online", this.Kr), window.removeEventListener("offline", this.Qr);
  11934. }, t.prototype.zr = function() {
  11935. window.addEventListener("online", this.Kr), window.addEventListener("offline", this.Qr);
  11936. }, t.prototype.Gr = function() {
  11937. V("ConnectivityMonitor", "Network connectivity changed: AVAILABLE");
  11938. for (var t = 0, e = this.Wr; t < e.length; t++) {
  11939. (0, e[t])(0 /* NetworkStatus.AVAILABLE */);
  11940. }
  11941. }, t.prototype.jr = function() {
  11942. V("ConnectivityMonitor", "Network connectivity changed: UNAVAILABLE");
  11943. for (var t = 0, e = this.Wr; t < e.length; t++) {
  11944. (0, e[t])(1 /* NetworkStatus.UNAVAILABLE */);
  11945. }
  11946. },
  11947. // TODO(chenbrian): Consider passing in window either into this component or
  11948. // here for testing via FakeWindow.
  11949. /** Checks that all used attributes of window are available. */
  11950. t.C = function() {
  11951. return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;
  11952. }, t;
  11953. }(), fa = {
  11954. BatchGetDocuments: "batchGet",
  11955. Commit: "commit",
  11956. RunQuery: "runQuery",
  11957. RunAggregationQuery: "runAggregationQuery"
  11958. }, da = /** @class */ function() {
  11959. function t(t) {
  11960. this.Hr = t.Hr, this.Jr = t.Jr;
  11961. }
  11962. return t.prototype.Yr = function(t) {
  11963. this.Xr = t;
  11964. }, t.prototype.Zr = function(t) {
  11965. this.eo = t;
  11966. }, t.prototype.onMessage = function(t) {
  11967. this.no = t;
  11968. }, t.prototype.close = function() {
  11969. this.Jr();
  11970. }, t.prototype.send = function(t) {
  11971. this.Hr(t);
  11972. }, t.prototype.so = function() {
  11973. this.Xr();
  11974. }, t.prototype.io = function(t) {
  11975. this.eo(t);
  11976. }, t.prototype.ro = function(t) {
  11977. this.no(t);
  11978. }, t;
  11979. }(), pa = /** @class */ function(e) {
  11980. function n(t) {
  11981. var n = this;
  11982. return (n = e.call(this, t) || this).forceLongPolling = t.forceLongPolling, n.autoDetectLongPolling = t.autoDetectLongPolling,
  11983. n.useFetchStreams = t.useFetchStreams, n;
  11984. }
  11985. /**
  11986. * Base class for all Rest-based connections to the backend (WebChannel and
  11987. * HTTP).
  11988. */
  11989. return t(n, e), n.prototype.fo = function(t, e, n, r) {
  11990. return new Promise((function(i, o) {
  11991. var u = new b;
  11992. u.setWithCredentials(!0), u.listenOnce(I.COMPLETE, (function() {
  11993. try {
  11994. switch (u.getLastErrorCode()) {
  11995. case T.NO_ERROR:
  11996. var e = u.getResponseJson();
  11997. V("Connection", "XHR received:", JSON.stringify(e)), i(e);
  11998. break;
  11999. case T.TIMEOUT:
  12000. V("Connection", 'RPC "' + t + '" timed out'), o(new j(K.DEADLINE_EXCEEDED, "Request time out"));
  12001. break;
  12002. case T.HTTP_ERROR:
  12003. var n = u.getStatus();
  12004. if (V("Connection", 'RPC "' + t + '" failed with status:', n, "response text:", u.getResponseText()),
  12005. n > 0) {
  12006. var r = u.getResponseJson();
  12007. Array.isArray(r) && (r = r[0]);
  12008. var a = null == r ? void 0 : r.error;
  12009. if (a && a.status && a.message) {
  12010. var s = function(t) {
  12011. var e = t.toLowerCase().replace(/_/g, "-");
  12012. return Object.values(K).indexOf(e) >= 0 ? e : K.UNKNOWN;
  12013. }(a.status);
  12014. o(new j(s, a.message));
  12015. } else o(new j(K.UNKNOWN, "Server responded with status " + u.getStatus()));
  12016. } else
  12017. // If we received an HTTP_ERROR but there's no status code,
  12018. // it's most probably a connection issue
  12019. o(new j(K.UNAVAILABLE, "Connection failed."));
  12020. break;
  12021. default:
  12022. q();
  12023. }
  12024. } finally {
  12025. V("Connection", 'RPC "' + t + '" completed.');
  12026. }
  12027. }));
  12028. var a = JSON.stringify(r);
  12029. u.send(e, "POST", a, n, 15);
  12030. }));
  12031. }, n.prototype.wo = function(t, e, n) {
  12032. var r = [ this.oo, "/", "google.firestore.v1.Firestore", "/", t, "/channel" ], i = E(), o = S(), u = {
  12033. // Required for backend stickiness, routing behavior is based on this
  12034. // parameter.
  12035. httpSessionIdParam: "gsessionid",
  12036. initMessageHeaders: {},
  12037. messageUrlParams: {
  12038. // This param is used to improve routing and project isolation by the
  12039. // backend and must be included in every request.
  12040. database: "projects/".concat(this.databaseId.projectId, "/databases/").concat(this.databaseId.database)
  12041. },
  12042. sendRawJson: !0,
  12043. supportsCrossDomainXhr: !0,
  12044. internalChannelParams: {
  12045. // Override the default timeout (randomized between 10-20 seconds) since
  12046. // a large write batch on a slow internet connection may take a long
  12047. // time to send to the backend. Rather than have WebChannel impose a
  12048. // tight timeout which could lead to infinite timeouts and retries, we
  12049. // set it very large (5-10 minutes) and rely on the browser's builtin
  12050. // timeouts to kick in if the request isn't working.
  12051. forwardChannelRequestTimeoutMs: 6e5
  12052. },
  12053. forceLongPolling: this.forceLongPolling,
  12054. detectBufferingProxy: this.autoDetectLongPolling
  12055. };
  12056. this.useFetchStreams && (u.xmlHttpFactory = new _({})), this.lo(u.initMessageHeaders, e, n),
  12057. // Sending the custom headers we just added to request.initMessageHeaders
  12058. // (Authorization, etc.) will trigger the browser to make a CORS preflight
  12059. // request because the XHR will no longer meet the criteria for a "simple"
  12060. // CORS request:
  12061. // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
  12062. // Therefore to avoid the CORS preflight request (an extra network
  12063. // roundtrip), we use the encodeInitMessageHeaders option to specify that
  12064. // the headers should instead be encoded in the request's POST payload,
  12065. // which is recognized by the webchannel backend.
  12066. u.encodeInitMessageHeaders = !0;
  12067. var a = r.join("");
  12068. V("Connection", "Creating WebChannel: " + a, u);
  12069. var s = i.createWebChannel(a, u), c = !1, l = !1, h = new da({
  12070. Hr: function(t) {
  12071. l ? V("Connection", "Not sending because WebChannel is closed:", t) : (c || (V("Connection", "Opening WebChannel transport."),
  12072. s.open(), c = !0), V("Connection", "WebChannel sending:", t), s.send(t));
  12073. },
  12074. Jr: function() {
  12075. return s.close();
  12076. }
  12077. }), f = function(t, e, n) {
  12078. // TODO(dimond): closure typing seems broken because WebChannel does
  12079. // not implement goog.events.Listenable
  12080. t.listen(e, (function(t) {
  12081. try {
  12082. n(t);
  12083. } catch (t) {
  12084. setTimeout((function() {
  12085. throw t;
  12086. }), 0);
  12087. }
  12088. }));
  12089. };
  12090. // WebChannel supports sending the first message with the handshake - saving
  12091. // a network round trip. However, it will have to call send in the same
  12092. // JS event loop as open. In order to enforce this, we delay actually
  12093. // opening the WebChannel until send is called. Whether we have called
  12094. // open is tracked with this variable.
  12095. // Closure events are guarded and exceptions are swallowed, so catch any
  12096. // exception and rethrow using a setTimeout so they become visible again.
  12097. // Note that eventually this function could go away if we are confident
  12098. // enough the code is exception free.
  12099. return f(s, D.EventType.OPEN, (function() {
  12100. l || V("Connection", "WebChannel transport opened.");
  12101. })), f(s, D.EventType.CLOSE, (function() {
  12102. l || (l = !0, V("Connection", "WebChannel transport closed"), h.io());
  12103. })), f(s, D.EventType.ERROR, (function(t) {
  12104. l || (l = !0, L("Connection", "WebChannel transport errored:", t), h.io(new j(K.UNAVAILABLE, "The operation could not be completed")));
  12105. })), f(s, D.EventType.MESSAGE, (function(t) {
  12106. var e;
  12107. if (!l) {
  12108. var n = t.data[0];
  12109. U(!!n);
  12110. // TODO(b/35143891): There is a bug in One Platform that caused errors
  12111. // (and only errors) to be wrapped in an extra array. To be forward
  12112. // compatible with the bug we need to check either condition. The latter
  12113. // can be removed once the fix has been rolled out.
  12114. // Use any because msgData.error is not typed.
  12115. var r = n, i = r.error || (null === (e = r[0]) || void 0 === e ? void 0 : e.error);
  12116. if (i) {
  12117. V("Connection", "WebChannel received error:", i);
  12118. // error.status will be a string like 'OK' or 'NOT_FOUND'.
  12119. var o = i.status, u =
  12120. /**
  12121. * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.
  12122. *
  12123. * @returns The Code equivalent to the given status string or undefined if
  12124. * there is no match.
  12125. */
  12126. function(t) {
  12127. // lookup by string
  12128. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12129. var e = ar[t];
  12130. if (void 0 !== e) return dr(e);
  12131. }(o), a = i.message;
  12132. void 0 === u && (u = K.INTERNAL, a = "Unknown error status: " + o + " with message " + i.message),
  12133. // Mark closed so no further events are propagated
  12134. l = !0, h.io(new j(u, a)), s.close();
  12135. } else V("Connection", "WebChannel received:", n), h.ro(n);
  12136. }
  12137. })), f(o, x.STAT_EVENT, (function(t) {
  12138. t.stat === A.PROXY ? V("Connection", "Detected buffering proxy") : t.stat === A.NOPROXY && V("Connection", "Detected no buffering proxy");
  12139. })), setTimeout((function() {
  12140. // Technically we could/should wait for the WebChannel opened event,
  12141. // but because we want to send the first message with the WebChannel
  12142. // handshake we pretend the channel opened here (asynchronously), and
  12143. // then delay the actual open until the first message is sent.
  12144. h.so();
  12145. }), 0), h;
  12146. }, n;
  12147. }(/** @class */ function() {
  12148. function t(t) {
  12149. this.databaseInfo = t, this.databaseId = t.databaseId;
  12150. var e = t.ssl ? "https" : "http";
  12151. this.oo = e + "://" + t.host, this.uo = "projects/" + this.databaseId.projectId + "/databases/" + this.databaseId.database + "/documents";
  12152. }
  12153. return Object.defineProperty(t.prototype, "co", {
  12154. get: function() {
  12155. // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine
  12156. // where to run the query, and expect the `request` to NOT specify the "path".
  12157. return !1;
  12158. },
  12159. enumerable: !1,
  12160. configurable: !0
  12161. }), t.prototype.ao = function(t, e, n, r, i) {
  12162. var o = this.ho(t, e);
  12163. V("RestConnection", "Sending: ", o, n);
  12164. var u = {};
  12165. return this.lo(u, r, i), this.fo(t, o, u, n).then((function(t) {
  12166. return V("RestConnection", "Received: ", t), t;
  12167. }), (function(e) {
  12168. throw L("RestConnection", "".concat(t, " failed with error: "), e, "url: ", o, "request:", n),
  12169. e;
  12170. }));
  12171. }, t.prototype._o = function(t, e, n, r, i, o) {
  12172. // The REST API automatically aggregates all of the streamed results, so we
  12173. // can just use the normal invoke() method.
  12174. return this.ao(t, e, n, r, i);
  12175. },
  12176. /**
  12177. * Modifies the headers for a request, adding any authorization token if
  12178. * present and any additional headers for the request.
  12179. */
  12180. t.prototype.lo = function(t, e, n) {
  12181. t["X-Goog-Api-Client"] = "gl-js/ fire/" + k,
  12182. // Content-Type: text/plain will avoid preflight requests which might
  12183. // mess with CORS and redirects by proxies. If we add custom headers
  12184. // we will need to change this code to potentially use the $httpOverwrite
  12185. // parameter supported by ESF to avoid triggering preflight requests.
  12186. t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId),
  12187. e && e.headers.forEach((function(e, n) {
  12188. return t[n] = e;
  12189. })), n && n.headers.forEach((function(e, n) {
  12190. return t[n] = e;
  12191. }));
  12192. }, t.prototype.ho = function(t, e) {
  12193. var n = fa[t];
  12194. return "".concat(this.oo, "/v1/").concat(e, ":").concat(n);
  12195. }, t;
  12196. }());
  12197. /**
  12198. * Holds the state of a query target, including its target ID and whether the
  12199. * target is 'not-current', 'current' or 'rejected'.
  12200. */
  12201. // Visible for testing
  12202. /**
  12203. * @license
  12204. * Copyright 2020 Google LLC
  12205. *
  12206. * Licensed under the Apache License, Version 2.0 (the "License");
  12207. * you may not use this file except in compliance with the License.
  12208. * You may obtain a copy of the License at
  12209. *
  12210. * http://www.apache.org/licenses/LICENSE-2.0
  12211. *
  12212. * Unless required by applicable law or agreed to in writing, software
  12213. * distributed under the License is distributed on an "AS IS" BASIS,
  12214. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12215. * See the License for the specific language governing permissions and
  12216. * limitations under the License.
  12217. */
  12218. /** Initializes the WebChannelConnection for the browser. */
  12219. /**
  12220. * @license
  12221. * Copyright 2020 Google LLC
  12222. *
  12223. * Licensed under the Apache License, Version 2.0 (the "License");
  12224. * you may not use this file except in compliance with the License.
  12225. * You may obtain a copy of the License at
  12226. *
  12227. * http://www.apache.org/licenses/LICENSE-2.0
  12228. *
  12229. * Unless required by applicable law or agreed to in writing, software
  12230. * distributed under the License is distributed on an "AS IS" BASIS,
  12231. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12232. * See the License for the specific language governing permissions and
  12233. * limitations under the License.
  12234. */
  12235. /** The Platform's 'window' implementation or null if not available. */
  12236. function ya() {
  12237. // `window` is not always available, e.g. in ReactNative and WebWorkers.
  12238. // eslint-disable-next-line no-restricted-globals
  12239. return "undefined" != typeof window ? window : null;
  12240. }
  12241. /** The Platform's 'document' implementation or null if not available. */ function va() {
  12242. // `document` is not always available, e.g. in ReactNative and WebWorkers.
  12243. // eslint-disable-next-line no-restricted-globals
  12244. return "undefined" != typeof document ? document : null;
  12245. }
  12246. /**
  12247. * @license
  12248. * Copyright 2020 Google LLC
  12249. *
  12250. * Licensed under the Apache License, Version 2.0 (the "License");
  12251. * you may not use this file except in compliance with the License.
  12252. * You may obtain a copy of the License at
  12253. *
  12254. * http://www.apache.org/licenses/LICENSE-2.0
  12255. *
  12256. * Unless required by applicable law or agreed to in writing, software
  12257. * distributed under the License is distributed on an "AS IS" BASIS,
  12258. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12259. * See the License for the specific language governing permissions and
  12260. * limitations under the License.
  12261. */ function ma(t) {
  12262. return new Ur(t, /* useProto3Json= */ !0);
  12263. }
  12264. /**
  12265. * An instance of the Platform's 'TextEncoder' implementation.
  12266. */
  12267. /**
  12268. * A helper for running delayed tasks following an exponential backoff curve
  12269. * between attempts.
  12270. *
  12271. * Each delay is made up of a "base" delay which follows the exponential
  12272. * backoff curve, and a +/- 50% "jitter" that is calculated and added to the
  12273. * base delay. This prevents clients from accidentally synchronizing their
  12274. * delays causing spikes of load to the backend.
  12275. */ var ga = /** @class */ function() {
  12276. function t(
  12277. /**
  12278. * The AsyncQueue to run backoff operations on.
  12279. */
  12280. t,
  12281. /**
  12282. * The ID to use when scheduling backoff operations on the AsyncQueue.
  12283. */
  12284. e,
  12285. /**
  12286. * The initial delay (used as the base delay on the first retry attempt).
  12287. * Note that jitter will still be applied, so the actual delay could be as
  12288. * little as 0.5*initialDelayMs.
  12289. */
  12290. n
  12291. /**
  12292. * The multiplier to use to determine the extended base delay after each
  12293. * attempt.
  12294. */ , r
  12295. /**
  12296. * The maximum base delay after which no further backoff is performed.
  12297. * Note that jitter will still be applied, so the actual delay could be as
  12298. * much as 1.5*maxDelayMs.
  12299. */ , i) {
  12300. void 0 === n && (n = 1e3), void 0 === r && (r = 1.5), void 0 === i && (i = 6e4),
  12301. this.Hs = t, this.timerId = e, this.mo = n, this.yo = r, this.po = i, this.Io = 0,
  12302. this.To = null,
  12303. /** The last backoff attempt, as epoch milliseconds. */
  12304. this.Eo = Date.now(), this.reset();
  12305. }
  12306. /**
  12307. * Resets the backoff delay.
  12308. *
  12309. * The very next backoffAndWait() will have no delay. If it is called again
  12310. * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
  12311. * subsequent ones will increase according to the backoffFactor.
  12312. */ return t.prototype.reset = function() {
  12313. this.Io = 0;
  12314. },
  12315. /**
  12316. * Resets the backoff delay to the maximum delay (e.g. for use after a
  12317. * RESOURCE_EXHAUSTED error).
  12318. */
  12319. t.prototype.Ao = function() {
  12320. this.Io = this.po;
  12321. },
  12322. /**
  12323. * Returns a promise that resolves after currentDelayMs, and increases the
  12324. * delay for any subsequent attempts. If there was a pending backoff operation
  12325. * already, it will be canceled.
  12326. */
  12327. t.prototype.Ro = function(t) {
  12328. var e = this;
  12329. // Cancel any pending backoff operation.
  12330. this.cancel();
  12331. // First schedule using the current base (which may be 0 and should be
  12332. // honored as such).
  12333. var n = Math.floor(this.Io + this.bo()), r = Math.max(0, Date.now() - this.Eo), i = Math.max(0, n - r);
  12334. // Guard against lastAttemptTime being in the future due to a clock change.
  12335. i > 0 && V("ExponentialBackoff", "Backing off for ".concat(i, " ms (base delay: ").concat(this.Io, " ms, delay with jitter: ").concat(n, " ms, last attempt: ").concat(r, " ms ago)")),
  12336. this.To = this.Hs.enqueueAfterDelay(this.timerId, i, (function() {
  12337. return e.Eo = Date.now(), t();
  12338. })),
  12339. // Apply backoff factor to determine next delay and ensure it is within
  12340. // bounds.
  12341. this.Io *= this.yo, this.Io < this.mo && (this.Io = this.mo), this.Io > this.po && (this.Io = this.po);
  12342. }, t.prototype.Po = function() {
  12343. null !== this.To && (this.To.skipDelay(), this.To = null);
  12344. }, t.prototype.cancel = function() {
  12345. null !== this.To && (this.To.cancel(), this.To = null);
  12346. },
  12347. /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ t.prototype.bo = function() {
  12348. return (Math.random() - .5) * this.Io;
  12349. }, t;
  12350. }(), wa = /** @class */ function() {
  12351. function t(t, e, n, r, i, o, u, a) {
  12352. this.Hs = t, this.vo = n, this.Vo = r, this.connection = i, this.authCredentialsProvider = o,
  12353. this.appCheckCredentialsProvider = u, this.listener = a, this.state = 0 /* PersistentStreamState.Initial */ ,
  12354. /**
  12355. * A close count that's incremented every time the stream is closed; used by
  12356. * getCloseGuardedDispatcher() to invalidate callbacks that happen after
  12357. * close.
  12358. */
  12359. this.So = 0, this.Do = null, this.Co = null, this.stream = null, this.xo = new ga(t, e)
  12360. /**
  12361. * Returns true if start() has been called and no error has occurred. True
  12362. * indicates the stream is open or in the process of opening (which
  12363. * encompasses respecting backoff, getting auth tokens, and starting the
  12364. * actual RPC). Use isOpen() to determine if the stream is open and ready for
  12365. * outbound requests.
  12366. */;
  12367. }
  12368. return t.prototype.No = function() {
  12369. return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.ko();
  12370. },
  12371. /**
  12372. * Returns true if the underlying RPC is open (the onOpen() listener has been
  12373. * called) and the stream is ready for outbound requests.
  12374. */
  12375. t.prototype.ko = function() {
  12376. return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state;
  12377. },
  12378. /**
  12379. * Starts the RPC. Only allowed if isStarted() returns false. The stream is
  12380. * not immediately ready for use: onOpen() will be invoked when the RPC is
  12381. * ready for outbound requests, at which point isOpen() will return true.
  12382. *
  12383. * When start returns, isStarted() will return true.
  12384. */
  12385. t.prototype.start = function() {
  12386. 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.Oo();
  12387. },
  12388. /**
  12389. * Stops the RPC. This call is idempotent and allowed regardless of the
  12390. * current isStarted() state.
  12391. *
  12392. * When stop returns, isStarted() and isOpen() will both return false.
  12393. */
  12394. t.prototype.stop = function() {
  12395. return e(this, void 0, void 0, (function() {
  12396. return n(this, (function(t) {
  12397. switch (t.label) {
  12398. case 0:
  12399. return this.No() ? [ 4 /*yield*/ , this.close(0 /* PersistentStreamState.Initial */) ] : [ 3 /*break*/ , 2 ];
  12400. case 1:
  12401. t.sent(), t.label = 2;
  12402. case 2:
  12403. return [ 2 /*return*/ ];
  12404. }
  12405. }));
  12406. }));
  12407. },
  12408. /**
  12409. * After an error the stream will usually back off on the next attempt to
  12410. * start it. If the error warrants an immediate restart of the stream, the
  12411. * sender can use this to indicate that the receiver should not back off.
  12412. *
  12413. * Each error will call the onClose() listener. That function can decide to
  12414. * inhibit backoff if required.
  12415. */
  12416. t.prototype.Mo = function() {
  12417. this.state = 0 /* PersistentStreamState.Initial */ , this.xo.reset();
  12418. },
  12419. /**
  12420. * Marks this stream as idle. If no further actions are performed on the
  12421. * stream for one minute, the stream will automatically close itself and
  12422. * notify the stream's onClose() handler with Status.OK. The stream will then
  12423. * be in a !isStarted() state, requiring the caller to start the stream again
  12424. * before further use.
  12425. *
  12426. * Only streams that are in state 'Open' can be marked idle, as all other
  12427. * states imply pending network operations.
  12428. */
  12429. t.prototype.Fo = function() {
  12430. var t = this;
  12431. // Starts the idle time if we are in state 'Open' and are not yet already
  12432. // running a timer (in which case the previous idle timeout still applies).
  12433. this.ko() && null === this.Do && (this.Do = this.Hs.enqueueAfterDelay(this.vo, 6e4, (function() {
  12434. return t.$o();
  12435. })));
  12436. },
  12437. /** Sends a message to the underlying stream. */ t.prototype.Bo = function(t) {
  12438. this.Lo(), this.stream.send(t);
  12439. },
  12440. /** Called by the idle timer when the stream should close due to inactivity. */ t.prototype.$o = function() {
  12441. return e(this, void 0, void 0, (function() {
  12442. return n(this, (function(t) {
  12443. return this.ko() ? [ 2 /*return*/ , this.close(0 /* PersistentStreamState.Initial */) ] : [ 2 /*return*/ ];
  12444. }));
  12445. }));
  12446. },
  12447. /** Marks the stream as active again. */ t.prototype.Lo = function() {
  12448. this.Do && (this.Do.cancel(), this.Do = null);
  12449. },
  12450. /** Cancels the health check delayed operation. */ t.prototype.qo = function() {
  12451. this.Co && (this.Co.cancel(), this.Co = null);
  12452. },
  12453. /**
  12454. * Closes the stream and cleans up as necessary:
  12455. *
  12456. * * closes the underlying GRPC stream;
  12457. * * calls the onClose handler with the given 'error';
  12458. * * sets internal stream state to 'finalState';
  12459. * * adjusts the backoff timer based on the error
  12460. *
  12461. * A new stream can be opened by calling start().
  12462. *
  12463. * @param finalState - the intended state of the stream after closing.
  12464. * @param error - the error the connection was closed with.
  12465. */
  12466. t.prototype.close = function(t, r) {
  12467. return e(this, void 0, void 0, (function() {
  12468. return n(this, (function(e) {
  12469. switch (e.label) {
  12470. case 0:
  12471. // Notify the listener that the stream closed.
  12472. // Cancel any outstanding timers (they're guaranteed not to execute).
  12473. return this.Lo(), this.qo(), this.xo.cancel(),
  12474. // Invalidates any stream-related callbacks (e.g. from auth or the
  12475. // underlying stream), guaranteeing they won't execute.
  12476. this.So++, 4 /* PersistentStreamState.Error */ !== t ?
  12477. // If this is an intentional close ensure we don't delay our next connection attempt.
  12478. this.xo.reset() : r && r.code === K.RESOURCE_EXHAUSTED ? (
  12479. // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)
  12480. M(r.toString()), M("Using maximum backoff delay to prevent overloading the backend."),
  12481. this.xo.Ao()) : r && r.code === K.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && (
  12482. // "unauthenticated" error means the token was rejected. This should rarely
  12483. // happen since both Auth and AppCheck ensure a sufficient TTL when we
  12484. // request a token. If a user manually resets their system clock this can
  12485. // fail, however. In this case, we should get a Code.UNAUTHENTICATED error
  12486. // before we received the first message and we need to invalidate the token
  12487. // to ensure that we fetch a new token.
  12488. this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()),
  12489. // Clean up the underlying stream because we are no longer interested in events.
  12490. null !== this.stream && (this.Uo(), this.stream.close(), this.stream = null),
  12491. // This state must be assigned before calling onClose() to allow the callback to
  12492. // inhibit backoff or otherwise manipulate the state in its non-started state.
  12493. this.state = t, [ 4 /*yield*/ , this.listener.Zr(r) ];
  12494. case 1:
  12495. // Cancel any outstanding timers (they're guaranteed not to execute).
  12496. // Notify the listener that the stream closed.
  12497. return e.sent(), [ 2 /*return*/ ];
  12498. }
  12499. }));
  12500. }));
  12501. },
  12502. /**
  12503. * Can be overridden to perform additional cleanup before the stream is closed.
  12504. * Calling super.tearDown() is not required.
  12505. */
  12506. t.prototype.Uo = function() {}, t.prototype.auth = function() {
  12507. var t = this;
  12508. this.state = 1 /* PersistentStreamState.Starting */;
  12509. var e = this.Ko(this.So), n = this.So;
  12510. // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.
  12511. Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((function(e) {
  12512. var r = e[0], i = e[1];
  12513. // Stream can be stopped while waiting for authentication.
  12514. // TODO(mikelehen): We really should just use dispatchIfNotClosed
  12515. // and let this dispatch onto the queue, but that opened a spec test can
  12516. // of worms that I don't want to deal with in this PR.
  12517. t.So === n &&
  12518. // Normally we'd have to schedule the callback on the AsyncQueue.
  12519. // However, the following calls are safe to be called outside the
  12520. // AsyncQueue since they don't chain asynchronous calls
  12521. t.Go(r, i);
  12522. }), (function(n) {
  12523. e((function() {
  12524. var e = new j(K.UNKNOWN, "Fetching auth token failed: " + n.message);
  12525. return t.Qo(e);
  12526. }));
  12527. }));
  12528. }, t.prototype.Go = function(t, e) {
  12529. var n = this, r = this.Ko(this.So);
  12530. this.stream = this.jo(t, e), this.stream.Yr((function() {
  12531. r((function() {
  12532. return n.state = 2 /* PersistentStreamState.Open */ , n.Co = n.Hs.enqueueAfterDelay(n.Vo, 1e4, (function() {
  12533. return n.ko() && (n.state = 3 /* PersistentStreamState.Healthy */), Promise.resolve();
  12534. })), n.listener.Yr();
  12535. }));
  12536. })), this.stream.Zr((function(t) {
  12537. r((function() {
  12538. return n.Qo(t);
  12539. }));
  12540. })), this.stream.onMessage((function(t) {
  12541. r((function() {
  12542. return n.onMessage(t);
  12543. }));
  12544. }));
  12545. }, t.prototype.Oo = function() {
  12546. var t = this;
  12547. this.state = 5 /* PersistentStreamState.Backoff */ , this.xo.Ro((function() {
  12548. return e(t, void 0, void 0, (function() {
  12549. return n(this, (function(t) {
  12550. return this.state = 0 /* PersistentStreamState.Initial */ , this.start(), [ 2 /*return*/ ];
  12551. }));
  12552. }));
  12553. }));
  12554. },
  12555. // Visible for tests
  12556. t.prototype.Qo = function(t) {
  12557. // In theory the stream could close cleanly, however, in our current model
  12558. // we never expect this to happen because if we stop a stream ourselves,
  12559. // this callback will never be called. To prevent cases where we retry
  12560. // without a backoff accidentally, we set the stream to error in all cases.
  12561. return V("PersistentStream", "close with error: ".concat(t)), this.stream = null,
  12562. this.close(4 /* PersistentStreamState.Error */ , t);
  12563. },
  12564. /**
  12565. * Returns a "dispatcher" function that dispatches operations onto the
  12566. * AsyncQueue but only runs them if closeCount remains unchanged. This allows
  12567. * us to turn auth / stream callbacks into no-ops if the stream is closed /
  12568. * re-opened, etc.
  12569. */
  12570. t.prototype.Ko = function(t) {
  12571. var e = this;
  12572. return function(n) {
  12573. e.Hs.enqueueAndForget((function() {
  12574. return e.So === t ? n() : (V("PersistentStream", "stream callback skipped by getCloseGuardedDispatcher."),
  12575. Promise.resolve());
  12576. }));
  12577. };
  12578. }, t;
  12579. }(), ba = /** @class */ function(e) {
  12580. function n(t, n, r, i, o, u) {
  12581. var a = this;
  12582. return (a = e.call(this, t, "listen_stream_connection_backoff" /* TimerId.ListenStreamConnectionBackoff */ , "listen_stream_idle" /* TimerId.ListenStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , n, r, i, u) || this).yt = o,
  12583. a;
  12584. }
  12585. return t(n, e), n.prototype.jo = function(t, e) {
  12586. return this.connection.wo("Listen", t, e);
  12587. }, n.prototype.onMessage = function(t) {
  12588. // A successful response means the stream is healthy
  12589. this.xo.reset();
  12590. var e = function(t, e) {
  12591. var n;
  12592. if ("targetChange" in e) {
  12593. e.targetChange;
  12594. // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'
  12595. // if unset
  12596. var r = function(t) {
  12597. return "NO_CHANGE" === t ? 0 /* WatchTargetChangeState.NoChange */ : "ADD" === t ? 1 /* WatchTargetChangeState.Added */ : "REMOVE" === t ? 2 /* WatchTargetChangeState.Removed */ : "CURRENT" === t ? 3 /* WatchTargetChangeState.Current */ : "RESET" === t ? 4 /* WatchTargetChangeState.Reset */ : q();
  12598. }(e.targetChange.targetChangeType || "NO_CHANGE"), i = e.targetChange.targetIds || [], o = function(t, e) {
  12599. return t.wt ? (U(void 0 === e || "string" == typeof e), Yt.fromBase64String(e || "")) : (U(void 0 === e || e instanceof Uint8Array),
  12600. Yt.fromUint8Array(e || new Uint8Array));
  12601. }(t, e.targetChange.resumeToken), u = e.targetChange.cause, a = u && function(t) {
  12602. var e = void 0 === t.code ? K.UNKNOWN : dr(t.code);
  12603. return new j(e, t.message || "");
  12604. }(u);
  12605. n = new Fr(r, i, o, a || null);
  12606. } else if ("documentChange" in e) {
  12607. e.documentChange;
  12608. var s = e.documentChange;
  12609. s.document, s.document.name, s.document.updateTime;
  12610. var c = Hr(t, s.document.name), l = jr(s.document.updateTime), h = s.document.createTime ? jr(s.document.createTime) : at.min(), f = new en({
  12611. mapValue: {
  12612. fields: s.document.fields
  12613. }
  12614. }), d = rn.newFoundDocument(c, l, h, f), p = s.targetIds || [], y = s.removedTargetIds || [];
  12615. n = new Nr(p, y, d.key, d);
  12616. } else if ("documentDelete" in e) {
  12617. e.documentDelete;
  12618. var v = e.documentDelete;
  12619. v.document;
  12620. var m = Hr(t, v.document), g = v.readTime ? jr(v.readTime) : at.min(), w = rn.newNoDocument(m, g), b = v.removedTargetIds || [];
  12621. n = new Nr([], b, w.key, w);
  12622. } else if ("documentRemove" in e) {
  12623. e.documentRemove;
  12624. var I = e.documentRemove;
  12625. I.document;
  12626. var T = Hr(t, I.document), E = I.removedTargetIds || [];
  12627. n = new Nr([], E, T, null);
  12628. } else {
  12629. if (!("filter" in e)) return q();
  12630. e.filter;
  12631. var S = e.filter;
  12632. S.targetId;
  12633. var _ = S.count || 0, D = new hr(_), x = S.targetId;
  12634. n = new kr(x, D);
  12635. }
  12636. return n;
  12637. }(this.yt, t), n = function(t) {
  12638. // We have only reached a consistent snapshot for the entire stream if there
  12639. // is a read_time set and it applies to all targets (i.e. the list of
  12640. // targets is empty). The backend is guaranteed to send such responses.
  12641. if (!("targetChange" in t)) return at.min();
  12642. var e = t.targetChange;
  12643. return e.targetIds && e.targetIds.length ? at.min() : e.readTime ? jr(e.readTime) : at.min();
  12644. }(t);
  12645. return this.listener.Wo(e, n);
  12646. },
  12647. /**
  12648. * Registers interest in the results of the given target. If the target
  12649. * includes a resumeToken it will be included in the request. Results that
  12650. * affect the target will be streamed back as WatchChange messages that
  12651. * reference the targetId.
  12652. */
  12653. n.prototype.zo = function(t) {
  12654. var e = {};
  12655. e.database = Zr(this.yt), e.addTarget = function(t, e) {
  12656. var n, r = e.target;
  12657. return (n = cn(r) ? {
  12658. documents: ri(t, r)
  12659. } : {
  12660. query: ii(t, r)
  12661. }).targetId = e.targetId, e.resumeToken.approximateByteSize() > 0 ? n.resumeToken = Gr(t, e.resumeToken) : e.snapshotVersion.compareTo(at.min()) > 0 && (
  12662. // TODO(wuandy): Consider removing above check because it is most likely true.
  12663. // Right now, many tests depend on this behaviour though (leaving min() out
  12664. // of serialization).
  12665. n.readTime = Br(t, e.snapshotVersion.toTimestamp())), n;
  12666. }(this.yt, t);
  12667. var n = function(t, e) {
  12668. var n = function(t, e) {
  12669. switch (e) {
  12670. case 0 /* TargetPurpose.Listen */ :
  12671. return null;
  12672. case 1 /* TargetPurpose.ExistenceFilterMismatch */ :
  12673. return "existence-filter-mismatch";
  12674. case 2 /* TargetPurpose.LimboResolution */ :
  12675. return "limbo-document";
  12676. default:
  12677. return q();
  12678. }
  12679. }(0, e.purpose);
  12680. return null == n ? null : {
  12681. "goog-listen-tags": n
  12682. };
  12683. }(this.yt, t);
  12684. n && (e.labels = n), this.Bo(e);
  12685. },
  12686. /**
  12687. * Unregisters interest in the results of the target associated with the
  12688. * given targetId.
  12689. */
  12690. n.prototype.Ho = function(t) {
  12691. var e = {};
  12692. e.database = Zr(this.yt), e.removeTarget = t, this.Bo(e);
  12693. }, n;
  12694. }(wa), Ia = /** @class */ function(e) {
  12695. function n(t, n, r, i, o, u) {
  12696. var a = this;
  12697. return (a = e.call(this, t, "write_stream_connection_backoff" /* TimerId.WriteStreamConnectionBackoff */ , "write_stream_idle" /* TimerId.WriteStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , n, r, i, u) || this).yt = o,
  12698. a.Jo = !1, a;
  12699. }
  12700. return t(n, e), Object.defineProperty(n.prototype, "Yo", {
  12701. /**
  12702. * Tracks whether or not a handshake has been successfully exchanged and
  12703. * the stream is ready to accept mutations.
  12704. */
  12705. get: function() {
  12706. return this.Jo;
  12707. },
  12708. enumerable: !1,
  12709. configurable: !0
  12710. }),
  12711. // Override of PersistentStream.start
  12712. n.prototype.start = function() {
  12713. this.Jo = !1, this.lastStreamToken = void 0, e.prototype.start.call(this);
  12714. }, n.prototype.Uo = function() {
  12715. this.Jo && this.Xo([]);
  12716. }, n.prototype.jo = function(t, e) {
  12717. return this.connection.wo("Write", t, e);
  12718. }, n.prototype.onMessage = function(t) {
  12719. if (
  12720. // Always capture the last stream token.
  12721. U(!!t.streamToken), this.lastStreamToken = t.streamToken, this.Jo) {
  12722. // A successful first write response means the stream is healthy,
  12723. // Note, that we could consider a successful handshake healthy, however,
  12724. // the write itself might be causing an error we want to back off from.
  12725. this.xo.reset();
  12726. var e = function(t, e) {
  12727. return t && t.length > 0 ? (U(void 0 !== e), t.map((function(t) {
  12728. return function(t, e) {
  12729. // NOTE: Deletes don't have an updateTime.
  12730. var n = t.updateTime ? jr(t.updateTime) : jr(e);
  12731. return n.isEqual(at.min()) && (
  12732. // The Firestore Emulator currently returns an update time of 0 for
  12733. // deletes of non-existing documents (rather than null). This breaks the
  12734. // test "get deleted doc while offline with source=cache" as NoDocuments
  12735. // with version 0 are filtered by IndexedDb's RemoteDocumentCache.
  12736. // TODO(#2149): Remove this when Emulator is fixed
  12737. n = jr(e)), new Wn(n, t.transformResults || []);
  12738. }(t, e);
  12739. }))) : [];
  12740. }(t.writeResults, t.commitTime), n = jr(t.commitTime);
  12741. return this.listener.Zo(n, e);
  12742. }
  12743. // The first response is always the handshake response
  12744. return U(!t.writeResults || 0 === t.writeResults.length), this.Jo = !0,
  12745. this.listener.tu();
  12746. },
  12747. /**
  12748. * Sends an initial streamToken to the server, performing the handshake
  12749. * required to make the StreamingWrite RPC work. Subsequent
  12750. * calls should wait until onHandshakeComplete was called.
  12751. */
  12752. n.prototype.eu = function() {
  12753. // TODO(dimond): Support stream resumption. We intentionally do not set the
  12754. // stream token on the handshake, ignoring any stream token we might have.
  12755. var t = {};
  12756. t.database = Zr(this.yt), this.Bo(t);
  12757. },
  12758. /** Sends a group of mutations to the Firestore backend to apply. */ n.prototype.Xo = function(t) {
  12759. var e = this, n = {
  12760. streamToken: this.lastStreamToken,
  12761. writes: t.map((function(t) {
  12762. return ei(e.yt, t);
  12763. }))
  12764. };
  12765. this.Bo(n);
  12766. }, n;
  12767. }(wa), Ta = /** @class */ function(e) {
  12768. function n(t, n, r, i) {
  12769. var o = this;
  12770. return (o = e.call(this) || this).authCredentials = t, o.appCheckCredentials = n,
  12771. o.connection = r, o.yt = i, o.nu = !1, o;
  12772. }
  12773. return t(n, e), n.prototype.su = function() {
  12774. if (this.nu) throw new j(K.FAILED_PRECONDITION, "The client has already been terminated.");
  12775. },
  12776. /** Invokes the provided RPC with auth and AppCheck tokens. */ n.prototype.ao = function(t, e, n) {
  12777. var r = this;
  12778. return this.su(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((function(i) {
  12779. var o = i[0], u = i[1];
  12780. return r.connection.ao(t, e, n, o, u);
  12781. })).catch((function(t) {
  12782. throw "FirebaseError" === t.name ? (t.code === K.UNAUTHENTICATED && (r.authCredentials.invalidateToken(),
  12783. r.appCheckCredentials.invalidateToken()), t) : new j(K.UNKNOWN, t.toString());
  12784. }));
  12785. },
  12786. /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ n.prototype._o = function(t, e, n, r) {
  12787. var i = this;
  12788. return this.su(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((function(o) {
  12789. var u = o[0], a = o[1];
  12790. return i.connection._o(t, e, n, u, a, r);
  12791. })).catch((function(t) {
  12792. throw "FirebaseError" === t.name ? (t.code === K.UNAUTHENTICATED && (i.authCredentials.invalidateToken(),
  12793. i.appCheckCredentials.invalidateToken()), t) : new j(K.UNKNOWN, t.toString());
  12794. }));
  12795. }, n.prototype.terminate = function() {
  12796. this.nu = !0;
  12797. }, n;
  12798. }((function() {}));
  12799. /**
  12800. * @license
  12801. * Copyright 2017 Google LLC
  12802. *
  12803. * Licensed under the Apache License, Version 2.0 (the "License");
  12804. * you may not use this file except in compliance with the License.
  12805. * You may obtain a copy of the License at
  12806. *
  12807. * http://www.apache.org/licenses/LICENSE-2.0
  12808. *
  12809. * Unless required by applicable law or agreed to in writing, software
  12810. * distributed under the License is distributed on an "AS IS" BASIS,
  12811. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12812. * See the License for the specific language governing permissions and
  12813. * limitations under the License.
  12814. */
  12815. /**
  12816. * A PersistentStream is an abstract base class that represents a streaming RPC
  12817. * to the Firestore backend. It's built on top of the connections own support
  12818. * for streaming RPCs, and adds several critical features for our clients:
  12819. *
  12820. * - Exponential backoff on failure
  12821. * - Authentication via CredentialsProvider
  12822. * - Dispatching all callbacks into the shared worker queue
  12823. * - Closing idle streams after 60 seconds of inactivity
  12824. *
  12825. * Subclasses of PersistentStream implement serialization of models to and
  12826. * from the JSON representation of the protocol buffers for a specific
  12827. * streaming RPC.
  12828. *
  12829. * ## Starting and Stopping
  12830. *
  12831. * Streaming RPCs are stateful and need to be start()ed before messages can
  12832. * be sent and received. The PersistentStream will call the onOpen() function
  12833. * of the listener once the stream is ready to accept requests.
  12834. *
  12835. * Should a start() fail, PersistentStream will call the registered onClose()
  12836. * listener with a FirestoreError indicating what went wrong.
  12837. *
  12838. * A PersistentStream can be started and stopped repeatedly.
  12839. *
  12840. * Generic types:
  12841. * SendType: The type of the outgoing message of the underlying
  12842. * connection stream
  12843. * ReceiveType: The type of the incoming message of the underlying
  12844. * connection stream
  12845. * ListenerType: The type of the listener that will be used for callbacks
  12846. */
  12847. /**
  12848. * A component used by the RemoteStore to track the OnlineState (that is,
  12849. * whether or not the client as a whole should be considered to be online or
  12850. * offline), implementing the appropriate heuristics.
  12851. *
  12852. * In particular, when the client is trying to connect to the backend, we
  12853. * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for
  12854. * a connection to succeed. If we have too many failures or the timeout elapses,
  12855. * then we set the OnlineState to Offline, and the client will behave as if
  12856. * it is offline (get()s will return cached data, etc.).
  12857. */
  12858. var Ea = /** @class */ function() {
  12859. function t(t, e) {
  12860. this.asyncQueue = t, this.onlineStateHandler = e,
  12861. /** The current OnlineState. */
  12862. this.state = "Unknown" /* OnlineState.Unknown */ ,
  12863. /**
  12864. * A count of consecutive failures to open the stream. If it reaches the
  12865. * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to
  12866. * Offline.
  12867. */
  12868. this.iu = 0,
  12869. /**
  12870. * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we
  12871. * transition from OnlineState.Unknown to OnlineState.Offline without waiting
  12872. * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).
  12873. */
  12874. this.ru = null,
  12875. /**
  12876. * Whether the client should log a warning message if it fails to connect to
  12877. * the backend (initially true, cleared after a successful stream, or if we've
  12878. * logged the message already).
  12879. */
  12880. this.ou = !0
  12881. /**
  12882. * Called by RemoteStore when a watch stream is started (including on each
  12883. * backoff attempt).
  12884. *
  12885. * If this is the first attempt, it sets the OnlineState to Unknown and starts
  12886. * the onlineStateTimer.
  12887. */;
  12888. }
  12889. return t.prototype.uu = function() {
  12890. var t = this;
  12891. 0 === this.iu && (this.cu("Unknown" /* OnlineState.Unknown */), this.ru = this.asyncQueue.enqueueAfterDelay("online_state_timeout" /* TimerId.OnlineStateTimeout */ , 1e4, (function() {
  12892. return t.ru = null, t.au("Backend didn't respond within 10 seconds."), t.cu("Offline" /* OnlineState.Offline */),
  12893. Promise.resolve();
  12894. })));
  12895. },
  12896. /**
  12897. * Updates our OnlineState as appropriate after the watch stream reports a
  12898. * failure. The first failure moves us to the 'Unknown' state. We then may
  12899. * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we
  12900. * actually transition to the 'Offline' state.
  12901. */
  12902. t.prototype.hu = function(t) {
  12903. "Online" /* OnlineState.Online */ === this.state ? this.cu("Unknown" /* OnlineState.Unknown */) : (this.iu++,
  12904. this.iu >= 1 && (this.lu(), this.au("Connection failed 1 times. Most recent error: ".concat(t.toString())),
  12905. this.cu("Offline" /* OnlineState.Offline */)));
  12906. },
  12907. /**
  12908. * Explicitly sets the OnlineState to the specified state.
  12909. *
  12910. * Note that this resets our timers / failure counters, etc. used by our
  12911. * Offline heuristics, so must not be used in place of
  12912. * handleWatchStreamStart() and handleWatchStreamFailure().
  12913. */
  12914. t.prototype.set = function(t) {
  12915. this.lu(), this.iu = 0, "Online" /* OnlineState.Online */ === t && (
  12916. // We've connected to watch at least once. Don't warn the developer
  12917. // about being offline going forward.
  12918. this.ou = !1), this.cu(t);
  12919. }, t.prototype.cu = function(t) {
  12920. t !== this.state && (this.state = t, this.onlineStateHandler(t));
  12921. }, t.prototype.au = function(t) {
  12922. var e = "Could not reach Cloud Firestore backend. ".concat(t, "\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.");
  12923. this.ou ? (M(e), this.ou = !1) : V("OnlineStateTracker", e);
  12924. }, t.prototype.lu = function() {
  12925. null !== this.ru && (this.ru.cancel(), this.ru = null);
  12926. }, t;
  12927. }(), Sa = function(
  12928. /**
  12929. * The local store, used to fill the write pipeline with outbound mutations.
  12930. */
  12931. t,
  12932. /** The client-side proxy for interacting with the backend. */
  12933. r, i, o, u) {
  12934. var a = this;
  12935. this.localStore = t, this.datastore = r, this.asyncQueue = i, this.remoteSyncer = {},
  12936. /**
  12937. * A list of up to MAX_PENDING_WRITES writes that we have fetched from the
  12938. * LocalStore via fillWritePipeline() and have or will send to the write
  12939. * stream.
  12940. *
  12941. * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or
  12942. * restart the write stream. When the stream is established the writes in the
  12943. * pipeline will be sent in order.
  12944. *
  12945. * Writes remain in writePipeline until they are acknowledged by the backend
  12946. * and thus will automatically be re-sent if the stream is interrupted /
  12947. * restarted before they're acknowledged.
  12948. *
  12949. * Write responses from the backend are linked to their originating request
  12950. * purely based on order, and so we can just shift() writes from the front of
  12951. * the writePipeline as we receive responses.
  12952. */
  12953. this.fu = [],
  12954. /**
  12955. * A mapping of watched targets that the client cares about tracking and the
  12956. * user has explicitly called a 'listen' for this target.
  12957. *
  12958. * These targets may or may not have been sent to or acknowledged by the
  12959. * server. On re-establishing the listen stream, these targets should be sent
  12960. * to the server. The targets removed with unlistens are removed eagerly
  12961. * without waiting for confirmation from the listen stream.
  12962. */
  12963. this.du = new Map,
  12964. /**
  12965. * A set of reasons for why the RemoteStore may be offline. If empty, the
  12966. * RemoteStore may start its network connections.
  12967. */
  12968. this._u = new Set,
  12969. /**
  12970. * Event handlers that get called when the network is disabled or enabled.
  12971. *
  12972. * PORTING NOTE: These functions are used on the Web client to create the
  12973. * underlying streams (to support tree-shakeable streams). On Android and iOS,
  12974. * the streams are created during construction of RemoteStore.
  12975. */
  12976. this.wu = [], this.mu = u, this.mu.Ur((function(t) {
  12977. i.enqueueAndForget((function() {
  12978. return e(a, void 0, void 0, (function() {
  12979. return n(this, (function(t) {
  12980. switch (t.label) {
  12981. case 0:
  12982. return Oa(this) ? (V("RemoteStore", "Restarting streams for network reachability change."),
  12983. [ 4 /*yield*/ , function(t) {
  12984. return e(this, void 0, void 0, (function() {
  12985. var e;
  12986. return n(this, (function(n) {
  12987. switch (n.label) {
  12988. case 0:
  12989. return (e = G(t))._u.add(4 /* OfflineCause.ConnectivityChange */), [ 4 /*yield*/ , Da(e) ];
  12990. case 1:
  12991. return n.sent(), e.gu.set("Unknown" /* OnlineState.Unknown */), e._u.delete(4 /* OfflineCause.ConnectivityChange */),
  12992. [ 4 /*yield*/ , _a(e) ];
  12993. case 2:
  12994. return n.sent(), [ 2 /*return*/ ];
  12995. }
  12996. }));
  12997. }));
  12998. }(this) ]) : [ 3 /*break*/ , 2 ];
  12999. case 1:
  13000. t.sent(), t.label = 2;
  13001. case 2:
  13002. return [ 2 /*return*/ ];
  13003. }
  13004. }));
  13005. }));
  13006. }));
  13007. })), this.gu = new Ea(i, o);
  13008. };
  13009. /**
  13010. * @license
  13011. * Copyright 2017 Google LLC
  13012. *
  13013. * Licensed under the Apache License, Version 2.0 (the "License");
  13014. * you may not use this file except in compliance with the License.
  13015. * You may obtain a copy of the License at
  13016. *
  13017. * http://www.apache.org/licenses/LICENSE-2.0
  13018. *
  13019. * Unless required by applicable law or agreed to in writing, software
  13020. * distributed under the License is distributed on an "AS IS" BASIS,
  13021. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13022. * See the License for the specific language governing permissions and
  13023. * limitations under the License.
  13024. */ function _a(t) {
  13025. return e(this, void 0, void 0, (function() {
  13026. var e, r;
  13027. return n(this, (function(n) {
  13028. switch (n.label) {
  13029. case 0:
  13030. if (!Oa(t)) return [ 3 /*break*/ , 4 ];
  13031. e = 0, r = t.wu, n.label = 1;
  13032. case 1:
  13033. return e < r.length ? [ 4 /*yield*/ , (0, r[e])(/* enabled= */ !0) ] : [ 3 /*break*/ , 4 ];
  13034. case 2:
  13035. n.sent(), n.label = 3;
  13036. case 3:
  13037. return e++, [ 3 /*break*/ , 1 ];
  13038. case 4:
  13039. return [ 2 /*return*/ ];
  13040. }
  13041. }));
  13042. }));
  13043. }
  13044. /**
  13045. * Temporarily disables the network. The network can be re-enabled using
  13046. * enableNetwork().
  13047. */ function Da(t) {
  13048. return e(this, void 0, void 0, (function() {
  13049. var e, r;
  13050. return n(this, (function(n) {
  13051. switch (n.label) {
  13052. case 0:
  13053. e = 0, r = t.wu, n.label = 1;
  13054. case 1:
  13055. return e < r.length ? [ 4 /*yield*/ , (0, r[e])(/* enabled= */ !1) ] : [ 3 /*break*/ , 4 ];
  13056. case 2:
  13057. n.sent(), n.label = 3;
  13058. case 3:
  13059. return e++, [ 3 /*break*/ , 1 ];
  13060. case 4:
  13061. return [ 2 /*return*/ ];
  13062. }
  13063. }));
  13064. }));
  13065. }
  13066. /**
  13067. * Starts new listen for the given target. Uses resume token if provided. It
  13068. * is a no-op if the target of given `TargetData` is already being listened to.
  13069. */ function xa(t, e) {
  13070. var n = G(t);
  13071. n.du.has(e.targetId) || (
  13072. // Mark this as something the client is currently listening for.
  13073. n.du.set(e.targetId, e), Fa(n) ?
  13074. // The listen will be sent in onWatchStreamOpen
  13075. ka(n) : Ya(n).ko() && Ca(n, e));
  13076. }
  13077. /**
  13078. * Removes the listen from server. It is a no-op if the given target id is
  13079. * not being listened to.
  13080. */ function Aa(t, e) {
  13081. var n = G(t), r = Ya(n);
  13082. n.du.delete(e), r.ko() && Na(n, e), 0 === n.du.size && (r.ko() ? r.Fo() : Oa(n) &&
  13083. // Revert to OnlineState.Unknown if the watch stream is not open and we
  13084. // have no listeners, since without any listens to send we cannot
  13085. // confirm if the stream is healthy and upgrade to OnlineState.Online.
  13086. n.gu.set("Unknown" /* OnlineState.Unknown */));
  13087. }
  13088. /**
  13089. * We need to increment the the expected number of pending responses we're due
  13090. * from watch so we wait for the ack to process any messages from this target.
  13091. */ function Ca(t, e) {
  13092. t.yu.Ot(e.targetId), Ya(t).zo(e)
  13093. /**
  13094. * We need to increment the expected number of pending responses we're due
  13095. * from watch so we wait for the removal on the server before we process any
  13096. * messages from this target.
  13097. */;
  13098. }
  13099. function Na(t, e) {
  13100. t.yu.Ot(e), Ya(t).Ho(e);
  13101. }
  13102. function ka(t) {
  13103. t.yu = new Rr({
  13104. getRemoteKeysForTarget: function(e) {
  13105. return t.remoteSyncer.getRemoteKeysForTarget(e);
  13106. },
  13107. ne: function(e) {
  13108. return t.du.get(e) || null;
  13109. }
  13110. }), Ya(t).start(), t.gu.uu()
  13111. /**
  13112. * Returns whether the watch stream should be started because it's necessary
  13113. * and has not yet been started.
  13114. */;
  13115. }
  13116. function Fa(t) {
  13117. return Oa(t) && !Ya(t).No() && t.du.size > 0;
  13118. }
  13119. function Oa(t) {
  13120. return 0 === G(t)._u.size;
  13121. }
  13122. function Ra(t) {
  13123. t.yu = void 0;
  13124. }
  13125. function Va(t) {
  13126. return e(this, void 0, void 0, (function() {
  13127. return n(this, (function(e) {
  13128. return t.du.forEach((function(e, n) {
  13129. Ca(t, e);
  13130. })), [ 2 /*return*/ ];
  13131. }));
  13132. }));
  13133. }
  13134. function Ma(t, r) {
  13135. return e(this, void 0, void 0, (function() {
  13136. return n(this, (function(e) {
  13137. return Ra(t),
  13138. // If we still need the watch stream, retry the connection.
  13139. Fa(t) ? (t.gu.hu(r), ka(t)) :
  13140. // No need to restart watch stream because there are no active targets.
  13141. // The online state is set to unknown because there is no active attempt
  13142. // at establishing a connection
  13143. t.gu.set("Unknown" /* OnlineState.Unknown */), [ 2 /*return*/ ];
  13144. }));
  13145. }));
  13146. }
  13147. function La(t, r, i) {
  13148. return e(this, void 0, void 0, (function() {
  13149. var o, u, a;
  13150. return n(this, (function(s) {
  13151. switch (s.label) {
  13152. case 0:
  13153. if (t.gu.set("Online" /* OnlineState.Online */), !(r instanceof Fr && 2 /* WatchTargetChangeState.Removed */ === r.state && r.cause))
  13154. // Mark the client as online since we got a message from the server
  13155. return [ 3 /*break*/ , 6 ];
  13156. s.label = 1;
  13157. case 1:
  13158. return s.trys.push([ 1, 3, , 5 ]), [ 4 /*yield*/ ,
  13159. /** Handles an error on a target */
  13160. function(t, r) {
  13161. return e(this, void 0, void 0, (function() {
  13162. var e, i, o, u;
  13163. return n(this, (function(n) {
  13164. switch (n.label) {
  13165. case 0:
  13166. e = r.cause, i = 0, o = r.targetIds, n.label = 1;
  13167. case 1:
  13168. return i < o.length ? (u = o[i], t.du.has(u) ? [ 4 /*yield*/ , t.remoteSyncer.rejectListen(u, e) ] : [ 3 /*break*/ , 3 ]) : [ 3 /*break*/ , 5 ];
  13169. case 2:
  13170. n.sent(), t.du.delete(u), t.yu.removeTarget(u), n.label = 3;
  13171. case 3:
  13172. n.label = 4;
  13173. case 4:
  13174. return i++, [ 3 /*break*/ , 1 ];
  13175. case 5:
  13176. return [ 2 /*return*/ ];
  13177. }
  13178. }));
  13179. }));
  13180. }(t, r) ];
  13181. case 2:
  13182. return s.sent(), [ 3 /*break*/ , 5 ];
  13183. case 3:
  13184. return o = s.sent(), V("RemoteStore", "Failed to remove targets %s: %s ", r.targetIds.join(","), o),
  13185. [ 4 /*yield*/ , Pa(t, o) ];
  13186. case 4:
  13187. return s.sent(), [ 3 /*break*/ , 5 ];
  13188. case 5:
  13189. return [ 3 /*break*/ , 13 ];
  13190. case 6:
  13191. if (r instanceof Nr ? t.yu.Kt(r) : r instanceof kr ? t.yu.Jt(r) : t.yu.jt(r), i.isEqual(at.min())) return [ 3 /*break*/ , 13 ];
  13192. s.label = 7;
  13193. case 7:
  13194. return s.trys.push([ 7, 11, , 13 ]), [ 4 /*yield*/ , Gu(t.localStore) ];
  13195. case 8:
  13196. return u = s.sent(), i.compareTo(u) >= 0 ? [ 4 /*yield*/ ,
  13197. /**
  13198. * Takes a batch of changes from the Datastore, repackages them as a
  13199. * RemoteEvent, and passes that on to the listener, which is typically the
  13200. * SyncEngine.
  13201. */
  13202. function(t, e) {
  13203. var n = t.yu.Zt(e);
  13204. // Update in-memory resume tokens. LocalStore will update the
  13205. // persistent view of these when applying the completed RemoteEvent.
  13206. return n.targetChanges.forEach((function(n, r) {
  13207. if (n.resumeToken.approximateByteSize() > 0) {
  13208. var i = t.du.get(r);
  13209. // A watched target might have been removed already.
  13210. i && t.du.set(r, i.withResumeToken(n.resumeToken, e));
  13211. }
  13212. })),
  13213. // Re-establish listens for the targets that have been invalidated by
  13214. // existence filter mismatches.
  13215. n.targetMismatches.forEach((function(e) {
  13216. var n = t.du.get(e);
  13217. if (n) {
  13218. // Clear the resume token for the target, since we're in a known mismatch
  13219. // state.
  13220. t.du.set(e, n.withResumeToken(Yt.EMPTY_BYTE_STRING, n.snapshotVersion)),
  13221. // Cause a hard reset by unwatching and rewatching immediately, but
  13222. // deliberately don't send a resume token so that we get a full update.
  13223. Na(t, e);
  13224. // Mark the target we send as being on behalf of an existence filter
  13225. // mismatch, but don't actually retain that in listenTargets. This ensures
  13226. // that we flag the first re-listen this way without impacting future
  13227. // listens of this target (that might happen e.g. on reconnect).
  13228. var r = new Wi(n.target, e, 1 /* TargetPurpose.ExistenceFilterMismatch */ , n.sequenceNumber);
  13229. Ca(t, r);
  13230. }
  13231. })), t.remoteSyncer.applyRemoteEvent(n);
  13232. }(t, i) ] : [ 3 /*break*/ , 10 ];
  13233. // We have received a target change with a global snapshot if the snapshot
  13234. // version is not equal to SnapshotVersion.min().
  13235. case 9:
  13236. // We have received a target change with a global snapshot if the snapshot
  13237. // version is not equal to SnapshotVersion.min().
  13238. s.sent(), s.label = 10;
  13239. case 10:
  13240. return [ 3 /*break*/ , 13 ];
  13241. case 11:
  13242. return V("RemoteStore", "Failed to raise snapshot:", a = s.sent()), [ 4 /*yield*/ , Pa(t, a) ];
  13243. case 12:
  13244. return s.sent(), [ 3 /*break*/ , 13 ];
  13245. case 13:
  13246. return [ 2 /*return*/ ];
  13247. }
  13248. }));
  13249. }));
  13250. }
  13251. /**
  13252. * Recovery logic for IndexedDB errors that takes the network offline until
  13253. * `op` succeeds. Retries are scheduled with backoff using
  13254. * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is
  13255. * validated via a generic operation.
  13256. *
  13257. * The returned Promise is resolved once the network is disabled and before
  13258. * any retry attempt.
  13259. */ function Pa(t, r, i) {
  13260. return e(this, void 0, void 0, (function() {
  13261. var o = this;
  13262. return n(this, (function(u) {
  13263. switch (u.label) {
  13264. case 0:
  13265. if (!Ft(r)) throw r;
  13266. // Disable network and raise offline snapshots
  13267. return t._u.add(1 /* OfflineCause.IndexedDbFailed */), [ 4 /*yield*/ , Da(t) ];
  13268. case 1:
  13269. // Disable network and raise offline snapshots
  13270. return u.sent(), t.gu.set("Offline" /* OnlineState.Offline */), i || (
  13271. // Use a simple read operation to determine if IndexedDB recovered.
  13272. // Ideally, we would expose a health check directly on SimpleDb, but
  13273. // RemoteStore only has access to persistence through LocalStore.
  13274. i = function() {
  13275. return Gu(t.localStore);
  13276. }),
  13277. // Probe IndexedDB periodically and re-enable network
  13278. t.asyncQueue.enqueueRetryable((function() {
  13279. return e(o, void 0, void 0, (function() {
  13280. return n(this, (function(e) {
  13281. switch (e.label) {
  13282. case 0:
  13283. return V("RemoteStore", "Retrying IndexedDB access"), [ 4 /*yield*/ , i() ];
  13284. case 1:
  13285. return e.sent(), t._u.delete(1 /* OfflineCause.IndexedDbFailed */), [ 4 /*yield*/ , _a(t) ];
  13286. case 2:
  13287. return e.sent(), [ 2 /*return*/ ];
  13288. }
  13289. }));
  13290. }));
  13291. })), [ 2 /*return*/ ];
  13292. }
  13293. }));
  13294. }));
  13295. }
  13296. /**
  13297. * Executes `op`. If `op` fails, takes the network offline until `op`
  13298. * succeeds. Returns after the first attempt.
  13299. */ function qa(t, e) {
  13300. return e().catch((function(n) {
  13301. return Pa(t, n, e);
  13302. }));
  13303. }
  13304. function Ua(t) {
  13305. return e(this, void 0, void 0, (function() {
  13306. var e, r, i, o, u;
  13307. return n(this, (function(n) {
  13308. switch (n.label) {
  13309. case 0:
  13310. e = G(t), r = Xa(e), i = e.fu.length > 0 ? e.fu[e.fu.length - 1].batchId : -1, n.label = 1;
  13311. case 1:
  13312. if (!
  13313. /**
  13314. * Returns true if we can add to the write pipeline (i.e. the network is
  13315. * enabled and the write pipeline is not full).
  13316. */
  13317. function(t) {
  13318. return Oa(t) && t.fu.length < 10;
  13319. }
  13320. /**
  13321. * Queues additional writes to be sent to the write stream, sending them
  13322. * immediately if the write stream is established.
  13323. */ (e)) return [ 3 /*break*/ , 7 ];
  13324. n.label = 2;
  13325. case 2:
  13326. return n.trys.push([ 2, 4, , 6 ]), [ 4 /*yield*/ , Qu(e.localStore, i) ];
  13327. case 3:
  13328. return null === (o = n.sent()) ? (0 === e.fu.length && r.Fo(), [ 3 /*break*/ , 7 ]) : (i = o.batchId,
  13329. function(t, e) {
  13330. t.fu.push(e);
  13331. var n = Xa(t);
  13332. n.ko() && n.Yo && n.Xo(e.mutations);
  13333. }(e, o), [ 3 /*break*/ , 6 ]);
  13334. case 4:
  13335. return u = n.sent(), [ 4 /*yield*/ , Pa(e, u) ];
  13336. case 5:
  13337. return n.sent(), [ 3 /*break*/ , 6 ];
  13338. case 6:
  13339. return [ 3 /*break*/ , 1 ];
  13340. case 7:
  13341. return Ba(e) && Ga(e), [ 2 /*return*/ ];
  13342. }
  13343. }));
  13344. }));
  13345. }
  13346. function Ba(t) {
  13347. return Oa(t) && !Xa(t).No() && t.fu.length > 0;
  13348. }
  13349. function Ga(t) {
  13350. Xa(t).start();
  13351. }
  13352. function Ka(t) {
  13353. return e(this, void 0, void 0, (function() {
  13354. return n(this, (function(e) {
  13355. return Xa(t).eu(), [ 2 /*return*/ ];
  13356. }));
  13357. }));
  13358. }
  13359. function ja(t) {
  13360. return e(this, void 0, void 0, (function() {
  13361. var e, r, i, o;
  13362. return n(this, (function(n) {
  13363. // Send the write pipeline now that the stream is established.
  13364. for (e = Xa(t), r = 0, i = t.fu; r < i.length; r++) o = i[r], e.Xo(o.mutations);
  13365. return [ 2 /*return*/ ];
  13366. }));
  13367. }));
  13368. }
  13369. function Qa(t, r, i) {
  13370. return e(this, void 0, void 0, (function() {
  13371. var e, o;
  13372. return n(this, (function(n) {
  13373. switch (n.label) {
  13374. case 0:
  13375. return e = t.fu.shift(), o = Qi.from(e, r, i), [ 4 /*yield*/ , qa(t, (function() {
  13376. return t.remoteSyncer.applySuccessfulWrite(o);
  13377. })) ];
  13378. case 1:
  13379. // It's possible that with the completion of this mutation another
  13380. // slot has freed up.
  13381. return n.sent(), [ 4 /*yield*/ , Ua(t) ];
  13382. case 2:
  13383. // It's possible that with the completion of this mutation another
  13384. // slot has freed up.
  13385. return n.sent(), [ 2 /*return*/ ];
  13386. }
  13387. }));
  13388. }));
  13389. }
  13390. function za(t, r) {
  13391. return e(this, void 0, void 0, (function() {
  13392. return n(this, (function(i) {
  13393. switch (i.label) {
  13394. case 0:
  13395. return r && Xa(t).Yo ? [ 4 /*yield*/ , function(t, r) {
  13396. return e(this, void 0, void 0, (function() {
  13397. var e, i;
  13398. return n(this, (function(n) {
  13399. switch (n.label) {
  13400. case 0:
  13401. return fr(i = r.code) && i !== K.ABORTED ? (e = t.fu.shift(),
  13402. // In this case it's also unlikely that the server itself is melting
  13403. // down -- this was just a bad request so inhibit backoff on the next
  13404. // restart.
  13405. Xa(t).Mo(), [ 4 /*yield*/ , qa(t, (function() {
  13406. return t.remoteSyncer.rejectFailedWrite(e.batchId, r);
  13407. })) ]) : [ 3 /*break*/ , 3 ];
  13408. case 1:
  13409. // It's possible that with the completion of this mutation
  13410. // another slot has freed up.
  13411. return n.sent(), [ 4 /*yield*/ , Ua(t) ];
  13412. case 2:
  13413. // In this case it's also unlikely that the server itself is melting
  13414. // down -- this was just a bad request so inhibit backoff on the next
  13415. // restart.
  13416. // It's possible that with the completion of this mutation
  13417. // another slot has freed up.
  13418. n.sent(), n.label = 3;
  13419. case 3:
  13420. return [ 2 /*return*/ ];
  13421. }
  13422. }));
  13423. }));
  13424. }(t, r) ] : [ 3 /*break*/ , 2 ];
  13425. // This error affects the actual write.
  13426. case 1:
  13427. // This error affects the actual write.
  13428. i.sent(), i.label = 2;
  13429. case 2:
  13430. // If the write stream closed after the write handshake completes, a write
  13431. // operation failed and we fail the pending operation.
  13432. // The write stream might have been started by refilling the write
  13433. // pipeline for failed writes
  13434. return Ba(t) && Ga(t), [ 2 /*return*/ ];
  13435. }
  13436. }));
  13437. }));
  13438. }
  13439. function Wa(t, r) {
  13440. return e(this, void 0, void 0, (function() {
  13441. var e, i;
  13442. return n(this, (function(n) {
  13443. switch (n.label) {
  13444. case 0:
  13445. return (e = G(t)).asyncQueue.verifyOperationInProgress(), V("RemoteStore", "RemoteStore received new credentials"),
  13446. i = Oa(e),
  13447. // Tear down and re-create our network streams. This will ensure we get a
  13448. // fresh auth token for the new user and re-fill the write pipeline with
  13449. // new mutations from the LocalStore (since mutations are per-user).
  13450. e._u.add(3 /* OfflineCause.CredentialChange */), [ 4 /*yield*/ , Da(e) ];
  13451. case 1:
  13452. return n.sent(), i &&
  13453. // Don't set the network status to Unknown if we are offline.
  13454. e.gu.set("Unknown" /* OnlineState.Unknown */), [ 4 /*yield*/ , e.remoteSyncer.handleCredentialChange(r) ];
  13455. case 2:
  13456. return n.sent(), e._u.delete(3 /* OfflineCause.CredentialChange */), [ 4 /*yield*/ , _a(e) ];
  13457. case 3:
  13458. // Tear down and re-create our network streams. This will ensure we get a
  13459. // fresh auth token for the new user and re-fill the write pipeline with
  13460. // new mutations from the LocalStore (since mutations are per-user).
  13461. return n.sent(), [ 2 /*return*/ ];
  13462. }
  13463. }));
  13464. }));
  13465. }
  13466. /**
  13467. * Toggles the network state when the client gains or loses its primary lease.
  13468. */ function Ha(t, r) {
  13469. return e(this, void 0, void 0, (function() {
  13470. var e;
  13471. return n(this, (function(n) {
  13472. switch (n.label) {
  13473. case 0:
  13474. return e = G(t), r ? (e._u.delete(2 /* OfflineCause.IsSecondary */), [ 4 /*yield*/ , _a(e) ]) : [ 3 /*break*/ , 2 ];
  13475. case 1:
  13476. return n.sent(), [ 3 /*break*/ , 5 ];
  13477. case 2:
  13478. return r ? [ 3 /*break*/ , 4 ] : (e._u.add(2 /* OfflineCause.IsSecondary */), [ 4 /*yield*/ , Da(e) ]);
  13479. case 3:
  13480. n.sent(), e.gu.set("Unknown" /* OnlineState.Unknown */), n.label = 4;
  13481. case 4:
  13482. n.label = 5;
  13483. case 5:
  13484. return [ 2 /*return*/ ];
  13485. }
  13486. }));
  13487. }));
  13488. }
  13489. /**
  13490. * If not yet initialized, registers the WatchStream and its network state
  13491. * callback with `remoteStoreImpl`. Returns the existing stream if one is
  13492. * already available.
  13493. *
  13494. * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.
  13495. * This is not done on Web to allow it to be tree-shaken.
  13496. */ function Ya(t) {
  13497. var r = this;
  13498. return t.pu || (
  13499. // Create stream (but note that it is not started yet).
  13500. t.pu = function(t, e, n) {
  13501. var r = G(t);
  13502. return r.su(), new ba(e, r.connection, r.authCredentials, r.appCheckCredentials, r.yt, n);
  13503. }(t.datastore, t.asyncQueue, {
  13504. Yr: Va.bind(null, t),
  13505. Zr: Ma.bind(null, t),
  13506. Wo: La.bind(null, t)
  13507. }), t.wu.push((function(i) {
  13508. return e(r, void 0, void 0, (function() {
  13509. return n(this, (function(e) {
  13510. switch (e.label) {
  13511. case 0:
  13512. return i ? (t.pu.Mo(), Fa(t) ? ka(t) : t.gu.set("Unknown" /* OnlineState.Unknown */),
  13513. [ 3 /*break*/ , 3 ]) : [ 3 /*break*/ , 1 ];
  13514. case 1:
  13515. return [ 4 /*yield*/ , t.pu.stop() ];
  13516. case 2:
  13517. e.sent(), Ra(t), e.label = 3;
  13518. case 3:
  13519. return [ 2 /*return*/ ];
  13520. }
  13521. }));
  13522. }));
  13523. }))), t.pu
  13524. /**
  13525. * If not yet initialized, registers the WriteStream and its network state
  13526. * callback with `remoteStoreImpl`. Returns the existing stream if one is
  13527. * already available.
  13528. *
  13529. * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.
  13530. * This is not done on Web to allow it to be tree-shaken.
  13531. */;
  13532. }
  13533. function Xa(t) {
  13534. var r = this;
  13535. return t.Iu || (
  13536. // Create stream (but note that it is not started yet).
  13537. t.Iu = function(t, e, n) {
  13538. var r = G(t);
  13539. return r.su(), new Ia(e, r.connection, r.authCredentials, r.appCheckCredentials, r.yt, n);
  13540. }(t.datastore, t.asyncQueue, {
  13541. Yr: Ka.bind(null, t),
  13542. Zr: za.bind(null, t),
  13543. tu: ja.bind(null, t),
  13544. Zo: Qa.bind(null, t)
  13545. }), t.wu.push((function(i) {
  13546. return e(r, void 0, void 0, (function() {
  13547. return n(this, (function(e) {
  13548. switch (e.label) {
  13549. case 0:
  13550. return i ? (t.Iu.Mo(), [ 4 /*yield*/ , Ua(t) ]) : [ 3 /*break*/ , 2 ];
  13551. case 1:
  13552. // This will start the write stream if necessary.
  13553. return e.sent(), [ 3 /*break*/ , 4 ];
  13554. case 2:
  13555. return [ 4 /*yield*/ , t.Iu.stop() ];
  13556. case 3:
  13557. e.sent(), t.fu.length > 0 && (V("RemoteStore", "Stopping write stream with ".concat(t.fu.length, " pending writes")),
  13558. t.fu = []), e.label = 4;
  13559. case 4:
  13560. return [ 2 /*return*/ ];
  13561. }
  13562. }));
  13563. }));
  13564. }))), t.Iu
  13565. /**
  13566. * @license
  13567. * Copyright 2017 Google LLC
  13568. *
  13569. * Licensed under the Apache License, Version 2.0 (the "License");
  13570. * you may not use this file except in compliance with the License.
  13571. * You may obtain a copy of the License at
  13572. *
  13573. * http://www.apache.org/licenses/LICENSE-2.0
  13574. *
  13575. * Unless required by applicable law or agreed to in writing, software
  13576. * distributed under the License is distributed on an "AS IS" BASIS,
  13577. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13578. * See the License for the specific language governing permissions and
  13579. * limitations under the License.
  13580. */
  13581. /**
  13582. * Represents an operation scheduled to be run in the future on an AsyncQueue.
  13583. *
  13584. * It is created via DelayedOperation.createAndSchedule().
  13585. *
  13586. * Supports cancellation (via cancel()) and early execution (via skipDelay()).
  13587. *
  13588. * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
  13589. * in newer versions of TypeScript defines `finally`, which is not available in
  13590. * IE.
  13591. */;
  13592. }
  13593. var Za = /** @class */ function() {
  13594. function t(t, e, n, r, i) {
  13595. this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = r, this.removalCallback = i,
  13596. this.deferred = new Q, this.then = this.deferred.promise.then.bind(this.deferred.promise),
  13597. // It's normal for the deferred promise to be canceled (due to cancellation)
  13598. // and so we attach a dummy catch callback to avoid
  13599. // 'UnhandledPromiseRejectionWarning' log spam.
  13600. this.deferred.promise.catch((function(t) {}))
  13601. /**
  13602. * Creates and returns a DelayedOperation that has been scheduled to be
  13603. * executed on the provided asyncQueue after the provided delayMs.
  13604. *
  13605. * @param asyncQueue - The queue to schedule the operation on.
  13606. * @param id - A Timer ID identifying the type of operation this is.
  13607. * @param delayMs - The delay (ms) before the operation should be scheduled.
  13608. * @param op - The operation to run.
  13609. * @param removalCallback - A callback to be called synchronously once the
  13610. * operation is executed or canceled, notifying the AsyncQueue to remove it
  13611. * from its delayedOperations list.
  13612. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and
  13613. * the DelayedOperation class public.
  13614. */;
  13615. }
  13616. return t.createAndSchedule = function(e, n, r, i, o) {
  13617. var u = new t(e, n, Date.now() + r, i, o);
  13618. return u.start(r), u;
  13619. },
  13620. /**
  13621. * Starts the timer. This is called immediately after construction by
  13622. * createAndSchedule().
  13623. */
  13624. t.prototype.start = function(t) {
  13625. var e = this;
  13626. this.timerHandle = setTimeout((function() {
  13627. return e.handleDelayElapsed();
  13628. }), t);
  13629. },
  13630. /**
  13631. * Queues the operation to run immediately (if it hasn't already been run or
  13632. * canceled).
  13633. */
  13634. t.prototype.skipDelay = function() {
  13635. return this.handleDelayElapsed();
  13636. },
  13637. /**
  13638. * Cancels the operation if it hasn't already been executed or canceled. The
  13639. * promise will be rejected.
  13640. *
  13641. * As long as the operation has not yet been run, calling cancel() provides a
  13642. * guarantee that the operation will not be run.
  13643. */
  13644. t.prototype.cancel = function(t) {
  13645. null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new j(K.CANCELLED, "Operation cancelled" + (t ? ": " + t : ""))));
  13646. }, t.prototype.handleDelayElapsed = function() {
  13647. var t = this;
  13648. this.asyncQueue.enqueueAndForget((function() {
  13649. return null !== t.timerHandle ? (t.clearTimeout(), t.op().then((function(e) {
  13650. return t.deferred.resolve(e);
  13651. }))) : Promise.resolve();
  13652. }));
  13653. }, t.prototype.clearTimeout = function() {
  13654. null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle),
  13655. this.timerHandle = null);
  13656. }, t;
  13657. }();
  13658. /**
  13659. * Returns a FirestoreError that can be surfaced to the user if the provided
  13660. * error is an IndexedDbTransactionError. Re-throws the error otherwise.
  13661. */ function Ja(t, e) {
  13662. if (M("AsyncQueue", "".concat(e, ": ").concat(t)), Ft(t)) return new j(K.UNAVAILABLE, "".concat(e, ": ").concat(t));
  13663. throw t;
  13664. }
  13665. /**
  13666. * @license
  13667. * Copyright 2017 Google LLC
  13668. *
  13669. * Licensed under the Apache License, Version 2.0 (the "License");
  13670. * you may not use this file except in compliance with the License.
  13671. * You may obtain a copy of the License at
  13672. *
  13673. * http://www.apache.org/licenses/LICENSE-2.0
  13674. *
  13675. * Unless required by applicable law or agreed to in writing, software
  13676. * distributed under the License is distributed on an "AS IS" BASIS,
  13677. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13678. * See the License for the specific language governing permissions and
  13679. * limitations under the License.
  13680. */
  13681. /**
  13682. * DocumentSet is an immutable (copy-on-write) collection that holds documents
  13683. * in order specified by the provided comparator. We always add a document key
  13684. * comparator on top of what is provided to guarantee document equality based on
  13685. * the key.
  13686. */ var $a = /** @class */ function() {
  13687. /** The default ordering is by key if the comparator is omitted */
  13688. function t(t) {
  13689. // We are adding document key comparator to the end as it's the only
  13690. // guaranteed unique property of a document.
  13691. this.comparator = t ? function(e, n) {
  13692. return t(e, n) || ft.comparator(e.key, n.key);
  13693. } : function(t, e) {
  13694. return ft.comparator(t.key, e.key);
  13695. }, this.keyedMap = gr(), this.sortedSet = new He(this.comparator)
  13696. /**
  13697. * Returns an empty copy of the existing DocumentSet, using the same
  13698. * comparator.
  13699. */;
  13700. }
  13701. return t.emptySet = function(e) {
  13702. return new t(e.comparator);
  13703. }, t.prototype.has = function(t) {
  13704. return null != this.keyedMap.get(t);
  13705. }, t.prototype.get = function(t) {
  13706. return this.keyedMap.get(t);
  13707. }, t.prototype.first = function() {
  13708. return this.sortedSet.minKey();
  13709. }, t.prototype.last = function() {
  13710. return this.sortedSet.maxKey();
  13711. }, t.prototype.isEmpty = function() {
  13712. return this.sortedSet.isEmpty();
  13713. },
  13714. /**
  13715. * Returns the index of the provided key in the document set, or -1 if the
  13716. * document key is not present in the set;
  13717. */
  13718. t.prototype.indexOf = function(t) {
  13719. var e = this.keyedMap.get(t);
  13720. return e ? this.sortedSet.indexOf(e) : -1;
  13721. }, Object.defineProperty(t.prototype, "size", {
  13722. get: function() {
  13723. return this.sortedSet.size;
  13724. },
  13725. enumerable: !1,
  13726. configurable: !0
  13727. }),
  13728. /** Iterates documents in order defined by "comparator" */ t.prototype.forEach = function(t) {
  13729. this.sortedSet.inorderTraversal((function(e, n) {
  13730. return t(e), !1;
  13731. }));
  13732. },
  13733. /** Inserts or updates a document with the same key */ t.prototype.add = function(t) {
  13734. // First remove the element if we have it.
  13735. var e = this.delete(t.key);
  13736. return e.copy(e.keyedMap.insert(t.key, t), e.sortedSet.insert(t, null));
  13737. },
  13738. /** Deletes a document with a given key */ t.prototype.delete = function(t) {
  13739. var e = this.get(t);
  13740. return e ? this.copy(this.keyedMap.remove(t), this.sortedSet.remove(e)) : this;
  13741. }, t.prototype.isEqual = function(e) {
  13742. if (!(e instanceof t)) return !1;
  13743. if (this.size !== e.size) return !1;
  13744. for (var n = this.sortedSet.getIterator(), r = e.sortedSet.getIterator(); n.hasNext(); ) {
  13745. var i = n.getNext().key, o = r.getNext().key;
  13746. if (!i.isEqual(o)) return !1;
  13747. }
  13748. return !0;
  13749. }, t.prototype.toString = function() {
  13750. var t = [];
  13751. return this.forEach((function(e) {
  13752. t.push(e.toString());
  13753. })), 0 === t.length ? "DocumentSet ()" : "DocumentSet (\n " + t.join(" \n") + "\n)";
  13754. }, t.prototype.copy = function(e, n) {
  13755. var r = new t;
  13756. return r.comparator = this.comparator, r.keyedMap = e, r.sortedSet = n, r;
  13757. }, t;
  13758. }(), ts = /** @class */ function() {
  13759. function t() {
  13760. this.Tu = new He(ft.comparator);
  13761. }
  13762. return t.prototype.track = function(t) {
  13763. var e = t.doc.key, n = this.Tu.get(e);
  13764. n ?
  13765. // Merge the new change with the existing change.
  13766. 0 /* ChangeType.Added */ !== t.type && 3 /* ChangeType.Metadata */ === n.type ? this.Tu = this.Tu.insert(e, t) : 3 /* ChangeType.Metadata */ === t.type && 1 /* ChangeType.Removed */ !== n.type ? this.Tu = this.Tu.insert(e, {
  13767. type: n.type,
  13768. doc: t.doc
  13769. }) : 2 /* ChangeType.Modified */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Tu = this.Tu.insert(e, {
  13770. type: 2 /* ChangeType.Modified */ ,
  13771. doc: t.doc
  13772. }) : 2 /* ChangeType.Modified */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Tu = this.Tu.insert(e, {
  13773. type: 0 /* ChangeType.Added */ ,
  13774. doc: t.doc
  13775. }) : 1 /* ChangeType.Removed */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Tu = this.Tu.remove(e) : 1 /* ChangeType.Removed */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Tu = this.Tu.insert(e, {
  13776. type: 1 /* ChangeType.Removed */ ,
  13777. doc: n.doc
  13778. }) : 0 /* ChangeType.Added */ === t.type && 1 /* ChangeType.Removed */ === n.type ? this.Tu = this.Tu.insert(e, {
  13779. type: 2 /* ChangeType.Modified */ ,
  13780. doc: t.doc
  13781. }) :
  13782. // This includes these cases, which don't make sense:
  13783. // Added->Added
  13784. // Removed->Removed
  13785. // Modified->Added
  13786. // Removed->Modified
  13787. // Metadata->Added
  13788. // Removed->Metadata
  13789. q() : this.Tu = this.Tu.insert(e, t);
  13790. }, t.prototype.Eu = function() {
  13791. var t = [];
  13792. return this.Tu.inorderTraversal((function(e, n) {
  13793. t.push(n);
  13794. })), t;
  13795. }, t;
  13796. }(), es = /** @class */ function() {
  13797. function t(t, e, n, r, i, o, u, a, s) {
  13798. this.query = t, this.docs = e, this.oldDocs = n, this.docChanges = r, this.mutatedKeys = i,
  13799. this.fromCache = o, this.syncStateChanged = u, this.excludesMetadataChanges = a,
  13800. this.hasCachedResults = s
  13801. /** Returns a view snapshot as if all documents in the snapshot were added. */;
  13802. }
  13803. return t.fromInitialDocuments = function(e, n, r, i, o) {
  13804. var u = [];
  13805. return n.forEach((function(t) {
  13806. u.push({
  13807. type: 0 /* ChangeType.Added */ ,
  13808. doc: t
  13809. });
  13810. })), new t(e, n, $a.emptySet(n), u, r, i,
  13811. /* syncStateChanged= */ !0,
  13812. /* excludesMetadataChanges= */ !1, o);
  13813. }, Object.defineProperty(t.prototype, "hasPendingWrites", {
  13814. get: function() {
  13815. return !this.mutatedKeys.isEmpty();
  13816. },
  13817. enumerable: !1,
  13818. configurable: !0
  13819. }), t.prototype.isEqual = function(t) {
  13820. if (!(this.fromCache === t.fromCache && this.hasCachedResults === t.hasCachedResults && this.syncStateChanged === t.syncStateChanged && this.mutatedKeys.isEqual(t.mutatedKeys) && Sn(this.query, t.query) && this.docs.isEqual(t.docs) && this.oldDocs.isEqual(t.oldDocs))) return !1;
  13821. var e = this.docChanges, n = t.docChanges;
  13822. if (e.length !== n.length) return !1;
  13823. for (var r = 0; r < e.length; r++) if (e[r].type !== n[r].type || !e[r].doc.isEqual(n[r].doc)) return !1;
  13824. return !0;
  13825. }, t;
  13826. }(), ns = function() {
  13827. this.Au = void 0, this.listeners = [];
  13828. }, rs = function() {
  13829. this.queries = new pr((function(t) {
  13830. return _n(t);
  13831. }), Sn), this.onlineState = "Unknown" /* OnlineState.Unknown */ , this.Ru = new Set;
  13832. };
  13833. /**
  13834. * @license
  13835. * Copyright 2017 Google LLC
  13836. *
  13837. * Licensed under the Apache License, Version 2.0 (the "License");
  13838. * you may not use this file except in compliance with the License.
  13839. * You may obtain a copy of the License at
  13840. *
  13841. * http://www.apache.org/licenses/LICENSE-2.0
  13842. *
  13843. * Unless required by applicable law or agreed to in writing, software
  13844. * distributed under the License is distributed on an "AS IS" BASIS,
  13845. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13846. * See the License for the specific language governing permissions and
  13847. * limitations under the License.
  13848. */
  13849. /**
  13850. * DocumentChangeSet keeps track of a set of changes to docs in a query, merging
  13851. * duplicate events for the same doc.
  13852. */ function is(t, r) {
  13853. return e(this, void 0, void 0, (function() {
  13854. var e, i, o, u, a, s, c;
  13855. return n(this, (function(n) {
  13856. switch (n.label) {
  13857. case 0:
  13858. if (e = G(t), i = r.query, o = !1, (u = e.queries.get(i)) || (o = !0, u = new ns),
  13859. !o) return [ 3 /*break*/ , 4 ];
  13860. n.label = 1;
  13861. case 1:
  13862. return n.trys.push([ 1, 3, , 4 ]), a = u, [ 4 /*yield*/ , e.onListen(i) ];
  13863. case 2:
  13864. return a.Au = n.sent(), [ 3 /*break*/ , 4 ];
  13865. case 3:
  13866. return s = n.sent(), c = Ja(s, "Initialization of query '".concat(Dn(r.query), "' failed")),
  13867. [ 2 /*return*/ , void r.onError(c) ];
  13868. case 4:
  13869. return e.queries.set(i, u), u.listeners.push(r),
  13870. // Run global snapshot listeners if a consistent snapshot has been emitted.
  13871. r.bu(e.onlineState), u.Au && r.Pu(u.Au) && ss(e), [ 2 /*return*/ ];
  13872. }
  13873. }));
  13874. }));
  13875. }
  13876. function os(t, r) {
  13877. return e(this, void 0, void 0, (function() {
  13878. var e, i, o, u, a;
  13879. return n(this, (function(n) {
  13880. return e = G(t), i = r.query, o = !1, (u = e.queries.get(i)) && (a = u.listeners.indexOf(r)) >= 0 && (u.listeners.splice(a, 1),
  13881. o = 0 === u.listeners.length), o ? [ 2 /*return*/ , (e.queries.delete(i), e.onUnlisten(i)) ] : [ 2 /*return*/ ];
  13882. }));
  13883. }));
  13884. }
  13885. function us(t, e) {
  13886. for (var n = G(t), r = !1, i = 0, o = e; i < o.length; i++) {
  13887. var u = o[i], a = u.query, s = n.queries.get(a);
  13888. if (s) {
  13889. for (var c = 0, l = s.listeners; c < l.length; c++) {
  13890. l[c].Pu(u) && (r = !0);
  13891. }
  13892. s.Au = u;
  13893. }
  13894. }
  13895. r && ss(n);
  13896. }
  13897. function as(t, e, n) {
  13898. var r = G(t), i = r.queries.get(e);
  13899. if (i) for (var o = 0, u = i.listeners; o < u.length; o++) {
  13900. u[o].onError(n);
  13901. }
  13902. // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()
  13903. // after an error.
  13904. r.queries.delete(e);
  13905. }
  13906. // Call all global snapshot listeners that have been set.
  13907. function ss(t) {
  13908. t.Ru.forEach((function(t) {
  13909. t.next();
  13910. }));
  13911. }
  13912. /**
  13913. * QueryListener takes a series of internal view snapshots and determines
  13914. * when to raise the event.
  13915. *
  13916. * It uses an Observer to dispatch events.
  13917. */ var cs = /** @class */ function() {
  13918. function t(t, e, n) {
  13919. this.query = t, this.vu = e,
  13920. /**
  13921. * Initial snapshots (e.g. from cache) may not be propagated to the wrapped
  13922. * observer. This flag is set to true once we've actually raised an event.
  13923. */
  13924. this.Vu = !1, this.Su = null, this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  13925. this.options = n || {}
  13926. /**
  13927. * Applies the new ViewSnapshot to this listener, raising a user-facing event
  13928. * if applicable (depending on what changed, whether the user has opted into
  13929. * metadata-only changes, etc.). Returns true if a user-facing event was
  13930. * indeed raised.
  13931. */;
  13932. }
  13933. return t.prototype.Pu = function(t) {
  13934. if (!this.options.includeMetadataChanges) {
  13935. for (
  13936. // Remove the metadata only changes.
  13937. var e = [], n = 0, r = t.docChanges; n < r.length; n++) {
  13938. var i = r[n];
  13939. 3 /* ChangeType.Metadata */ !== i.type && e.push(i);
  13940. }
  13941. t = new es(t.query, t.docs, t.oldDocs, e, t.mutatedKeys, t.fromCache, t.syncStateChanged,
  13942. /* excludesMetadataChanges= */ !0, t.hasCachedResults);
  13943. }
  13944. var o = !1;
  13945. return this.Vu ? this.Du(t) && (this.vu.next(t), o = !0) : this.Cu(t, this.onlineState) && (this.xu(t),
  13946. o = !0), this.Su = t, o;
  13947. }, t.prototype.onError = function(t) {
  13948. this.vu.error(t);
  13949. },
  13950. /** Returns whether a snapshot was raised. */ t.prototype.bu = function(t) {
  13951. this.onlineState = t;
  13952. var e = !1;
  13953. return this.Su && !this.Vu && this.Cu(this.Su, t) && (this.xu(this.Su), e = !0),
  13954. e;
  13955. }, t.prototype.Cu = function(t, e) {
  13956. // Always raise the first event when we're synced
  13957. if (!t.fromCache) return !0;
  13958. // NOTE: We consider OnlineState.Unknown as online (it should become Offline
  13959. // or Online if we wait long enough).
  13960. var n = "Offline" /* OnlineState.Offline */ !== e;
  13961. // Don't raise the event if we're online, aren't synced yet (checked
  13962. // above) and are waiting for a sync.
  13963. return (!this.options.Nu || !n) && (!t.docs.isEmpty() || t.hasCachedResults || "Offline" /* OnlineState.Offline */ === e);
  13964. // Raise data from cache if we have any documents, have cached results before,
  13965. // or we are offline.
  13966. }, t.prototype.Du = function(t) {
  13967. // We don't need to handle includeDocumentMetadataChanges here because
  13968. // the Metadata only changes have already been stripped out if needed.
  13969. // At this point the only changes we will see are the ones we should
  13970. // propagate.
  13971. if (t.docChanges.length > 0) return !0;
  13972. var e = this.Su && this.Su.hasPendingWrites !== t.hasPendingWrites;
  13973. return !(!t.syncStateChanged && !e) && !0 === this.options.includeMetadataChanges;
  13974. // Generally we should have hit one of the cases above, but it's possible
  13975. // to get here if there were only metadata docChanges and they got
  13976. // stripped out.
  13977. }, t.prototype.xu = function(t) {
  13978. t = es.fromInitialDocuments(t.query, t.docs, t.mutatedKeys, t.fromCache, t.hasCachedResults),
  13979. this.Vu = !0, this.vu.next(t);
  13980. }, t;
  13981. }(), ls = /** @class */ function() {
  13982. function t(t,
  13983. // How many bytes this element takes to store in the bundle.
  13984. e) {
  13985. this.ku = t, this.byteLength = e;
  13986. }
  13987. return t.prototype.Ou = function() {
  13988. return "metadata" in this.ku;
  13989. }, t;
  13990. }(), hs = /** @class */ function() {
  13991. function t(t) {
  13992. this.yt = t;
  13993. }
  13994. return t.prototype.Ji = function(t) {
  13995. return Hr(this.yt, t);
  13996. },
  13997. /**
  13998. * Converts a BundleDocument to a MutableDocument.
  13999. */
  14000. t.prototype.Yi = function(t) {
  14001. return t.metadata.exists ? ti(this.yt, t.document, !1) : rn.newNoDocument(this.Ji(t.metadata.name), this.Xi(t.metadata.readTime));
  14002. }, t.prototype.Xi = function(t) {
  14003. return jr(t);
  14004. }, t;
  14005. }(), fs = /** @class */ function() {
  14006. function t(t, e, n) {
  14007. this.Mu = t, this.localStore = e, this.yt = n,
  14008. /** Batched queries to be saved into storage */
  14009. this.queries = [],
  14010. /** Batched documents to be saved into storage */
  14011. this.documents = [],
  14012. /** The collection groups affected by this bundle. */
  14013. this.collectionGroups = new Set, this.progress = ds(t)
  14014. /**
  14015. * Adds an element from the bundle to the loader.
  14016. *
  14017. * Returns a new progress if adding the element leads to a new progress,
  14018. * otherwise returns null.
  14019. */;
  14020. }
  14021. return t.prototype.Fu = function(t) {
  14022. this.progress.bytesLoaded += t.byteLength;
  14023. var e = this.progress.documentsLoaded;
  14024. if (t.ku.namedQuery) this.queries.push(t.ku.namedQuery); else if (t.ku.documentMetadata) {
  14025. this.documents.push({
  14026. metadata: t.ku.documentMetadata
  14027. }), t.ku.documentMetadata.exists || ++e;
  14028. var n = ct.fromString(t.ku.documentMetadata.name);
  14029. this.collectionGroups.add(n.get(n.length - 2));
  14030. } else t.ku.document && (this.documents[this.documents.length - 1].document = t.ku.document,
  14031. ++e);
  14032. return e !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = e,
  14033. Object.assign({}, this.progress)) : null;
  14034. }, t.prototype.$u = function(t) {
  14035. for (var e = new Map, n = new hs(this.yt), r = 0, i = t; r < i.length; r++) {
  14036. var o = i[r];
  14037. if (o.metadata.queries) for (var u = n.Ji(o.metadata.name), a = 0, s = o.metadata.queries; a < s.length; a++) {
  14038. var c = s[a], l = (e.get(c) || _r()).add(u);
  14039. e.set(c, l);
  14040. }
  14041. }
  14042. return e;
  14043. },
  14044. /**
  14045. * Update the progress to 'Success' and return the updated progress.
  14046. */
  14047. t.prototype.complete = function() {
  14048. return e(this, void 0, void 0, (function() {
  14049. var t, e, r, i, o;
  14050. return n(this, (function(n) {
  14051. switch (n.label) {
  14052. case 0:
  14053. return [ 4 /*yield*/ , Ju(this.localStore, new hs(this.yt), this.documents, this.Mu.id) ];
  14054. case 1:
  14055. t = n.sent(), e = this.$u(this.documents), r = 0, i = this.queries, n.label = 2;
  14056. case 2:
  14057. return r < i.length ? (o = i[r], [ 4 /*yield*/ , $u(this.localStore, o, e.get(o.name)) ]) : [ 3 /*break*/ , 5 ];
  14058. case 3:
  14059. n.sent(), n.label = 4;
  14060. case 4:
  14061. return r++, [ 3 /*break*/ , 2 ];
  14062. case 5:
  14063. return [ 2 /*return*/ , (this.progress.taskState = "Success", {
  14064. progress: this.progress,
  14065. Bu: this.collectionGroups,
  14066. Lu: t
  14067. }) ];
  14068. }
  14069. }));
  14070. }));
  14071. }, t;
  14072. }();
  14073. /**
  14074. * @license
  14075. * Copyright 2020 Google LLC
  14076. *
  14077. * Licensed under the Apache License, Version 2.0 (the "License");
  14078. * you may not use this file except in compliance with the License.
  14079. * You may obtain a copy of the License at
  14080. *
  14081. * http://www.apache.org/licenses/LICENSE-2.0
  14082. *
  14083. * Unless required by applicable law or agreed to in writing, software
  14084. * distributed under the License is distributed on an "AS IS" BASIS,
  14085. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14086. * See the License for the specific language governing permissions and
  14087. * limitations under the License.
  14088. */
  14089. /**
  14090. * A complete element in the bundle stream, together with the byte length it
  14091. * occupies in the stream.
  14092. */
  14093. /**
  14094. * Returns a `LoadBundleTaskProgress` representing the initial progress of
  14095. * loading a bundle.
  14096. */
  14097. function ds(t) {
  14098. return {
  14099. taskState: "Running",
  14100. documentsLoaded: 0,
  14101. bytesLoaded: 0,
  14102. totalDocuments: t.totalDocuments,
  14103. totalBytes: t.totalBytes
  14104. };
  14105. }
  14106. /**
  14107. * Returns a `LoadBundleTaskProgress` representing the progress that the loading
  14108. * has succeeded.
  14109. */
  14110. /**
  14111. * @license
  14112. * Copyright 2017 Google LLC
  14113. *
  14114. * Licensed under the Apache License, Version 2.0 (the "License");
  14115. * you may not use this file except in compliance with the License.
  14116. * You may obtain a copy of the License at
  14117. *
  14118. * http://www.apache.org/licenses/LICENSE-2.0
  14119. *
  14120. * Unless required by applicable law or agreed to in writing, software
  14121. * distributed under the License is distributed on an "AS IS" BASIS,
  14122. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14123. * See the License for the specific language governing permissions and
  14124. * limitations under the License.
  14125. */ var ps = function(t) {
  14126. this.key = t;
  14127. }, ys = function(t) {
  14128. this.key = t;
  14129. }, vs = /** @class */ function() {
  14130. function t(t,
  14131. /** Documents included in the remote target */
  14132. e) {
  14133. this.query = t, this.qu = e, this.Uu = null, this.hasCachedResults = !1,
  14134. /**
  14135. * A flag whether the view is current with the backend. A view is considered
  14136. * current after it has seen the current flag from the backend and did not
  14137. * lose consistency within the watch stream (e.g. because of an existence
  14138. * filter mismatch).
  14139. */
  14140. this.current = !1,
  14141. /** Documents in the view but not in the remote target */
  14142. this.Ku = _r(),
  14143. /** Document Keys that have local changes */
  14144. this.mutatedKeys = _r(), this.Gu = Cn(t), this.Qu = new $a(this.Gu);
  14145. }
  14146. return Object.defineProperty(t.prototype, "ju", {
  14147. /**
  14148. * The set of remote documents that the server has told us belongs to the target associated with
  14149. * this view.
  14150. */
  14151. get: function() {
  14152. return this.qu;
  14153. },
  14154. enumerable: !1,
  14155. configurable: !0
  14156. }),
  14157. /**
  14158. * Iterates over a set of doc changes, applies the query limit, and computes
  14159. * what the new results should be, what the changes were, and whether we may
  14160. * need to go back to the local cache for more results. Does not make any
  14161. * changes to the view.
  14162. * @param docChanges - The doc changes to apply to this view.
  14163. * @param previousChanges - If this is being called with a refill, then start
  14164. * with this set of docs and changes instead of the current view.
  14165. * @returns a new set of docs, changes, and refill flag.
  14166. */
  14167. t.prototype.Wu = function(t, e) {
  14168. var n = this, r = e ? e.zu : new ts, i = e ? e.Qu : this.Qu, o = e ? e.mutatedKeys : this.mutatedKeys, u = i, a = !1, s = "F" /* LimitType.First */ === this.query.limitType && i.size === this.query.limit ? i.last() : null, c = "L" /* LimitType.Last */ === this.query.limitType && i.size === this.query.limit ? i.first() : null;
  14169. // Drop documents out to meet limit/limitToLast requirement.
  14170. if (t.inorderTraversal((function(t, e) {
  14171. var l = i.get(t), h = xn(n.query, e) ? e : null, f = !!l && n.mutatedKeys.has(l.key), d = !!h && (h.hasLocalMutations ||
  14172. // We only consider committed mutations for documents that were
  14173. // mutated during the lifetime of the view.
  14174. n.mutatedKeys.has(h.key) && h.hasCommittedMutations), p = !1;
  14175. // Calculate change
  14176. l && h ? l.data.isEqual(h.data) ? f !== d && (r.track({
  14177. type: 3 /* ChangeType.Metadata */ ,
  14178. doc: h
  14179. }), p = !0) : n.Hu(l, h) || (r.track({
  14180. type: 2 /* ChangeType.Modified */ ,
  14181. doc: h
  14182. }), p = !0, (s && n.Gu(h, s) > 0 || c && n.Gu(h, c) < 0) && (
  14183. // This doc moved from inside the limit to outside the limit.
  14184. // That means there may be some other doc in the local cache
  14185. // that should be included instead.
  14186. a = !0)) : !l && h ? (r.track({
  14187. type: 0 /* ChangeType.Added */ ,
  14188. doc: h
  14189. }), p = !0) : l && !h && (r.track({
  14190. type: 1 /* ChangeType.Removed */ ,
  14191. doc: l
  14192. }), p = !0, (s || c) && (
  14193. // A doc was removed from a full limit query. We'll need to
  14194. // requery from the local cache to see if we know about some other
  14195. // doc that should be in the results.
  14196. a = !0)), p && (h ? (u = u.add(h), o = d ? o.add(t) : o.delete(t)) : (u = u.delete(t),
  14197. o = o.delete(t)));
  14198. })), null !== this.query.limit) for (;u.size > this.query.limit; ) {
  14199. var l = "F" /* LimitType.First */ === this.query.limitType ? u.last() : u.first();
  14200. u = u.delete(l.key), o = o.delete(l.key), r.track({
  14201. type: 1 /* ChangeType.Removed */ ,
  14202. doc: l
  14203. });
  14204. }
  14205. return {
  14206. Qu: u,
  14207. zu: r,
  14208. $i: a,
  14209. mutatedKeys: o
  14210. };
  14211. }, t.prototype.Hu = function(t, e) {
  14212. // We suppress the initial change event for documents that were modified as
  14213. // part of a write acknowledgment (e.g. when the value of a server transform
  14214. // is applied) as Watch will send us the same document again.
  14215. // By suppressing the event, we only raise two user visible events (one with
  14216. // `hasPendingWrites` and the final state of the document) instead of three
  14217. // (one with `hasPendingWrites`, the modified document with
  14218. // `hasPendingWrites` and the final state of the document).
  14219. return t.hasLocalMutations && e.hasCommittedMutations && !e.hasLocalMutations;
  14220. },
  14221. /**
  14222. * Updates the view with the given ViewDocumentChanges and optionally updates
  14223. * limbo docs and sync state from the provided target change.
  14224. * @param docChanges - The set of changes to make to the view's docs.
  14225. * @param updateLimboDocuments - Whether to update limbo documents based on
  14226. * this change.
  14227. * @param targetChange - A target change to apply for computing limbo docs and
  14228. * sync state.
  14229. * @returns A new ViewChange with the given docs, changes, and sync state.
  14230. */
  14231. // PORTING NOTE: The iOS/Android clients always compute limbo document changes.
  14232. t.prototype.applyChanges = function(t, e, n) {
  14233. var r = this, i = this.Qu;
  14234. this.Qu = t.Qu, this.mutatedKeys = t.mutatedKeys;
  14235. // Sort changes based on type and query comparator
  14236. var o = t.zu.Eu();
  14237. o.sort((function(t, e) {
  14238. return function(t, e) {
  14239. var n = function(t) {
  14240. switch (t) {
  14241. case 0 /* ChangeType.Added */ :
  14242. return 1;
  14243. case 2 /* ChangeType.Modified */ :
  14244. case 3 /* ChangeType.Metadata */ :
  14245. // A metadata change is converted to a modified change at the public
  14246. // api layer. Since we sort by document key and then change type,
  14247. // metadata and modified changes must be sorted equivalently.
  14248. return 2;
  14249. case 1 /* ChangeType.Removed */ :
  14250. return 0;
  14251. default:
  14252. return q();
  14253. }
  14254. };
  14255. return n(t) - n(e);
  14256. }(t.type, e.type) || r.Gu(t.doc, e.doc);
  14257. })), this.Ju(n);
  14258. var u = e ? this.Yu() : [], a = 0 === this.Ku.size && this.current ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , s = a !== this.Uu;
  14259. return this.Uu = a, 0 !== o.length || s ? {
  14260. snapshot: new es(this.query, t.Qu, i, o, t.mutatedKeys, 0 /* SyncState.Local */ === a, s,
  14261. /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0),
  14262. Xu: u
  14263. } : {
  14264. Xu: u
  14265. };
  14266. // no changes
  14267. },
  14268. /**
  14269. * Applies an OnlineState change to the view, potentially generating a
  14270. * ViewChange if the view's syncState changes as a result.
  14271. */
  14272. t.prototype.bu = function(t) {
  14273. return this.current && "Offline" /* OnlineState.Offline */ === t ? (
  14274. // If we're offline, set `current` to false and then call applyChanges()
  14275. // to refresh our syncState and generate a ViewChange as appropriate. We
  14276. // are guaranteed to get a new TargetChange that sets `current` back to
  14277. // true once the client is back online.
  14278. this.current = !1, this.applyChanges({
  14279. Qu: this.Qu,
  14280. zu: new ts,
  14281. mutatedKeys: this.mutatedKeys,
  14282. $i: !1
  14283. },
  14284. /* updateLimboDocuments= */ !1)) : {
  14285. Xu: []
  14286. };
  14287. },
  14288. /**
  14289. * Returns whether the doc for the given key should be in limbo.
  14290. */
  14291. t.prototype.Zu = function(t) {
  14292. // If the remote end says it's part of this query, it's not in limbo.
  14293. return !this.qu.has(t) &&
  14294. // The local store doesn't think it's a result, so it shouldn't be in limbo.
  14295. !!this.Qu.has(t) && !this.Qu.get(t).hasLocalMutations;
  14296. },
  14297. /**
  14298. * Updates syncedDocuments, current, and limbo docs based on the given change.
  14299. * Returns the list of changes to which docs are in limbo.
  14300. */
  14301. t.prototype.Ju = function(t) {
  14302. var e = this;
  14303. t && (t.addedDocuments.forEach((function(t) {
  14304. return e.qu = e.qu.add(t);
  14305. })), t.modifiedDocuments.forEach((function(t) {})), t.removedDocuments.forEach((function(t) {
  14306. return e.qu = e.qu.delete(t);
  14307. })), this.current = t.current);
  14308. }, t.prototype.Yu = function() {
  14309. var t = this;
  14310. // We can only determine limbo documents when we're in-sync with the server.
  14311. if (!this.current) return [];
  14312. // TODO(klimt): Do this incrementally so that it's not quadratic when
  14313. // updating many documents.
  14314. var e = this.Ku;
  14315. this.Ku = _r(), this.Qu.forEach((function(e) {
  14316. t.Zu(e.key) && (t.Ku = t.Ku.add(e.key));
  14317. }));
  14318. // Diff the new limbo docs with the old limbo docs.
  14319. var n = [];
  14320. return e.forEach((function(e) {
  14321. t.Ku.has(e) || n.push(new ys(e));
  14322. })), this.Ku.forEach((function(t) {
  14323. e.has(t) || n.push(new ps(t));
  14324. })), n;
  14325. },
  14326. /**
  14327. * Update the in-memory state of the current view with the state read from
  14328. * persistence.
  14329. *
  14330. * We update the query view whenever a client's primary status changes:
  14331. * - When a client transitions from primary to secondary, it can miss
  14332. * LocalStorage updates and its query views may temporarily not be
  14333. * synchronized with the state on disk.
  14334. * - For secondary to primary transitions, the client needs to update the list
  14335. * of `syncedDocuments` since secondary clients update their query views
  14336. * based purely on synthesized RemoteEvents.
  14337. *
  14338. * @param queryResult.documents - The documents that match the query according
  14339. * to the LocalStore.
  14340. * @param queryResult.remoteKeys - The keys of the documents that match the
  14341. * query according to the backend.
  14342. *
  14343. * @returns The ViewChange that resulted from this synchronization.
  14344. */
  14345. // PORTING NOTE: Multi-tab only.
  14346. t.prototype.tc = function(t) {
  14347. this.qu = t.Hi, this.Ku = _r();
  14348. var e = this.Wu(t.documents);
  14349. return this.applyChanges(e, /*updateLimboDocuments=*/ !0);
  14350. },
  14351. /**
  14352. * Returns a view snapshot as if this query was just listened to. Contains
  14353. * a document add for every existing document and the `fromCache` and
  14354. * `hasPendingWrites` status of the already established view.
  14355. */
  14356. // PORTING NOTE: Multi-tab only.
  14357. t.prototype.ec = function() {
  14358. return es.fromInitialDocuments(this.query, this.Qu, this.mutatedKeys, 0 /* SyncState.Local */ === this.Uu, this.hasCachedResults);
  14359. }, t;
  14360. }(), ms = function(
  14361. /**
  14362. * The query itself.
  14363. */
  14364. t,
  14365. /**
  14366. * The target number created by the client that is used in the watch
  14367. * stream to identify this query.
  14368. */
  14369. e,
  14370. /**
  14371. * The view is responsible for computing the final merged truth of what
  14372. * docs are in the query. It gets notified of local and remote changes,
  14373. * and applies the query filters and limits to determine the most correct
  14374. * possible results.
  14375. */
  14376. n) {
  14377. this.query = t, this.targetId = e, this.view = n;
  14378. }, gs = function(t) {
  14379. this.key = t,
  14380. /**
  14381. * Set to true once we've received a document. This is used in
  14382. * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to
  14383. * decide whether it needs to manufacture a delete event for the target once
  14384. * the target is CURRENT.
  14385. */
  14386. this.nc = !1;
  14387. }, ws = /** @class */ function() {
  14388. function t(t, e, n,
  14389. // PORTING NOTE: Manages state synchronization in multi-tab environments.
  14390. r, i, o) {
  14391. this.localStore = t, this.remoteStore = e, this.eventManager = n, this.sharedClientState = r,
  14392. this.currentUser = i, this.maxConcurrentLimboResolutions = o, this.sc = {}, this.ic = new pr((function(t) {
  14393. return _n(t);
  14394. }), Sn), this.rc = new Map,
  14395. /**
  14396. * The keys of documents that are in limbo for which we haven't yet started a
  14397. * limbo resolution query. The strings in this set are the result of calling
  14398. * `key.path.canonicalString()` where `key` is a `DocumentKey` object.
  14399. *
  14400. * The `Set` type was chosen because it provides efficient lookup and removal
  14401. * of arbitrary elements and it also maintains insertion order, providing the
  14402. * desired queue-like FIFO semantics.
  14403. */
  14404. this.oc = new Set,
  14405. /**
  14406. * Keeps track of the target ID for each document that is in limbo with an
  14407. * active target.
  14408. */
  14409. this.uc = new He(ft.comparator),
  14410. /**
  14411. * Keeps track of the information about an active limbo resolution for each
  14412. * active target ID that was started for the purpose of limbo resolution.
  14413. */
  14414. this.cc = new Map, this.ac = new bu,
  14415. /** Stores user completion handlers, indexed by User and BatchId. */
  14416. this.hc = {},
  14417. /** Stores user callbacks waiting for all pending writes to be acknowledged. */
  14418. this.lc = new Map, this.fc = Xo.vn(), this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  14419. // The primary state is set to `true` or `false` immediately after Firestore
  14420. // startup. In the interim, a client should only be considered primary if
  14421. // `isPrimary` is true.
  14422. this.dc = void 0;
  14423. }
  14424. return Object.defineProperty(t.prototype, "isPrimaryClient", {
  14425. get: function() {
  14426. return !0 === this.dc;
  14427. },
  14428. enumerable: !1,
  14429. configurable: !0
  14430. }), t;
  14431. }();
  14432. /**
  14433. * Initiates the new listen, resolves promise when listen enqueued to the
  14434. * server. All the subsequent view snapshots or errors are sent to the
  14435. * subscribed handlers. Returns the initial snapshot.
  14436. */
  14437. function bs(t, r) {
  14438. return e(this, void 0, void 0, (function() {
  14439. var e, i, o, u, a, s;
  14440. return n(this, (function(n) {
  14441. switch (n.label) {
  14442. case 0:
  14443. return e = Ys(t), (u = e.ic.get(r)) ? (
  14444. // PORTING NOTE: With Multi-Tab Web, it is possible that a query view
  14445. // already exists when EventManager calls us for the first time. This
  14446. // happens when the primary tab is already listening to this query on
  14447. // behalf of another tab and the user of the primary also starts listening
  14448. // to the query. EventManager will not have an assigned target ID in this
  14449. // case and calls `listen` to obtain this ID.
  14450. i = u.targetId, e.sharedClientState.addLocalQueryTarget(i), o = u.view.ec(), [ 3 /*break*/ , 4 ]) : [ 3 /*break*/ , 1 ];
  14451. case 1:
  14452. return [ 4 /*yield*/ , zu(e.localStore, In(r)) ];
  14453. case 2:
  14454. return a = n.sent(), e.isPrimaryClient && xa(e.remoteStore, a), s = e.sharedClientState.addLocalQueryTarget(a.targetId),
  14455. i = a.targetId, [ 4 /*yield*/ , Is(e, r, i, "current" === s, a.resumeToken) ];
  14456. case 3:
  14457. o = n.sent(), n.label = 4;
  14458. case 4:
  14459. return [ 2 /*return*/ , o ];
  14460. }
  14461. }));
  14462. }));
  14463. }
  14464. /**
  14465. * Registers a view for a previously unknown query and computes its initial
  14466. * snapshot.
  14467. */ function Is(t, r, i, o, u) {
  14468. return e(this, void 0, void 0, (function() {
  14469. var a, s, c, l, h, f;
  14470. return n(this, (function(d) {
  14471. switch (d.label) {
  14472. case 0:
  14473. // PORTING NOTE: On Web only, we inject the code that registers new Limbo
  14474. // targets based on view changes. This allows us to only depend on Limbo
  14475. // changes when user code includes queries.
  14476. return t._c = function(r, i, o) {
  14477. return function(t, r, i, o) {
  14478. return e(this, void 0, void 0, (function() {
  14479. var e, u, a;
  14480. return n(this, (function(n) {
  14481. switch (n.label) {
  14482. case 0:
  14483. return e = r.view.Wu(i), e.$i ? [ 4 /*yield*/ , Hu(t.localStore, r.query,
  14484. /* usePreviousResults= */ !1).then((function(t) {
  14485. var n = t.documents;
  14486. return r.view.Wu(n, e);
  14487. })) ] : [ 3 /*break*/ , 2 ];
  14488. case 1:
  14489. // The query has a limit and some docs were removed, so we need
  14490. // to re-run the query against the local store to make sure we
  14491. // didn't lose any good docs that had been past the limit.
  14492. e = n.sent(), n.label = 2;
  14493. case 2:
  14494. return u = o && o.targetChanges.get(r.targetId), a = r.view.applyChanges(e,
  14495. /* updateLimboDocuments= */ t.isPrimaryClient, u), [ 2 /*return*/ , (Rs(t, r.targetId, a.Xu),
  14496. a.snapshot) ];
  14497. }
  14498. }));
  14499. }));
  14500. }(t, r, i, o);
  14501. }, [ 4 /*yield*/ , Hu(t.localStore, r,
  14502. /* usePreviousResults= */ !0) ];
  14503. case 1:
  14504. return a = d.sent(), s = new vs(r, a.Hi), c = s.Wu(a.documents), l = Cr.createSynthesizedTargetChangeForCurrentChange(i, o && "Offline" /* OnlineState.Offline */ !== t.onlineState, u),
  14505. h = s.applyChanges(c,
  14506. /* updateLimboDocuments= */ t.isPrimaryClient, l), Rs(t, i, h.Xu), f = new ms(r, i, s),
  14507. [ 2 /*return*/ , (t.ic.set(r, f), t.rc.has(i) ? t.rc.get(i).push(r) : t.rc.set(i, [ r ]),
  14508. h.snapshot) ];
  14509. }
  14510. }));
  14511. }));
  14512. }
  14513. /** Stops listening to the query. */ function Ts(t, r) {
  14514. return e(this, void 0, void 0, (function() {
  14515. var e, i, o;
  14516. return n(this, (function(n) {
  14517. switch (n.label) {
  14518. case 0:
  14519. return e = G(t), i = e.ic.get(r), (o = e.rc.get(i.targetId)).length > 1 ? [ 2 /*return*/ , (e.rc.set(i.targetId, o.filter((function(t) {
  14520. return !Sn(t, r);
  14521. }))), void e.ic.delete(r)) ] : e.isPrimaryClient ? (
  14522. // We need to remove the local query target first to allow us to verify
  14523. // whether any other client is still interested in this target.
  14524. e.sharedClientState.removeLocalQueryTarget(i.targetId), e.sharedClientState.isActiveQueryTarget(i.targetId) ? [ 3 /*break*/ , 2 ] : [ 4 /*yield*/ , Wu(e.localStore, i.targetId,
  14525. /*keepPersistedTargetData=*/ !1).then((function() {
  14526. e.sharedClientState.clearQueryState(i.targetId), Aa(e.remoteStore, i.targetId),
  14527. Fs(e, i.targetId);
  14528. })).catch(Dt) ]) : [ 3 /*break*/ , 3 ];
  14529. case 1:
  14530. n.sent(), n.label = 2;
  14531. case 2:
  14532. return [ 3 /*break*/ , 5 ];
  14533. case 3:
  14534. return Fs(e, i.targetId), [ 4 /*yield*/ , Wu(e.localStore, i.targetId,
  14535. /*keepPersistedTargetData=*/ !0) ];
  14536. case 4:
  14537. n.sent(), n.label = 5;
  14538. case 5:
  14539. return [ 2 /*return*/ ];
  14540. }
  14541. }));
  14542. }));
  14543. }
  14544. /**
  14545. * Initiates the write of local mutation batch which involves adding the
  14546. * writes to the mutation queue, notifying the remote store about new
  14547. * mutations and raising events for any changes this write caused.
  14548. *
  14549. * The promise returned by this call is resolved when the above steps
  14550. * have completed, *not* when the write was acked by the backend. The
  14551. * userCallback is resolved once the write was acked/rejected by the
  14552. * backend (or failed locally for any other reason).
  14553. */ function Es(t, r, i) {
  14554. return e(this, void 0, void 0, (function() {
  14555. var e, o, u, a;
  14556. return n(this, (function(n) {
  14557. switch (n.label) {
  14558. case 0:
  14559. e = Xs(t), n.label = 1;
  14560. case 1:
  14561. return n.trys.push([ 1, 5, , 6 ]), [ 4 /*yield*/ , function(t, e) {
  14562. var n, r, i = G(t), o = ut.now(), u = e.reduce((function(t, e) {
  14563. return t.add(e.key);
  14564. }), _r());
  14565. return i.persistence.runTransaction("Locally write mutations", "readwrite", (function(t) {
  14566. // Figure out which keys do not have a remote version in the cache, this
  14567. // is needed to create the right overlay mutation: if no remote version
  14568. // presents, we do not need to create overlays as patch mutations.
  14569. // TODO(Overlay): Is there a better way to determine this? Using the
  14570. // document version does not work because local mutations set them back
  14571. // to 0.
  14572. var a = vr(), s = _r();
  14573. return i.Gi.getEntries(t, u).next((function(t) {
  14574. (a = t).forEach((function(t, e) {
  14575. e.isValidDocument() || (s = s.add(t));
  14576. }));
  14577. })).next((function() {
  14578. return i.localDocuments.getOverlayedDocuments(t, a);
  14579. })).next((function(r) {
  14580. n = r;
  14581. for (
  14582. // For non-idempotent mutations (such as `FieldValue.increment()`),
  14583. // we record the base state in a separate patch mutation. This is
  14584. // later used to guarantee consistent values and prevents flicker
  14585. // even if the backend sends us an update that already includes our
  14586. // transform.
  14587. var u = [], a = 0, s = e; a < s.length; a++) {
  14588. var c = s[a], l = tr(c, n.get(c.key).overlayedDocument);
  14589. null != l &&
  14590. // NOTE: The base state should only be applied if there's some
  14591. // existing document to override, so use a Precondition of
  14592. // exists=true
  14593. u.push(new rr(c.key, l, nn(l.value.mapValue), Hn.exists(!0)));
  14594. }
  14595. return i.mutationQueue.addMutationBatch(t, o, u, e);
  14596. })).next((function(e) {
  14597. r = e;
  14598. var o = e.applyToLocalDocumentSet(n, s);
  14599. return i.documentOverlayCache.saveOverlays(t, e.batchId, o);
  14600. }));
  14601. })).then((function() {
  14602. return {
  14603. batchId: r.batchId,
  14604. changes: wr(n)
  14605. };
  14606. }));
  14607. }(e.localStore, r) ];
  14608. case 2:
  14609. return o = n.sent(), e.sharedClientState.addPendingMutation(o.batchId), function(t, e, n) {
  14610. var r = t.hc[t.currentUser.toKey()];
  14611. r || (r = new He(rt)), r = r.insert(e, n), t.hc[t.currentUser.toKey()] = r;
  14612. }(e, o.batchId, i), [ 4 /*yield*/ , Ls(e, o.changes) ];
  14613. case 3:
  14614. return n.sent(), [ 4 /*yield*/ , Ua(e.remoteStore) ];
  14615. case 4:
  14616. return n.sent(), [ 3 /*break*/ , 6 ];
  14617. case 5:
  14618. return u = n.sent(), a = Ja(u, "Failed to persist write"), i.reject(a), [ 3 /*break*/ , 6 ];
  14619. case 6:
  14620. return [ 2 /*return*/ ];
  14621. }
  14622. }));
  14623. }));
  14624. }
  14625. /**
  14626. * Applies one remote event to the sync engine, notifying any views of the
  14627. * changes, and releasing any pending mutation batches that would become
  14628. * visible because of the snapshot version the remote event contains.
  14629. */ function Ss(t, r) {
  14630. return e(this, void 0, void 0, (function() {
  14631. var e, i;
  14632. return n(this, (function(n) {
  14633. switch (n.label) {
  14634. case 0:
  14635. e = G(t), n.label = 1;
  14636. case 1:
  14637. return n.trys.push([ 1, 4, , 6 ]), [ 4 /*yield*/ , Ku(e.localStore, r) ];
  14638. case 2:
  14639. return i = n.sent(),
  14640. // Update `receivedDocument` as appropriate for any limbo targets.
  14641. r.targetChanges.forEach((function(t, n) {
  14642. var r = e.cc.get(n);
  14643. r && (
  14644. // Since this is a limbo resolution lookup, it's for a single document
  14645. // and it could be added, modified, or removed, but not a combination.
  14646. U(t.addedDocuments.size + t.modifiedDocuments.size + t.removedDocuments.size <= 1),
  14647. t.addedDocuments.size > 0 ? r.nc = !0 : t.modifiedDocuments.size > 0 ? U(r.nc) : t.removedDocuments.size > 0 && (U(r.nc),
  14648. r.nc = !1));
  14649. })), [ 4 /*yield*/ , Ls(e, i, r) ];
  14650. case 3:
  14651. // Update `receivedDocument` as appropriate for any limbo targets.
  14652. return n.sent(), [ 3 /*break*/ , 6 ];
  14653. case 4:
  14654. return [ 4 /*yield*/ , Dt(n.sent()) ];
  14655. case 5:
  14656. return n.sent(), [ 3 /*break*/ , 6 ];
  14657. case 6:
  14658. return [ 2 /*return*/ ];
  14659. }
  14660. }));
  14661. }));
  14662. }
  14663. /**
  14664. * Applies an OnlineState change to the sync engine and notifies any views of
  14665. * the change.
  14666. */ function _s(t, e, n) {
  14667. var r = G(t);
  14668. // If we are the secondary client, we explicitly ignore the remote store's
  14669. // online state (the local client may go offline, even though the primary
  14670. // tab remains online) and only apply the primary tab's online state from
  14671. // SharedClientState.
  14672. if (r.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !r.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) {
  14673. var i = [];
  14674. r.ic.forEach((function(t, n) {
  14675. var r = n.view.bu(e);
  14676. r.snapshot && i.push(r.snapshot);
  14677. })), function(t, e) {
  14678. var n = G(t);
  14679. n.onlineState = e;
  14680. var r = !1;
  14681. n.queries.forEach((function(t, n) {
  14682. for (var i = 0, o = n.listeners; i < o.length; i++) {
  14683. // Run global snapshot listeners if a consistent snapshot has been emitted.
  14684. o[i].bu(e) && (r = !0);
  14685. }
  14686. })), r && ss(n);
  14687. }(r.eventManager, e), i.length && r.sc.Wo(i), r.onlineState = e, r.isPrimaryClient && r.sharedClientState.setOnlineState(e);
  14688. }
  14689. }
  14690. /**
  14691. * Rejects the listen for the given targetID. This can be triggered by the
  14692. * backend for any active target.
  14693. *
  14694. * @param syncEngine - The sync engine implementation.
  14695. * @param targetId - The targetID corresponds to one previously initiated by the
  14696. * user as part of TargetData passed to listen() on RemoteStore.
  14697. * @param err - A description of the condition that has forced the rejection.
  14698. * Nearly always this will be an indication that the user is no longer
  14699. * authorized to see the data matching the target.
  14700. */ function Ds(t, r, i) {
  14701. return e(this, void 0, void 0, (function() {
  14702. var e, o, u, a, s, c;
  14703. return n(this, (function(n) {
  14704. switch (n.label) {
  14705. case 0:
  14706. // PORTING NOTE: Multi-tab only.
  14707. return (e = G(t)).sharedClientState.updateQueryState(r, "rejected", i), o = e.cc.get(r),
  14708. (u = o && o.key) ? (
  14709. // TODO(b/217189216): This limbo document should ideally have a read time,
  14710. // so that it is picked up by any read-time based scans. The backend,
  14711. // however, does not send a read time for target removals.
  14712. a = (a = new He(ft.comparator)).insert(u, rn.newNoDocument(u, at.min())), s = _r().add(u),
  14713. c = new Ar(at.min(),
  14714. /* targetChanges= */ new Map,
  14715. /* targetMismatches= */ new Ze(rt), a, s), [ 4 /*yield*/ , Ss(e, c) ]) : [ 3 /*break*/ , 2 ];
  14716. case 1:
  14717. return n.sent(),
  14718. // Since this query failed, we won't want to manually unlisten to it.
  14719. // We only remove it from bookkeeping after we successfully applied the
  14720. // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to
  14721. // this query when the RemoteStore restarts the Watch stream, which should
  14722. // re-trigger the target failure.
  14723. e.uc = e.uc.remove(u), e.cc.delete(r), Ms(e), [ 3 /*break*/ , 4 ];
  14724. case 2:
  14725. return [ 4 /*yield*/ , Wu(e.localStore, r,
  14726. /* keepPersistedTargetData */ !1).then((function() {
  14727. return Fs(e, r, i);
  14728. })).catch(Dt) ];
  14729. case 3:
  14730. n.sent(), n.label = 4;
  14731. case 4:
  14732. return [ 2 /*return*/ ];
  14733. }
  14734. }));
  14735. }));
  14736. }
  14737. function xs(t, r) {
  14738. return e(this, void 0, void 0, (function() {
  14739. var e, i, o;
  14740. return n(this, (function(n) {
  14741. switch (n.label) {
  14742. case 0:
  14743. e = G(t), i = r.batch.batchId, n.label = 1;
  14744. case 1:
  14745. return n.trys.push([ 1, 4, , 6 ]), [ 4 /*yield*/ , Bu(e.localStore, r) ];
  14746. case 2:
  14747. return o = n.sent(),
  14748. // The local store may or may not be able to apply the write result and
  14749. // raise events immediately (depending on whether the watcher is caught
  14750. // up), so we raise user callbacks first so that they consistently happen
  14751. // before listen events.
  14752. ks(e, i, /*error=*/ null), Ns(e, i), e.sharedClientState.updateMutationState(i, "acknowledged"),
  14753. [ 4 /*yield*/ , Ls(e, o) ];
  14754. case 3:
  14755. // The local store may or may not be able to apply the write result and
  14756. // raise events immediately (depending on whether the watcher is caught
  14757. // up), so we raise user callbacks first so that they consistently happen
  14758. // before listen events.
  14759. return n.sent(), [ 3 /*break*/ , 6 ];
  14760. case 4:
  14761. return [ 4 /*yield*/ , Dt(n.sent()) ];
  14762. case 5:
  14763. return n.sent(), [ 3 /*break*/ , 6 ];
  14764. case 6:
  14765. return [ 2 /*return*/ ];
  14766. }
  14767. }));
  14768. }));
  14769. }
  14770. function As(t, r, i) {
  14771. return e(this, void 0, void 0, (function() {
  14772. var e, o;
  14773. return n(this, (function(n) {
  14774. switch (n.label) {
  14775. case 0:
  14776. e = G(t), n.label = 1;
  14777. case 1:
  14778. return n.trys.push([ 1, 4, , 6 ]), [ 4 /*yield*/ , function(t, e) {
  14779. var n = G(t);
  14780. return n.persistence.runTransaction("Reject batch", "readwrite-primary", (function(t) {
  14781. var r;
  14782. return n.mutationQueue.lookupMutationBatch(t, e).next((function(e) {
  14783. return U(null !== e), r = e.keys(), n.mutationQueue.removeMutationBatch(t, e);
  14784. })).next((function() {
  14785. return n.mutationQueue.performConsistencyCheck(t);
  14786. })).next((function() {
  14787. return n.documentOverlayCache.removeOverlaysForBatchId(t, r, e);
  14788. })).next((function() {
  14789. return n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, r);
  14790. })).next((function() {
  14791. return n.localDocuments.getDocuments(t, r);
  14792. }));
  14793. }));
  14794. }(e.localStore, r) ];
  14795. case 2:
  14796. return o = n.sent(),
  14797. // The local store may or may not be able to apply the write result and
  14798. // raise events immediately (depending on whether the watcher is caught up),
  14799. // so we raise user callbacks first so that they consistently happen before
  14800. // listen events.
  14801. ks(e, r, i), Ns(e, r), e.sharedClientState.updateMutationState(r, "rejected", i),
  14802. [ 4 /*yield*/ , Ls(e, o) ];
  14803. case 3:
  14804. // The local store may or may not be able to apply the write result and
  14805. // raise events immediately (depending on whether the watcher is caught up),
  14806. // so we raise user callbacks first so that they consistently happen before
  14807. // listen events.
  14808. return n.sent(), [ 3 /*break*/ , 6 ];
  14809. case 4:
  14810. return [ 4 /*yield*/ , Dt(n.sent()) ];
  14811. case 5:
  14812. return n.sent(), [ 3 /*break*/ , 6 ];
  14813. case 6:
  14814. return [ 2 /*return*/ ];
  14815. }
  14816. }));
  14817. }));
  14818. }
  14819. /**
  14820. * Registers a user callback that resolves when all pending mutations at the moment of calling
  14821. * are acknowledged .
  14822. */ function Cs(t, r) {
  14823. return e(this, void 0, void 0, (function() {
  14824. var e, i, o, u, a;
  14825. return n(this, (function(n) {
  14826. switch (n.label) {
  14827. case 0:
  14828. Oa((e = G(t)).remoteStore) || V("SyncEngine", "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled."),
  14829. n.label = 1;
  14830. case 1:
  14831. return n.trys.push([ 1, 3, , 4 ]), [ 4 /*yield*/ , function(t) {
  14832. var e = G(t);
  14833. return e.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", (function(t) {
  14834. return e.mutationQueue.getHighestUnacknowledgedBatchId(t);
  14835. }));
  14836. }(e.localStore) ];
  14837. case 2:
  14838. return -1 === (i = n.sent()) ? [ 2 /*return*/ , void r.resolve() ] : ((o = e.lc.get(i) || []).push(r),
  14839. e.lc.set(i, o), [ 3 /*break*/ , 4 ]);
  14840. case 3:
  14841. return u = n.sent(), a = Ja(u, "Initialization of waitForPendingWrites() operation failed"),
  14842. r.reject(a), [ 3 /*break*/ , 4 ];
  14843. case 4:
  14844. return [ 2 /*return*/ ];
  14845. }
  14846. }));
  14847. }));
  14848. }
  14849. /**
  14850. * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,
  14851. * if there are any.
  14852. */ function Ns(t, e) {
  14853. (t.lc.get(e) || []).forEach((function(t) {
  14854. t.resolve();
  14855. })), t.lc.delete(e)
  14856. /** Reject all outstanding callbacks waiting for pending writes to complete. */;
  14857. }
  14858. function ks(t, e, n) {
  14859. var r = G(t), i = r.hc[r.currentUser.toKey()];
  14860. // NOTE: Mutations restored from persistence won't have callbacks, so it's
  14861. // okay for there to be no callback for this ID.
  14862. if (i) {
  14863. var o = i.get(e);
  14864. o && (n ? o.reject(n) : o.resolve(), i = i.remove(e)), r.hc[r.currentUser.toKey()] = i;
  14865. }
  14866. }
  14867. function Fs(t, e, n) {
  14868. void 0 === n && (n = null), t.sharedClientState.removeLocalQueryTarget(e);
  14869. for (var r = 0, i = t.rc.get(e); r < i.length; r++) {
  14870. var o = i[r];
  14871. t.ic.delete(o), n && t.sc.wc(o, n);
  14872. }
  14873. t.rc.delete(e), t.isPrimaryClient && t.ac.ls(e).forEach((function(e) {
  14874. t.ac.containsKey(e) ||
  14875. // We removed the last reference for this key
  14876. Os(t, e);
  14877. }));
  14878. }
  14879. function Os(t, e) {
  14880. t.oc.delete(e.path.canonicalString());
  14881. // It's possible that the target already got removed because the query failed. In that case,
  14882. // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.
  14883. var n = t.uc.get(e);
  14884. null !== n && (Aa(t.remoteStore, n), t.uc = t.uc.remove(e), t.cc.delete(n), Ms(t));
  14885. }
  14886. function Rs(t, e, n) {
  14887. for (var r = 0, i = n; r < i.length; r++) {
  14888. var o = i[r];
  14889. o instanceof ps ? (t.ac.addReference(o.key, e), Vs(t, o)) : o instanceof ys ? (V("SyncEngine", "Document no longer in limbo: " + o.key),
  14890. t.ac.removeReference(o.key, e), t.ac.containsKey(o.key) ||
  14891. // We removed the last reference for this key
  14892. Os(t, o.key)) : q();
  14893. }
  14894. }
  14895. function Vs(t, e) {
  14896. var n = e.key, r = n.path.canonicalString();
  14897. t.uc.get(n) || t.oc.has(r) || (V("SyncEngine", "New document in limbo: " + n), t.oc.add(r),
  14898. Ms(t));
  14899. }
  14900. /**
  14901. * Starts listens for documents in limbo that are enqueued for resolution,
  14902. * subject to a maximum number of concurrent resolutions.
  14903. *
  14904. * Without bounding the number of concurrent resolutions, the server can fail
  14905. * with "resource exhausted" errors which can lead to pathological client
  14906. * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.
  14907. */ function Ms(t) {
  14908. for (;t.oc.size > 0 && t.uc.size < t.maxConcurrentLimboResolutions; ) {
  14909. var e = t.oc.values().next().value;
  14910. t.oc.delete(e);
  14911. var n = new ft(ct.fromString(e)), r = t.fc.next();
  14912. t.cc.set(r, new gs(n)), t.uc = t.uc.insert(n, r), xa(t.remoteStore, new Wi(In(yn(n.path)), r, 2 /* TargetPurpose.LimboResolution */ , qt.at));
  14913. }
  14914. }
  14915. function Ls(t, r, i) {
  14916. return e(this, void 0, void 0, (function() {
  14917. var o, u, a, s;
  14918. return n(this, (function(c) {
  14919. switch (c.label) {
  14920. case 0:
  14921. return o = G(t), u = [], a = [], s = [], o.ic.isEmpty() ? [ 3 /*break*/ , 3 ] : (o.ic.forEach((function(t, e) {
  14922. s.push(o._c(e, r, i).then((function(t) {
  14923. // Update views if there are actual changes.
  14924. if (
  14925. // If there are changes, or we are handling a global snapshot, notify
  14926. // secondary clients to update query state.
  14927. (t || i) && o.isPrimaryClient && o.sharedClientState.updateQueryState(e.targetId, (null == t ? void 0 : t.fromCache) ? "not-current" : "current"),
  14928. t) {
  14929. u.push(t);
  14930. var n = Mu.Ci(e.targetId, t);
  14931. a.push(n);
  14932. }
  14933. })));
  14934. })), [ 4 /*yield*/ , Promise.all(s) ]);
  14935. case 1:
  14936. return c.sent(), o.sc.Wo(u), [ 4 /*yield*/ , function(t, r) {
  14937. return e(this, void 0, void 0, (function() {
  14938. var e, i, o, u, a, s, c, l, h;
  14939. return n(this, (function(n) {
  14940. switch (n.label) {
  14941. case 0:
  14942. e = G(t), n.label = 1;
  14943. case 1:
  14944. return n.trys.push([ 1, 3, , 4 ]), [ 4 /*yield*/ , e.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (function(t) {
  14945. return xt.forEach(r, (function(n) {
  14946. return xt.forEach(n.Si, (function(r) {
  14947. return e.persistence.referenceDelegate.addReference(t, n.targetId, r);
  14948. })).next((function() {
  14949. return xt.forEach(n.Di, (function(r) {
  14950. return e.persistence.referenceDelegate.removeReference(t, n.targetId, r);
  14951. }));
  14952. }));
  14953. }));
  14954. })) ];
  14955. case 2:
  14956. return n.sent(), [ 3 /*break*/ , 4 ];
  14957. case 3:
  14958. if (!Ft(i = n.sent())) throw i;
  14959. // If `notifyLocalViewChanges` fails, we did not advance the sequence
  14960. // number for the documents that were included in this transaction.
  14961. // This might trigger them to be deleted earlier than they otherwise
  14962. // would have, but it should not invalidate the integrity of the data.
  14963. return V("LocalStore", "Failed to update sequence numbers: " + i),
  14964. [ 3 /*break*/ , 4 ];
  14965. case 4:
  14966. for (o = 0, u = r; o < u.length; o++) a = u[o], s = a.targetId, a.fromCache || (c = e.qi.get(s),
  14967. l = c.snapshotVersion, h = c.withLastLimboFreeSnapshotVersion(l),
  14968. // Advance the last limbo free snapshot version
  14969. e.qi = e.qi.insert(s, h));
  14970. return [ 2 /*return*/ ];
  14971. }
  14972. }));
  14973. }));
  14974. }(o.localStore, a) ];
  14975. case 2:
  14976. c.sent(), c.label = 3;
  14977. case 3:
  14978. return [ 2 /*return*/ ];
  14979. }
  14980. }));
  14981. }));
  14982. }
  14983. function Ps(t, r) {
  14984. return e(this, void 0, void 0, (function() {
  14985. var e, i;
  14986. return n(this, (function(n) {
  14987. switch (n.label) {
  14988. case 0:
  14989. return (e = G(t)).currentUser.isEqual(r) ? [ 3 /*break*/ , 3 ] : (V("SyncEngine", "User change. New user:", r.toKey()),
  14990. [ 4 /*yield*/ , Uu(e.localStore, r) ]);
  14991. case 1:
  14992. return i = n.sent(), e.currentUser = r,
  14993. // Fails tasks waiting for pending writes requested by previous user.
  14994. function(t, e) {
  14995. t.lc.forEach((function(t) {
  14996. t.forEach((function(t) {
  14997. t.reject(new j(K.CANCELLED, "'waitForPendingWrites' promise is rejected due to a user change."));
  14998. }));
  14999. })), t.lc.clear();
  15000. }(e),
  15001. // TODO(b/114226417): Consider calling this only in the primary tab.
  15002. e.sharedClientState.handleUserChange(r, i.removedBatchIds, i.addedBatchIds), [ 4 /*yield*/ , Ls(e, i.ji) ];
  15003. case 2:
  15004. n.sent(), n.label = 3;
  15005. case 3:
  15006. return [ 2 /*return*/ ];
  15007. }
  15008. }));
  15009. }));
  15010. }
  15011. function qs(t, e) {
  15012. var n = G(t), r = n.cc.get(e);
  15013. if (r && r.nc) return _r().add(r.key);
  15014. var i = _r(), o = n.rc.get(e);
  15015. if (!o) return i;
  15016. for (var u = 0, a = o; u < a.length; u++) {
  15017. var s = a[u], c = n.ic.get(s);
  15018. i = i.unionWith(c.view.ju);
  15019. }
  15020. return i;
  15021. }
  15022. /**
  15023. * Reconcile the list of synced documents in an existing view with those
  15024. * from persistence.
  15025. */ function Us(t, r) {
  15026. return e(this, void 0, void 0, (function() {
  15027. var e, i, o;
  15028. return n(this, (function(n) {
  15029. switch (n.label) {
  15030. case 0:
  15031. return [ 4 /*yield*/ , Hu((e = G(t)).localStore, r.query,
  15032. /* usePreviousResults= */ !0) ];
  15033. case 1:
  15034. return i = n.sent(), o = r.view.tc(i), [ 2 /*return*/ , (e.isPrimaryClient && Rs(e, r.targetId, o.Xu),
  15035. o) ];
  15036. }
  15037. }));
  15038. }));
  15039. }
  15040. /**
  15041. * Retrieves newly changed documents from remote document cache and raises
  15042. * snapshots if needed.
  15043. */
  15044. // PORTING NOTE: Multi-Tab only.
  15045. function Bs(t, r) {
  15046. return e(this, void 0, void 0, (function() {
  15047. var e;
  15048. return n(this, (function(n) {
  15049. return [ 2 /*return*/ , Xu((e = G(t)).localStore, r).then((function(t) {
  15050. return Ls(e, t);
  15051. })) ];
  15052. }));
  15053. }));
  15054. }
  15055. /** Applies a mutation state to an existing batch. */
  15056. // PORTING NOTE: Multi-Tab only.
  15057. function Gs(t, r, i, o) {
  15058. return e(this, void 0, void 0, (function() {
  15059. var e, u;
  15060. return n(this, (function(n) {
  15061. switch (n.label) {
  15062. case 0:
  15063. return [ 4 /*yield*/ , function(t, e) {
  15064. var n = G(t), r = G(n.mutationQueue);
  15065. return n.persistence.runTransaction("Lookup mutation documents", "readonly", (function(t) {
  15066. return r.Tn(t, e).next((function(e) {
  15067. return e ? n.localDocuments.getDocuments(t, e) : xt.resolve(null);
  15068. }));
  15069. }));
  15070. }((e = G(t)).localStore, r) ];
  15071. case 1:
  15072. return null === (u = n.sent()) ? [ 3 /*break*/ , 6 ] : "pending" !== i ? [ 3 /*break*/ , 3 ] : [ 4 /*yield*/ , Ua(e.remoteStore) ];
  15073. case 2:
  15074. // If we are the primary client, we need to send this write to the
  15075. // backend. Secondary clients will ignore these writes since their remote
  15076. // connection is disabled.
  15077. return n.sent(), [ 3 /*break*/ , 4 ];
  15078. case 3:
  15079. "acknowledged" === i || "rejected" === i ? (
  15080. // NOTE: Both these methods are no-ops for batches that originated from
  15081. // other clients.
  15082. ks(e, r, o || null), Ns(e, r), function(t, e) {
  15083. G(G(t).mutationQueue).An(e);
  15084. }(e.localStore, r)) : q(), n.label = 4;
  15085. case 4:
  15086. return [ 4 /*yield*/ , Ls(e, u) ];
  15087. case 5:
  15088. return n.sent(), [ 3 /*break*/ , 7 ];
  15089. case 6:
  15090. // A throttled tab may not have seen the mutation before it was completed
  15091. // and removed from the mutation queue, in which case we won't have cached
  15092. // the affected documents. In this case we can safely ignore the update
  15093. // since that means we didn't apply the mutation locally at all (if we
  15094. // had, we would have cached the affected documents), and so we will just
  15095. // see any resulting document changes via normal remote document updates
  15096. // as applicable.
  15097. V("SyncEngine", "Cannot apply mutation batch with id: " + r), n.label = 7;
  15098. case 7:
  15099. return [ 2 /*return*/ ];
  15100. }
  15101. }));
  15102. }));
  15103. }
  15104. /** Applies a query target change from a different tab. */
  15105. // PORTING NOTE: Multi-Tab only.
  15106. function Ks(t, r) {
  15107. return e(this, void 0, void 0, (function() {
  15108. var e, i, o, u, a, s, c, l;
  15109. return n(this, (function(n) {
  15110. switch (n.label) {
  15111. case 0:
  15112. return Ys(e = G(t)), Xs(e), !0 !== r || !0 === e.dc ? [ 3 /*break*/ , 3 ] : (i = e.sharedClientState.getAllActiveQueryTargets(),
  15113. [ 4 /*yield*/ , js(e, i.toArray()) ]);
  15114. case 1:
  15115. return o = n.sent(), e.dc = !0, [ 4 /*yield*/ , Ha(e.remoteStore, !0) ];
  15116. case 2:
  15117. for (n.sent(), u = 0, a = o; u < a.length; u++) s = a[u], xa(e.remoteStore, s);
  15118. return [ 3 /*break*/ , 7 ];
  15119. case 3:
  15120. return !1 !== r || !1 === e.dc ? [ 3 /*break*/ , 7 ] : (c = [], l = Promise.resolve(),
  15121. e.rc.forEach((function(t, n) {
  15122. e.sharedClientState.isLocalQueryTarget(n) ? c.push(n) : l = l.then((function() {
  15123. return Fs(e, n), Wu(e.localStore, n,
  15124. /*keepPersistedTargetData=*/ !0);
  15125. })), Aa(e.remoteStore, n);
  15126. })), [ 4 /*yield*/ , l ]);
  15127. case 4:
  15128. return n.sent(), [ 4 /*yield*/ , js(e, c) ];
  15129. case 5:
  15130. return n.sent(),
  15131. // PORTING NOTE: Multi-Tab only.
  15132. function(t) {
  15133. var e = G(t);
  15134. e.cc.forEach((function(t, n) {
  15135. Aa(e.remoteStore, n);
  15136. })), e.ac.fs(), e.cc = new Map, e.uc = new He(ft.comparator);
  15137. }(e), e.dc = !1, [ 4 /*yield*/ , Ha(e.remoteStore, !1) ];
  15138. case 6:
  15139. n.sent(), n.label = 7;
  15140. case 7:
  15141. return [ 2 /*return*/ ];
  15142. }
  15143. }));
  15144. }));
  15145. }
  15146. function js(t, r, i) {
  15147. return e(this, void 0, void 0, (function() {
  15148. var e, i, o, u, a, s, c, l, h, f, d, p, y, v;
  15149. return n(this, (function(n) {
  15150. switch (n.label) {
  15151. case 0:
  15152. e = G(t), i = [], o = [], u = 0, a = r, n.label = 1;
  15153. case 1:
  15154. return u < a.length ? (s = a[u], c = void 0, (l = e.rc.get(s)) && 0 !== l.length ? [ 4 /*yield*/ , zu(e.localStore, In(l[0])) ] : [ 3 /*break*/ , 7 ]) : [ 3 /*break*/ , 13 ];
  15155. case 2:
  15156. // For queries that have a local View, we fetch their current state
  15157. // from LocalStore (as the resume token and the snapshot version
  15158. // might have changed) and reconcile their views with the persisted
  15159. // state (the list of syncedDocuments may have gotten out of sync).
  15160. c = n.sent(), h = 0, f = l, n.label = 3;
  15161. case 3:
  15162. return h < f.length ? (d = f[h], p = e.ic.get(d), [ 4 /*yield*/ , Us(e, p) ]) : [ 3 /*break*/ , 6 ];
  15163. case 4:
  15164. (y = n.sent()).snapshot && o.push(y.snapshot), n.label = 5;
  15165. case 5:
  15166. return h++, [ 3 /*break*/ , 3 ];
  15167. case 6:
  15168. return [ 3 /*break*/ , 11 ];
  15169. case 7:
  15170. return [ 4 /*yield*/ , Yu(e.localStore, s) ];
  15171. case 8:
  15172. return v = n.sent(), [ 4 /*yield*/ , zu(e.localStore, v) ];
  15173. case 9:
  15174. return c = n.sent(), [ 4 /*yield*/ , Is(e, Qs(v), s,
  15175. /*current=*/ !1, c.resumeToken) ];
  15176. case 10:
  15177. n.sent(), n.label = 11;
  15178. case 11:
  15179. i.push(c), n.label = 12;
  15180. case 12:
  15181. return u++, [ 3 /*break*/ , 1 ];
  15182. case 13:
  15183. return [ 2 /*return*/ , (e.sc.Wo(o), i) ];
  15184. }
  15185. }));
  15186. }));
  15187. }
  15188. /**
  15189. * Creates a `Query` object from the specified `Target`. There is no way to
  15190. * obtain the original `Query`, so we synthesize a `Query` from the `Target`
  15191. * object.
  15192. *
  15193. * The synthesized result might be different from the original `Query`, but
  15194. * since the synthesized `Query` should return the same results as the
  15195. * original one (only the presentation of results might differ), the potential
  15196. * difference will not cause issues.
  15197. */
  15198. // PORTING NOTE: Multi-Tab only.
  15199. function Qs(t) {
  15200. return pn(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, "F" /* LimitType.First */ , t.startAt, t.endAt);
  15201. }
  15202. /** Returns the IDs of the clients that are currently active. */
  15203. // PORTING NOTE: Multi-Tab only.
  15204. function zs(t) {
  15205. var e = G(t);
  15206. return G(G(e.localStore).persistence).vi();
  15207. }
  15208. /** Applies a query target change from a different tab. */
  15209. // PORTING NOTE: Multi-Tab only.
  15210. function Ws(t, r, i, o) {
  15211. return e(this, void 0, void 0, (function() {
  15212. var e, u, a, s;
  15213. return n(this, (function(n) {
  15214. switch (n.label) {
  15215. case 0:
  15216. if ((e = G(t)).dc)
  15217. // If we receive a target state notification via WebStorage, we are
  15218. // either already secondary or another tab has taken the primary lease.
  15219. return [ 2 /*return*/ , void V("SyncEngine", "Ignoring unexpected query state notification.") ];
  15220. if (!((u = e.rc.get(r)) && u.length > 0)) return [ 3 /*break*/ , 7 ];
  15221. switch (i) {
  15222. case "current":
  15223. case "not-current":
  15224. return [ 3 /*break*/ , 1 ];
  15225. case "rejected":
  15226. return [ 3 /*break*/ , 4 ];
  15227. }
  15228. return [ 3 /*break*/ , 6 ];
  15229. case 1:
  15230. return [ 4 /*yield*/ , Xu(e.localStore, An(u[0])) ];
  15231. case 2:
  15232. return a = n.sent(), s = Ar.createSynthesizedRemoteEventForCurrentChange(r, "current" === i, Yt.EMPTY_BYTE_STRING),
  15233. [ 4 /*yield*/ , Ls(e, a, s) ];
  15234. case 3:
  15235. return n.sent(), [ 3 /*break*/ , 7 ];
  15236. case 4:
  15237. return [ 4 /*yield*/ , Wu(e.localStore, r,
  15238. /* keepPersistedTargetData */ !0) ];
  15239. case 5:
  15240. return n.sent(), Fs(e, r, o), [ 3 /*break*/ , 7 ];
  15241. case 6:
  15242. q(), n.label = 7;
  15243. case 7:
  15244. return [ 2 /*return*/ ];
  15245. }
  15246. }));
  15247. }));
  15248. }
  15249. /** Adds or removes Watch targets for queries from different tabs. */ function Hs(t, r, i) {
  15250. return e(this, void 0, void 0, (function() {
  15251. var e, o, u, a, s, c, l, h, f, d;
  15252. return n(this, (function(p) {
  15253. switch (p.label) {
  15254. case 0:
  15255. if (!(e = Ys(t)).dc) return [ 3 /*break*/ , 10 ];
  15256. o = 0, u = r, p.label = 1;
  15257. case 1:
  15258. return o < u.length ? (a = u[o], e.rc.has(a) ? (
  15259. // A target might have been added in a previous attempt
  15260. V("SyncEngine", "Adding an already active target " + a), [ 3 /*break*/ , 5 ]) : [ 4 /*yield*/ , Yu(e.localStore, a) ]) : [ 3 /*break*/ , 6 ];
  15261. case 2:
  15262. return s = p.sent(), [ 4 /*yield*/ , zu(e.localStore, s) ];
  15263. case 3:
  15264. return c = p.sent(), [ 4 /*yield*/ , Is(e, Qs(s), c.targetId,
  15265. /*current=*/ !1, c.resumeToken) ];
  15266. case 4:
  15267. p.sent(), xa(e.remoteStore, c), p.label = 5;
  15268. case 5:
  15269. return o++, [ 3 /*break*/ , 1 ];
  15270. case 6:
  15271. l = function(t) {
  15272. return n(this, (function(n) {
  15273. switch (n.label) {
  15274. case 0:
  15275. return e.rc.has(t) ? [ 4 /*yield*/ , Wu(e.localStore, t,
  15276. /* keepPersistedTargetData */ !1).then((function() {
  15277. Aa(e.remoteStore, t), Fs(e, t);
  15278. })).catch(Dt) ] : [ 3 /*break*/ , 2 ];
  15279. // Release queries that are still active.
  15280. case 1:
  15281. // Release queries that are still active.
  15282. n.sent(), n.label = 2;
  15283. case 2:
  15284. return [ 2 /*return*/ ];
  15285. }
  15286. }));
  15287. }, h = 0, f = i, p.label = 7;
  15288. case 7:
  15289. return h < f.length ? (d = f[h], [ 5 /*yield**/ , l(d) ]) : [ 3 /*break*/ , 10 ];
  15290. case 8:
  15291. p.sent(), p.label = 9;
  15292. case 9:
  15293. return h++, [ 3 /*break*/ , 7 ];
  15294. case 10:
  15295. return [ 2 /*return*/ ];
  15296. }
  15297. }));
  15298. }));
  15299. }
  15300. function Ys(t) {
  15301. var e = G(t);
  15302. return e.remoteStore.remoteSyncer.applyRemoteEvent = Ss.bind(null, e), e.remoteStore.remoteSyncer.getRemoteKeysForTarget = qs.bind(null, e),
  15303. e.remoteStore.remoteSyncer.rejectListen = Ds.bind(null, e), e.sc.Wo = us.bind(null, e.eventManager),
  15304. e.sc.wc = as.bind(null, e.eventManager), e;
  15305. }
  15306. function Xs(t) {
  15307. var e = G(t);
  15308. return e.remoteStore.remoteSyncer.applySuccessfulWrite = xs.bind(null, e), e.remoteStore.remoteSyncer.rejectFailedWrite = As.bind(null, e),
  15309. e
  15310. /**
  15311. * Loads a Firestore bundle into the SDK. The returned promise resolves when
  15312. * the bundle finished loading.
  15313. *
  15314. * @param syncEngine - SyncEngine to use.
  15315. * @param bundleReader - Bundle to load into the SDK.
  15316. * @param task - LoadBundleTask used to update the loading progress to public API.
  15317. */;
  15318. }
  15319. function Zs(t, r, i) {
  15320. var o = G(t);
  15321. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  15322. /** Loads a bundle and returns the list of affected collection groups. */
  15323. (function(t, r, i) {
  15324. return e(this, void 0, void 0, (function() {
  15325. var e, o, u, a, s, c;
  15326. return n(this, (function(n) {
  15327. switch (n.label) {
  15328. case 0:
  15329. return n.trys.push([ 0, 14, , 15 ]), [ 4 /*yield*/ , r.getMetadata() ];
  15330. case 1:
  15331. return e = n.sent(), [ 4 /*yield*/ , function(t, e) {
  15332. var n = G(t), r = jr(e.createTime);
  15333. return n.persistence.runTransaction("hasNewerBundle", "readonly", (function(t) {
  15334. return n.Ns.getBundleMetadata(t, e.id);
  15335. })).then((function(t) {
  15336. return !!t && t.createTime.compareTo(r) >= 0;
  15337. }));
  15338. }(t.localStore, e) ];
  15339. case 2:
  15340. return n.sent() ? [ 4 /*yield*/ , r.close() ] : [ 3 /*break*/ , 4 ];
  15341. case 3:
  15342. return [ 2 /*return*/ , (n.sent(), i._completeWith(function(t) {
  15343. return {
  15344. taskState: "Success",
  15345. documentsLoaded: t.totalDocuments,
  15346. bytesLoaded: t.totalBytes,
  15347. totalDocuments: t.totalDocuments,
  15348. totalBytes: t.totalBytes
  15349. };
  15350. }(e)), Promise.resolve(new Set)) ];
  15351. case 4:
  15352. return i._updateProgress(ds(e)), o = new fs(e, t.localStore, r.yt), [ 4 /*yield*/ , r.mc() ];
  15353. case 5:
  15354. u = n.sent(), n.label = 6;
  15355. case 6:
  15356. return u ? [ 4 /*yield*/ , o.Fu(u) ] : [ 3 /*break*/ , 10 ];
  15357. case 7:
  15358. return (a = n.sent()) && i._updateProgress(a), [ 4 /*yield*/ , r.mc() ];
  15359. case 8:
  15360. u = n.sent(), n.label = 9;
  15361. case 9:
  15362. return [ 3 /*break*/ , 6 ];
  15363. case 10:
  15364. return [ 4 /*yield*/ , o.complete() ];
  15365. case 11:
  15366. return s = n.sent(), [ 4 /*yield*/ , Ls(t, s.Lu,
  15367. /* remoteEvent */ void 0) ];
  15368. case 12:
  15369. // Save metadata, so loading the same bundle will skip.
  15370. return n.sent(), [ 4 /*yield*/ , function(t, e) {
  15371. var n = G(t);
  15372. return n.persistence.runTransaction("Save bundle", "readwrite", (function(t) {
  15373. return n.Ns.saveBundleMetadata(t, e);
  15374. }));
  15375. }(t.localStore, e) ];
  15376. case 13:
  15377. return [ 2 /*return*/ , (
  15378. // Save metadata, so loading the same bundle will skip.
  15379. n.sent(), i._completeWith(s.progress), Promise.resolve(s.Bu)) ];
  15380. case 14:
  15381. return c = n.sent(), [ 2 /*return*/ , (L("SyncEngine", "Loading bundle failed with ".concat(c)),
  15382. i._failWith(c), Promise.resolve(new Set)) ];
  15383. case 15:
  15384. return [ 2 /*return*/ ];
  15385. }
  15386. }));
  15387. }));
  15388. }
  15389. /**
  15390. * @license
  15391. * Copyright 2020 Google LLC
  15392. *
  15393. * Licensed under the Apache License, Version 2.0 (the "License");
  15394. * you may not use this file except in compliance with the License.
  15395. * You may obtain a copy of the License at
  15396. *
  15397. * http://www.apache.org/licenses/LICENSE-2.0
  15398. *
  15399. * Unless required by applicable law or agreed to in writing, software
  15400. * distributed under the License is distributed on an "AS IS" BASIS,
  15401. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15402. * See the License for the specific language governing permissions and
  15403. * limitations under the License.
  15404. */
  15405. /**
  15406. * Provides all components needed for Firestore with in-memory persistence.
  15407. * Uses EagerGC garbage collection.
  15408. */)(o, r, i).then((function(t) {
  15409. o.sharedClientState.notifyBundleLoaded(t);
  15410. }));
  15411. }
  15412. var Js = /** @class */ function() {
  15413. function t() {
  15414. this.synchronizeTabs = !1;
  15415. }
  15416. return t.prototype.initialize = function(t) {
  15417. return e(this, void 0, void 0, (function() {
  15418. return n(this, (function(e) {
  15419. switch (e.label) {
  15420. case 0:
  15421. return this.yt = ma(t.databaseInfo.databaseId), this.sharedClientState = this.gc(t),
  15422. this.persistence = this.yc(t), [ 4 /*yield*/ , this.persistence.start() ];
  15423. case 1:
  15424. return e.sent(), this.localStore = this.Ic(t), this.gcScheduler = this.Tc(t, this.localStore),
  15425. this.indexBackfillerScheduler = this.Ec(t, this.localStore), [ 2 /*return*/ ];
  15426. }
  15427. }));
  15428. }));
  15429. }, t.prototype.Tc = function(t, e) {
  15430. return null;
  15431. }, t.prototype.Ec = function(t, e) {
  15432. return null;
  15433. }, t.prototype.Ic = function(t) {
  15434. return qu(this.persistence, new Lu, t.initialUser, this.yt);
  15435. }, t.prototype.yc = function(t) {
  15436. return new Du(Au.Bs, this.yt);
  15437. }, t.prototype.gc = function(t) {
  15438. return new ca;
  15439. }, t.prototype.terminate = function() {
  15440. return e(this, void 0, void 0, (function() {
  15441. return n(this, (function(t) {
  15442. switch (t.label) {
  15443. case 0:
  15444. return this.gcScheduler && this.gcScheduler.stop(), [ 4 /*yield*/ , this.sharedClientState.shutdown() ];
  15445. case 1:
  15446. return t.sent(), [ 4 /*yield*/ , this.persistence.shutdown() ];
  15447. case 2:
  15448. return t.sent(), [ 2 /*return*/ ];
  15449. }
  15450. }));
  15451. }));
  15452. }, t;
  15453. }(), $s = /** @class */ function(r) {
  15454. function i(t, e, n) {
  15455. var i = this;
  15456. return (i = r.call(this) || this).Ac = t, i.cacheSizeBytes = e, i.forceOwnership = n,
  15457. i.synchronizeTabs = !1, i;
  15458. }
  15459. return t(i, r), i.prototype.initialize = function(t) {
  15460. return e(this, void 0, void 0, (function() {
  15461. var e = this;
  15462. return n(this, (function(n) {
  15463. switch (n.label) {
  15464. case 0:
  15465. return [ 4 /*yield*/ , r.prototype.initialize.call(this, t) ];
  15466. case 1:
  15467. return n.sent(), [ 4 /*yield*/ , this.Ac.initialize(this, t) ];
  15468. case 2:
  15469. // Enqueue writes from a previous session
  15470. return n.sent(), [ 4 /*yield*/ , Xs(this.Ac.syncEngine) ];
  15471. case 3:
  15472. // Enqueue writes from a previous session
  15473. return n.sent(), [ 4 /*yield*/ , Ua(this.Ac.remoteStore) ];
  15474. case 4:
  15475. // NOTE: This will immediately call the listener, so we make sure to
  15476. // set it after localStore / remoteStore are started.
  15477. return n.sent(), [ 4 /*yield*/ , this.persistence.li((function() {
  15478. return e.gcScheduler && !e.gcScheduler.started && e.gcScheduler.start(), e.indexBackfillerScheduler && !e.indexBackfillerScheduler.started && e.indexBackfillerScheduler.start(),
  15479. Promise.resolve();
  15480. })) ];
  15481. case 5:
  15482. // NOTE: This will immediately call the listener, so we make sure to
  15483. // set it after localStore / remoteStore are started.
  15484. return n.sent(), [ 2 /*return*/ ];
  15485. }
  15486. }));
  15487. }));
  15488. }, i.prototype.Ic = function(t) {
  15489. return qu(this.persistence, new Lu, t.initialUser, this.yt);
  15490. }, i.prototype.Tc = function(t, e) {
  15491. var n = this.persistence.referenceDelegate.garbageCollector;
  15492. return new ru(n, t.asyncQueue, e);
  15493. }, i.prototype.Ec = function(t, e) {
  15494. var n = new Pt(e, this.persistence);
  15495. return new Lt(t.asyncQueue, n);
  15496. }, i.prototype.yc = function(t) {
  15497. var e = Vu(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? Go.withCacheSize(this.cacheSizeBytes) : Go.DEFAULT;
  15498. return new Fu(this.synchronizeTabs, e, t.clientId, n, t.asyncQueue, ya(), va(), this.yt, this.sharedClientState, !!this.forceOwnership);
  15499. }, i.prototype.gc = function(t) {
  15500. return new ca;
  15501. }, i;
  15502. }(Js), tc = /** @class */ function(r) {
  15503. function i(t, e) {
  15504. var n = this;
  15505. return (n = r.call(this, t, e, /* forceOwnership= */ !1) || this).Ac = t, n.cacheSizeBytes = e,
  15506. n.synchronizeTabs = !0, n;
  15507. }
  15508. return t(i, r), i.prototype.initialize = function(t) {
  15509. return e(this, void 0, void 0, (function() {
  15510. var i, o = this;
  15511. return n(this, (function(u) {
  15512. switch (u.label) {
  15513. case 0:
  15514. return [ 4 /*yield*/ , r.prototype.initialize.call(this, t) ];
  15515. case 1:
  15516. return u.sent(), i = this.Ac.syncEngine, this.sharedClientState instanceof sa ? (this.sharedClientState.syncEngine = {
  15517. Fr: Gs.bind(null, i),
  15518. $r: Ws.bind(null, i),
  15519. Br: Hs.bind(null, i),
  15520. vi: zs.bind(null, i),
  15521. Mr: Bs.bind(null, i)
  15522. }, [ 4 /*yield*/ , this.sharedClientState.start() ]) : [ 3 /*break*/ , 3 ];
  15523. case 2:
  15524. u.sent(), u.label = 3;
  15525. case 3:
  15526. // NOTE: This will immediately call the listener, so we make sure to
  15527. // set it after localStore / remoteStore are started.
  15528. return [ 4 /*yield*/ , this.persistence.li((function(t) {
  15529. return e(o, void 0, void 0, (function() {
  15530. return n(this, (function(e) {
  15531. switch (e.label) {
  15532. case 0:
  15533. return [ 4 /*yield*/ , Ks(this.Ac.syncEngine, t) ];
  15534. case 1:
  15535. return e.sent(), this.gcScheduler && (t && !this.gcScheduler.started ? this.gcScheduler.start() : t || this.gcScheduler.stop()),
  15536. this.indexBackfillerScheduler && (t && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : t || this.indexBackfillerScheduler.stop()),
  15537. [ 2 /*return*/ ];
  15538. }
  15539. }));
  15540. }));
  15541. })) ];
  15542. case 4:
  15543. // NOTE: This will immediately call the listener, so we make sure to
  15544. // set it after localStore / remoteStore are started.
  15545. return u.sent(), [ 2 /*return*/ ];
  15546. }
  15547. }));
  15548. }));
  15549. }, i.prototype.gc = function(t) {
  15550. var e = ya();
  15551. if (!sa.C(e)) throw new j(K.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
  15552. var n = Vu(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey);
  15553. return new sa(e, t.asyncQueue, n, t.clientId, t.initialUser);
  15554. }, i;
  15555. }($s), ec = /** @class */ function() {
  15556. function t() {}
  15557. return t.prototype.initialize = function(t, r) {
  15558. return e(this, void 0, void 0, (function() {
  15559. var e = this;
  15560. return n(this, (function(n) {
  15561. switch (n.label) {
  15562. case 0:
  15563. return this.localStore ? [ 3 /*break*/ , 2 ] : (this.localStore = t.localStore,
  15564. this.sharedClientState = t.sharedClientState, this.datastore = this.createDatastore(r),
  15565. this.remoteStore = this.createRemoteStore(r), this.eventManager = this.createEventManager(r),
  15566. this.syncEngine = this.createSyncEngine(r,
  15567. /* startAsPrimary=*/ !t.synchronizeTabs), this.sharedClientState.onlineStateHandler = function(t) {
  15568. return _s(e.syncEngine, t, 1 /* OnlineStateSource.SharedClientState */);
  15569. }, this.remoteStore.remoteSyncer.handleCredentialChange = Ps.bind(null, this.syncEngine),
  15570. [ 4 /*yield*/ , Ha(this.remoteStore, this.syncEngine.isPrimaryClient) ]);
  15571. case 1:
  15572. n.sent(), n.label = 2;
  15573. case 2:
  15574. return [ 2 /*return*/ ];
  15575. }
  15576. }));
  15577. }));
  15578. }, t.prototype.createEventManager = function(t) {
  15579. return new rs;
  15580. }, t.prototype.createDatastore = function(t) {
  15581. var e, n = ma(t.databaseInfo.databaseId), r = (e = t.databaseInfo, new pa(e));
  15582. /** Return the Platform-specific connectivity monitor. */ return function(t, e, n, r) {
  15583. return new Ta(t, e, n, r);
  15584. }(t.authCredentials, t.appCheckCredentials, r, n);
  15585. }, t.prototype.createRemoteStore = function(t) {
  15586. var e, n, r, i, o, u = this;
  15587. return e = this.localStore, n = this.datastore, r = t.asyncQueue, i = function(t) {
  15588. return _s(u.syncEngine, t, 0 /* OnlineStateSource.RemoteStore */);
  15589. }, o = ha.C() ? new ha : new la, new Sa(e, n, r, i, o);
  15590. }, t.prototype.createSyncEngine = function(t, e) {
  15591. return function(t, e, n,
  15592. // PORTING NOTE: Manages state synchronization in multi-tab environments.
  15593. r, i, o, u) {
  15594. var a = new ws(t, e, n, r, i, o);
  15595. return u && (a.dc = !0), a;
  15596. }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, t.initialUser, t.maxConcurrentLimboResolutions, e);
  15597. }, t.prototype.terminate = function() {
  15598. return function(t) {
  15599. return e(this, void 0, void 0, (function() {
  15600. var e;
  15601. return n(this, (function(n) {
  15602. switch (n.label) {
  15603. case 0:
  15604. return e = G(t), V("RemoteStore", "RemoteStore shutting down."), e._u.add(5 /* OfflineCause.Shutdown */),
  15605. [ 4 /*yield*/ , Da(e) ];
  15606. case 1:
  15607. return n.sent(), e.mu.shutdown(),
  15608. // Set the OnlineState to Unknown (rather than Offline) to avoid potentially
  15609. // triggering spurious listener events with cached data, etc.
  15610. e.gu.set("Unknown" /* OnlineState.Unknown */), [ 2 /*return*/ ];
  15611. }
  15612. }));
  15613. }));
  15614. }(this.remoteStore);
  15615. }, t;
  15616. }();
  15617. /**
  15618. * Provides all components needed for Firestore with IndexedDB persistence.
  15619. */
  15620. /**
  15621. * @license
  15622. * Copyright 2017 Google LLC
  15623. *
  15624. * Licensed under the Apache License, Version 2.0 (the "License");
  15625. * you may not use this file except in compliance with the License.
  15626. * You may obtain a copy of the License at
  15627. *
  15628. * http://www.apache.org/licenses/LICENSE-2.0
  15629. *
  15630. * Unless required by applicable law or agreed to in writing, software
  15631. * distributed under the License is distributed on an "AS IS" BASIS,
  15632. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15633. * See the License for the specific language governing permissions and
  15634. * limitations under the License.
  15635. */
  15636. function nc(t, e, n) {
  15637. if (!n) throw new j(K.INVALID_ARGUMENT, "Function ".concat(t, "() cannot be called with an empty ").concat(e, "."));
  15638. }
  15639. /**
  15640. * Validates that two boolean options are not set at the same time.
  15641. * @internal
  15642. */ function rc(t, e, n, r) {
  15643. if (!0 === e && !0 === r) throw new j(K.INVALID_ARGUMENT, "".concat(t, " and ").concat(n, " cannot be used together."));
  15644. }
  15645. /**
  15646. * Validates that `path` refers to a document (indicated by the fact it contains
  15647. * an even numbers of segments).
  15648. */ function ic(t) {
  15649. if (!ft.isDocumentKey(t)) throw new j(K.INVALID_ARGUMENT, "Invalid document reference. Document references must have an even number of segments, but ".concat(t, " has ").concat(t.length, "."));
  15650. }
  15651. /**
  15652. * Validates that `path` refers to a collection (indicated by the fact it
  15653. * contains an odd numbers of segments).
  15654. */ function oc(t) {
  15655. if (ft.isDocumentKey(t)) throw new j(K.INVALID_ARGUMENT, "Invalid collection reference. Collection references must have an odd number of segments, but ".concat(t, " has ").concat(t.length, "."));
  15656. }
  15657. /**
  15658. * Returns true if it's a non-null object without a custom prototype
  15659. * (i.e. excludes Array, Date, etc.).
  15660. */
  15661. /** Returns a string describing the type / value of the provided input. */ function uc(t) {
  15662. if (void 0 === t) return "undefined";
  15663. if (null === t) return "null";
  15664. if ("string" == typeof t) return t.length > 20 && (t = "".concat(t.substring(0, 20), "...")),
  15665. JSON.stringify(t);
  15666. if ("number" == typeof t || "boolean" == typeof t) return "" + t;
  15667. if ("object" == typeof t) {
  15668. if (t instanceof Array) return "an array";
  15669. var e =
  15670. /** try to get the constructor name for an object. */
  15671. function(t) {
  15672. return t.constructor ? t.constructor.name : null;
  15673. }(t);
  15674. return e ? "a custom ".concat(e, " object") : "an object";
  15675. }
  15676. return "function" == typeof t ? "a function" : q();
  15677. }
  15678. function ac(t,
  15679. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15680. e) {
  15681. if ("_delegate" in t && (
  15682. // Unwrap Compat types
  15683. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15684. t = t._delegate), !(t instanceof e)) {
  15685. if (e.name === t.constructor.name) throw new j(K.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
  15686. var n = uc(t);
  15687. throw new j(K.INVALID_ARGUMENT, "Expected type '".concat(e.name, "', but it was: ").concat(n));
  15688. }
  15689. return t;
  15690. }
  15691. function sc(t, e) {
  15692. if (e <= 0) throw new j(K.INVALID_ARGUMENT, "Function ".concat(t, "() requires a positive number, but it was: ").concat(e, "."));
  15693. }
  15694. /**
  15695. * @license
  15696. * Copyright 2020 Google LLC
  15697. *
  15698. * Licensed under the Apache License, Version 2.0 (the "License");
  15699. * you may not use this file except in compliance with the License.
  15700. * You may obtain a copy of the License at
  15701. *
  15702. * http://www.apache.org/licenses/LICENSE-2.0
  15703. *
  15704. * Unless required by applicable law or agreed to in writing, software
  15705. * distributed under the License is distributed on an "AS IS" BASIS,
  15706. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15707. * See the License for the specific language governing permissions and
  15708. * limitations under the License.
  15709. */ var cc = new Map, lc = /** @class */ function() {
  15710. function t(t) {
  15711. var e;
  15712. if (void 0 === t.host) {
  15713. if (void 0 !== t.ssl) throw new j(K.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
  15714. this.host = "firestore.googleapis.com", this.ssl = !0;
  15715. } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;
  15716. if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties,
  15717. void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {
  15718. if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new j(K.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  15719. this.cacheSizeBytes = t.cacheSizeBytes;
  15720. }
  15721. this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling,
  15722. this.useFetchStreams = !!t.useFetchStreams, rc("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling);
  15723. }
  15724. return t.prototype.isEqual = function(t) {
  15725. return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams;
  15726. }, t;
  15727. }(), hc = /** @class */ function() {
  15728. /** @hideconstructor */
  15729. function t(t, e, n, r) {
  15730. this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = n,
  15731. this._app = r,
  15732. /**
  15733. * Whether it's a Firestore or Firestore Lite instance.
  15734. */
  15735. this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new lc({}),
  15736. this._settingsFrozen = !1;
  15737. }
  15738. return Object.defineProperty(t.prototype, "app", {
  15739. /**
  15740. * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
  15741. * instance.
  15742. */
  15743. get: function() {
  15744. if (!this._app) throw new j(K.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
  15745. return this._app;
  15746. },
  15747. enumerable: !1,
  15748. configurable: !0
  15749. }), Object.defineProperty(t.prototype, "_initialized", {
  15750. get: function() {
  15751. return this._settingsFrozen;
  15752. },
  15753. enumerable: !1,
  15754. configurable: !0
  15755. }), Object.defineProperty(t.prototype, "_terminated", {
  15756. get: function() {
  15757. return void 0 !== this._terminateTask;
  15758. },
  15759. enumerable: !1,
  15760. configurable: !0
  15761. }), t.prototype._setSettings = function(t) {
  15762. if (this._settingsFrozen) throw new j(K.FAILED_PRECONDITION, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");
  15763. this._settings = new lc(t), void 0 !== t.credentials && (this._authCredentials = function(t) {
  15764. if (!t) return new W;
  15765. switch (t.type) {
  15766. case "gapi":
  15767. var e = t.client;
  15768. return new Z(e, t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null);
  15769. case "provider":
  15770. return t.client;
  15771. default:
  15772. throw new j(K.INVALID_ARGUMENT, "makeAuthCredentialsProvider failed due to invalid credential type");
  15773. }
  15774. }(t.credentials));
  15775. }, t.prototype._getSettings = function() {
  15776. return this._settings;
  15777. }, t.prototype._freezeSettings = function() {
  15778. return this._settingsFrozen = !0, this._settings;
  15779. }, t.prototype._delete = function() {
  15780. return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;
  15781. },
  15782. /** Returns a JSON-serializable representation of this `Firestore` instance. */ t.prototype.toJSON = function() {
  15783. return {
  15784. app: this._app,
  15785. databaseId: this._databaseId,
  15786. settings: this._settings
  15787. };
  15788. },
  15789. /**
  15790. * Terminates all components used by this client. Subclasses can override
  15791. * this method to clean up their own dependencies, but must also call this
  15792. * method.
  15793. *
  15794. * Only ever called once.
  15795. */
  15796. t.prototype._terminate = function() {
  15797. /**
  15798. * Removes all components associated with the provided instance. Must be called
  15799. * when the `Firestore` instance is terminated.
  15800. */
  15801. return t = this, (e = cc.get(t)) && (V("ComponentProvider", "Removing Datastore"),
  15802. cc.delete(t), e.terminate()), Promise.resolve();
  15803. var t, e;
  15804. }, t;
  15805. }();
  15806. /**
  15807. * An instance map that ensures only one Datastore exists per Firestore
  15808. * instance.
  15809. */
  15810. /**
  15811. * A concrete type describing all the values that can be applied via a
  15812. * user-supplied `FirestoreSettings` object. This is a separate type so that
  15813. * defaults can be supplied and the value can be checked for equality.
  15814. */
  15815. /**
  15816. * Modify this instance to communicate with the Cloud Firestore emulator.
  15817. *
  15818. * Note: This must be called before this instance has been used to do any
  15819. * operations.
  15820. *
  15821. * @param firestore - The `Firestore` instance to configure to connect to the
  15822. * emulator.
  15823. * @param host - the emulator host (ex: localhost).
  15824. * @param port - the emulator port (ex: 9000).
  15825. * @param options.mockUserToken - the mock auth token to use for unit testing
  15826. * Security Rules.
  15827. */
  15828. function fc(t, e, n, r) {
  15829. var i;
  15830. void 0 === r && (r = {});
  15831. var o = (t = ac(t, hc))._getSettings();
  15832. if ("firestore.googleapis.com" !== o.host && o.host !== e && L("Host has been set in both settings() and useEmulator(), emulator host will be used"),
  15833. t._setSettings(Object.assign(Object.assign({}, o), {
  15834. host: "".concat(e, ":").concat(n),
  15835. ssl: !1
  15836. })), r.mockUserToken) {
  15837. var u, a;
  15838. if ("string" == typeof r.mockUserToken) u = r.mockUserToken, a = N.MOCK_USER; else {
  15839. // Let createMockUserToken validate first (catches common mistakes like
  15840. // invalid field "uid" and missing field "sub" / "user_id".)
  15841. u = m(r.mockUserToken, null === (i = t._app) || void 0 === i ? void 0 : i.options.projectId);
  15842. var s = r.mockUserToken.sub || r.mockUserToken.user_id;
  15843. if (!s) throw new j(K.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!");
  15844. a = new N(s);
  15845. }
  15846. t._authCredentials = new H(new z(u, a));
  15847. }
  15848. }
  15849. /**
  15850. * @license
  15851. * Copyright 2020 Google LLC
  15852. *
  15853. * Licensed under the Apache License, Version 2.0 (the "License");
  15854. * you may not use this file except in compliance with the License.
  15855. * You may obtain a copy of the License at
  15856. *
  15857. * http://www.apache.org/licenses/LICENSE-2.0
  15858. *
  15859. * Unless required by applicable law or agreed to in writing, software
  15860. * distributed under the License is distributed on an "AS IS" BASIS,
  15861. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15862. * See the License for the specific language governing permissions and
  15863. * limitations under the License.
  15864. */
  15865. /**
  15866. * A `DocumentReference` refers to a document location in a Firestore database
  15867. * and can be used to write, read, or listen to the location. The document at
  15868. * the referenced location may or may not exist.
  15869. */ var dc = /** @class */ function() {
  15870. /** @hideconstructor */
  15871. function t(t,
  15872. /**
  15873. * If provided, the `FirestoreDataConverter` associated with this instance.
  15874. */
  15875. e, n) {
  15876. this.converter = e, this._key = n,
  15877. /** The type of this Firestore reference. */
  15878. this.type = "document", this.firestore = t;
  15879. }
  15880. return Object.defineProperty(t.prototype, "_path", {
  15881. get: function() {
  15882. return this._key.path;
  15883. },
  15884. enumerable: !1,
  15885. configurable: !0
  15886. }), Object.defineProperty(t.prototype, "id", {
  15887. /**
  15888. * The document's identifier within its collection.
  15889. */
  15890. get: function() {
  15891. return this._key.path.lastSegment();
  15892. },
  15893. enumerable: !1,
  15894. configurable: !0
  15895. }), Object.defineProperty(t.prototype, "path", {
  15896. /**
  15897. * A string representing the path of the referenced document (relative
  15898. * to the root of the database).
  15899. */
  15900. get: function() {
  15901. return this._key.path.canonicalString();
  15902. },
  15903. enumerable: !1,
  15904. configurable: !0
  15905. }), Object.defineProperty(t.prototype, "parent", {
  15906. /**
  15907. * The collection this `DocumentReference` belongs to.
  15908. */
  15909. get: function() {
  15910. return new yc(this.firestore, this.converter, this._key.path.popLast());
  15911. },
  15912. enumerable: !1,
  15913. configurable: !0
  15914. }), t.prototype.withConverter = function(e) {
  15915. return new t(this.firestore, e, this._key);
  15916. }, t;
  15917. }(), pc = /** @class */ function() {
  15918. // This is the lite version of the Query class in the main SDK.
  15919. /** @hideconstructor protected */
  15920. function t(t,
  15921. /**
  15922. * If provided, the `FirestoreDataConverter` associated with this instance.
  15923. */
  15924. e, n) {
  15925. this.converter = e, this._query = n,
  15926. /** The type of this Firestore reference. */
  15927. this.type = "query", this.firestore = t;
  15928. }
  15929. return t.prototype.withConverter = function(e) {
  15930. return new t(this.firestore, e, this._query);
  15931. }, t;
  15932. }(), yc = /** @class */ function(e) {
  15933. /** @hideconstructor */
  15934. function n(t, n, r) {
  15935. var i = this;
  15936. return (i = e.call(this, t, n, yn(r)) || this)._path = r,
  15937. /** The type of this Firestore reference. */
  15938. i.type = "collection", i;
  15939. }
  15940. return t(n, e), Object.defineProperty(n.prototype, "id", {
  15941. /** The collection's identifier. */ get: function() {
  15942. return this._query.path.lastSegment();
  15943. },
  15944. enumerable: !1,
  15945. configurable: !0
  15946. }), Object.defineProperty(n.prototype, "path", {
  15947. /**
  15948. * A string representing the path of the referenced collection (relative
  15949. * to the root of the database).
  15950. */
  15951. get: function() {
  15952. return this._query.path.canonicalString();
  15953. },
  15954. enumerable: !1,
  15955. configurable: !0
  15956. }), Object.defineProperty(n.prototype, "parent", {
  15957. /**
  15958. * A reference to the containing `DocumentReference` if this is a
  15959. * subcollection. If this isn't a subcollection, the reference is null.
  15960. */
  15961. get: function() {
  15962. var t = this._path.popLast();
  15963. return t.isEmpty() ? null : new dc(this.firestore,
  15964. /* converter= */ null, new ft(t));
  15965. },
  15966. enumerable: !1,
  15967. configurable: !0
  15968. }), n.prototype.withConverter = function(t) {
  15969. return new n(this.firestore, t, this._path);
  15970. }, n;
  15971. }(pc);
  15972. /**
  15973. * A `Query` refers to a query which you can read or listen to. You can also
  15974. * construct refined `Query` objects by adding filters and ordering.
  15975. */ function vc(t, e) {
  15976. for (var n = [], i = 2; i < arguments.length; i++) n[i - 2] = arguments[i];
  15977. if (t = y(t), nc("collection", "path", e), t instanceof hc) {
  15978. var o = ct.fromString.apply(ct, r([ e ], n, !1));
  15979. return oc(o), new yc(t, /* converter= */ null, o);
  15980. }
  15981. if (!(t instanceof dc || t instanceof yc)) throw new j(K.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  15982. var u = t._path.child(ct.fromString.apply(ct, r([ e ], n, !1)));
  15983. return oc(u), new yc(t.firestore,
  15984. /* converter= */ null, u);
  15985. }
  15986. // TODO(firestorelite): Consider using ErrorFactory -
  15987. // https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106
  15988. /**
  15989. * Creates and returns a new `Query` instance that includes all documents in the
  15990. * database that are contained in a collection or subcollection with the
  15991. * given `collectionId`.
  15992. *
  15993. * @param firestore - A reference to the root `Firestore` instance.
  15994. * @param collectionId - Identifies the collections to query over. Every
  15995. * collection or subcollection with this ID as the last segment of its path
  15996. * will be included. Cannot contain a slash.
  15997. * @returns The created `Query`.
  15998. */ function mc(t, e) {
  15999. if (t = ac(t, hc), nc("collectionGroup", "collection id", e), e.indexOf("/") >= 0) throw new j(K.INVALID_ARGUMENT, "Invalid collection ID '".concat(e, "' passed to function collectionGroup(). Collection IDs must not contain '/'."));
  16000. return new pc(t,
  16001. /* converter= */ null, function(t) {
  16002. return new dn(ct.emptyPath(), t);
  16003. }(e));
  16004. }
  16005. function gc(t, e) {
  16006. for (var n = [], i = 2; i < arguments.length; i++) n[i - 2] = arguments[i];
  16007. if (t = y(t),
  16008. // We allow omission of 'pathString' but explicitly prohibit passing in both
  16009. // 'undefined' and 'null'.
  16010. 1 === arguments.length && (e = nt.R()), nc("doc", "path", e), t instanceof hc) {
  16011. var o = ct.fromString.apply(ct, r([ e ], n, !1));
  16012. return ic(o), new dc(t,
  16013. /* converter= */ null, new ft(o));
  16014. }
  16015. if (!(t instanceof dc || t instanceof yc)) throw new j(K.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  16016. var u = t._path.child(ct.fromString.apply(ct, r([ e ], n, !1)));
  16017. return ic(u), new dc(t.firestore, t instanceof yc ? t.converter : null, new ft(u));
  16018. }
  16019. /**
  16020. * Returns true if the provided references are equal.
  16021. *
  16022. * @param left - A reference to compare.
  16023. * @param right - A reference to compare.
  16024. * @returns true if the references point to the same location in the same
  16025. * Firestore database.
  16026. */ function wc(t, e) {
  16027. return t = y(t), e = y(e), (t instanceof dc || t instanceof yc) && (e instanceof dc || e instanceof yc) && t.firestore === e.firestore && t.path === e.path && t.converter === e.converter
  16028. /**
  16029. * Returns true if the provided queries point to the same collection and apply
  16030. * the same constraints.
  16031. *
  16032. * @param left - A `Query` to compare.
  16033. * @param right - A `Query` to compare.
  16034. * @returns true if the references point to the same location in the same
  16035. * Firestore database.
  16036. */;
  16037. }
  16038. function bc(t, e) {
  16039. return t = y(t), e = y(e), t instanceof pc && e instanceof pc && t.firestore === e.firestore && Sn(t._query, e._query) && t.converter === e.converter
  16040. /**
  16041. * @license
  16042. * Copyright 2020 Google LLC
  16043. *
  16044. * Licensed under the Apache License, Version 2.0 (the "License");
  16045. * you may not use this file except in compliance with the License.
  16046. * You may obtain a copy of the License at
  16047. *
  16048. * http://www.apache.org/licenses/LICENSE-2.0
  16049. *
  16050. * Unless required by applicable law or agreed to in writing, software
  16051. * distributed under the License is distributed on an "AS IS" BASIS,
  16052. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16053. * See the License for the specific language governing permissions and
  16054. * limitations under the License.
  16055. */
  16056. /**
  16057. * How many bytes to read each time when `ReadableStreamReader.read()` is
  16058. * called. Only applicable for byte streams that we control (e.g. those backed
  16059. * by an UInt8Array).
  16060. */
  16061. /**
  16062. * Builds a `ByteStreamReader` from a UInt8Array.
  16063. * @param source - The data source to use.
  16064. * @param bytesPerRead - How many bytes each `read()` from the returned reader
  16065. * will read.
  16066. */;
  16067. }
  16068. function Ic(t, r) {
  16069. void 0 === r && (r = 10240);
  16070. var i = 0;
  16071. // The TypeScript definition for ReadableStreamReader changed. We use
  16072. // `any` here to allow this code to compile with different versions.
  16073. // See https://github.com/microsoft/TypeScript/issues/42970
  16074. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16075. return {
  16076. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16077. read: function() {
  16078. return e(this, void 0, void 0, (function() {
  16079. var e;
  16080. return n(this, (function(n) {
  16081. return i < t.byteLength ? (e = {
  16082. value: t.slice(i, i + r),
  16083. done: !1
  16084. }, [ 2 /*return*/ , (i += r, e) ]) : [ 2 /*return*/ , {
  16085. done: !0
  16086. } ];
  16087. }));
  16088. }));
  16089. },
  16090. cancel: function() {
  16091. return e(this, void 0, void 0, (function() {
  16092. return n(this, (function(t) {
  16093. return [ 2 /*return*/ ];
  16094. }));
  16095. }));
  16096. },
  16097. releaseLock: function() {},
  16098. closed: Promise.reject("unimplemented")
  16099. };
  16100. }
  16101. /**
  16102. * @license
  16103. * Copyright 2020 Google LLC
  16104. *
  16105. * Licensed under the Apache License, Version 2.0 (the "License");
  16106. * you may not use this file except in compliance with the License.
  16107. * You may obtain a copy of the License at
  16108. *
  16109. * http://www.apache.org/licenses/LICENSE-2.0
  16110. *
  16111. * Unless required by applicable law or agreed to in writing, software
  16112. * distributed under the License is distributed on an "AS IS" BASIS,
  16113. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16114. * See the License for the specific language governing permissions and
  16115. * limitations under the License.
  16116. */
  16117. /**
  16118. * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.
  16119. */
  16120. /**
  16121. * @license
  16122. * Copyright 2017 Google LLC
  16123. *
  16124. * Licensed under the Apache License, Version 2.0 (the "License");
  16125. * you may not use this file except in compliance with the License.
  16126. * You may obtain a copy of the License at
  16127. *
  16128. * http://www.apache.org/licenses/LICENSE-2.0
  16129. *
  16130. * Unless required by applicable law or agreed to in writing, software
  16131. * distributed under the License is distributed on an "AS IS" BASIS,
  16132. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16133. * See the License for the specific language governing permissions and
  16134. * limitations under the License.
  16135. */
  16136. /*
  16137. * A wrapper implementation of Observer<T> that will dispatch events
  16138. * asynchronously. To allow immediate silencing, a mute call is added which
  16139. * causes events scheduled to no longer be raised.
  16140. */ var Tc = /** @class */ function() {
  16141. function t(t) {
  16142. this.observer = t,
  16143. /**
  16144. * When set to true, will not raise future events. Necessary to deal with
  16145. * async detachment of listener.
  16146. */
  16147. this.muted = !1;
  16148. }
  16149. return t.prototype.next = function(t) {
  16150. this.observer.next && this.Rc(this.observer.next, t);
  16151. }, t.prototype.error = function(t) {
  16152. this.observer.error ? this.Rc(this.observer.error, t) : M("Uncaught Error in snapshot listener:", t.toString());
  16153. }, t.prototype.bc = function() {
  16154. this.muted = !0;
  16155. }, t.prototype.Rc = function(t, e) {
  16156. var n = this;
  16157. this.muted || setTimeout((function() {
  16158. n.muted || t(e);
  16159. }), 0);
  16160. }, t;
  16161. }(), Ec = /** @class */ function() {
  16162. function t(
  16163. /** The reader to read from underlying binary bundle data source. */
  16164. t, e) {
  16165. var n = this;
  16166. this.Pc = t, this.yt = e,
  16167. /** Cached bundle metadata. */
  16168. this.metadata = new Q,
  16169. /**
  16170. * Internal buffer to hold bundle content, accumulating incomplete element
  16171. * content.
  16172. */
  16173. this.buffer = new Uint8Array, this.vc = new TextDecoder("utf-8"),
  16174. // Read the metadata (which is the first element).
  16175. this.Vc().then((function(t) {
  16176. t && t.Ou() ? n.metadata.resolve(t.ku.metadata) : n.metadata.reject(new Error("The first element of the bundle is not a metadata, it is\n ".concat(JSON.stringify(null == t ? void 0 : t.ku))));
  16177. }), (function(t) {
  16178. return n.metadata.reject(t);
  16179. }));
  16180. }
  16181. return t.prototype.close = function() {
  16182. return this.Pc.cancel();
  16183. }, t.prototype.getMetadata = function() {
  16184. return e(this, void 0, void 0, (function() {
  16185. return n(this, (function(t) {
  16186. return [ 2 /*return*/ , this.metadata.promise ];
  16187. }));
  16188. }));
  16189. }, t.prototype.mc = function() {
  16190. return e(this, void 0, void 0, (function() {
  16191. return n(this, (function(t) {
  16192. switch (t.label) {
  16193. case 0:
  16194. return [ 4 /*yield*/ , this.getMetadata() ];
  16195. case 1:
  16196. // Makes sure metadata is read before proceeding.
  16197. return [ 2 /*return*/ , (t.sent(), this.Vc()) ];
  16198. }
  16199. }));
  16200. }));
  16201. },
  16202. /**
  16203. * Reads from the head of internal buffer, and pulling more data from
  16204. * underlying stream if a complete element cannot be found, until an
  16205. * element(including the prefixed length and the JSON string) is found.
  16206. *
  16207. * Once a complete element is read, it is dropped from internal buffer.
  16208. *
  16209. * Returns either the bundled element, or null if we have reached the end of
  16210. * the stream.
  16211. */
  16212. t.prototype.Vc = function() {
  16213. return e(this, void 0, void 0, (function() {
  16214. var t, e, r, i;
  16215. return n(this, (function(n) {
  16216. switch (n.label) {
  16217. case 0:
  16218. return [ 4 /*yield*/ , this.Sc() ];
  16219. case 1:
  16220. return null === (t = n.sent()) ? [ 2 /*return*/ , null ] : (e = this.vc.decode(t),
  16221. r = Number(e), isNaN(r) && this.Dc("length string (".concat(e, ") is not valid number")),
  16222. [ 4 /*yield*/ , this.Cc(r) ]);
  16223. case 2:
  16224. return i = n.sent(), [ 2 /*return*/ , new ls(JSON.parse(i), t.length + r) ];
  16225. }
  16226. }));
  16227. }));
  16228. },
  16229. /** First index of '{' from the underlying buffer. */ t.prototype.xc = function() {
  16230. return this.buffer.findIndex((function(t) {
  16231. return t === "{".charCodeAt(0);
  16232. }));
  16233. },
  16234. /**
  16235. * Reads from the beginning of the internal buffer, until the first '{', and
  16236. * return the content.
  16237. *
  16238. * If reached end of the stream, returns a null.
  16239. */
  16240. t.prototype.Sc = function() {
  16241. return e(this, void 0, void 0, (function() {
  16242. var t, e;
  16243. return n(this, (function(n) {
  16244. switch (n.label) {
  16245. case 0:
  16246. return this.xc() < 0 ? [ 4 /*yield*/ , this.Nc() ] : [ 3 /*break*/ , 3 ];
  16247. case 1:
  16248. if (n.sent()) return [ 3 /*break*/ , 3 ];
  16249. n.label = 2;
  16250. case 2:
  16251. return [ 3 /*break*/ , 0 ];
  16252. case 3:
  16253. // Broke out of the loop because underlying stream is closed, and there
  16254. // happens to be no more data to process.
  16255. return 0 === this.buffer.length ? [ 2 /*return*/ , null ] : (
  16256. // Broke out of the loop because underlying stream is closed, but still
  16257. // cannot find an open bracket.
  16258. (t = this.xc()) < 0 && this.Dc("Reached the end of bundle when a length string is expected."),
  16259. e = this.buffer.slice(0, t), [ 2 /*return*/ , (this.buffer = this.buffer.slice(t),
  16260. e) ]);
  16261. }
  16262. }));
  16263. }));
  16264. },
  16265. /**
  16266. * Reads from a specified position from the internal buffer, for a specified
  16267. * number of bytes, pulling more data from the underlying stream if needed.
  16268. *
  16269. * Returns a string decoded from the read bytes.
  16270. */
  16271. t.prototype.Cc = function(t) {
  16272. return e(this, void 0, void 0, (function() {
  16273. var e;
  16274. return n(this, (function(n) {
  16275. switch (n.label) {
  16276. case 0:
  16277. return this.buffer.length < t ? [ 4 /*yield*/ , this.Nc() ] : [ 3 /*break*/ , 3 ];
  16278. case 1:
  16279. n.sent() && this.Dc("Reached the end of bundle when more is expected."), n.label = 2;
  16280. case 2:
  16281. return [ 3 /*break*/ , 0 ];
  16282. case 3:
  16283. // Update the internal buffer to drop the read json string.
  16284. return e = this.vc.decode(this.buffer.slice(0, t)), [ 2 /*return*/ , (this.buffer = this.buffer.slice(t),
  16285. e) ];
  16286. }
  16287. }));
  16288. }));
  16289. }, t.prototype.Dc = function(t) {
  16290. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  16291. throw this.Pc.cancel(), new Error("Invalid bundle format: ".concat(t));
  16292. },
  16293. /**
  16294. * Pulls more data from underlying stream to internal buffer.
  16295. * Returns a boolean indicating whether the stream is finished.
  16296. */
  16297. t.prototype.Nc = function() {
  16298. return e(this, void 0, void 0, (function() {
  16299. var t, e;
  16300. return n(this, (function(n) {
  16301. switch (n.label) {
  16302. case 0:
  16303. return [ 4 /*yield*/ , this.Pc.read() ];
  16304. case 1:
  16305. return (t = n.sent()).done || ((e = new Uint8Array(this.buffer.length + t.value.length)).set(this.buffer),
  16306. e.set(t.value, this.buffer.length), this.buffer = e), [ 2 /*return*/ , t.done ];
  16307. }
  16308. }));
  16309. }));
  16310. }, t;
  16311. }(), Sc = function() {
  16312. /** A type string to uniquely identify instances of this class. */
  16313. this.type = "AggregateField";
  16314. }, _c = /** @class */ function() {
  16315. /** @hideconstructor */
  16316. function t(t, e) {
  16317. this._data = e,
  16318. /** A type string to uniquely identify instances of this class. */
  16319. this.type = "AggregateQuerySnapshot", this.query = t
  16320. /**
  16321. * Returns the results of the aggregations performed over the underlying
  16322. * query.
  16323. *
  16324. * The keys of the returned object will be the same as those of the
  16325. * `AggregateSpec` object specified to the aggregation method, and the values
  16326. * will be the corresponding aggregation result.
  16327. *
  16328. * @returns The results of the aggregations performed over the underlying
  16329. * query.
  16330. */;
  16331. }
  16332. return t.prototype.data = function() {
  16333. return this._data;
  16334. }, t;
  16335. }(), Dc = /** @class */ function() {
  16336. function t(t, e, n) {
  16337. this.query = t, this.datastore = e, this.userDataWriter = n;
  16338. }
  16339. return t.prototype.run = function() {
  16340. var t = this;
  16341. // TODO(firestorexp): Make sure there is only one Datastore instance per
  16342. // firestore-exp client.
  16343. return function(t, r) {
  16344. return e(this, void 0, void 0, (function() {
  16345. var e, i, o;
  16346. return n(this, (function(n) {
  16347. switch (n.label) {
  16348. case 0:
  16349. return e = G(t), i = function(t, e) {
  16350. var n = ii(t, e);
  16351. return {
  16352. structuredAggregationQuery: {
  16353. aggregations: [ {
  16354. count: {},
  16355. alias: "count_alias"
  16356. } ],
  16357. structuredQuery: n.structuredQuery
  16358. },
  16359. parent: n.parent
  16360. };
  16361. }(e.yt, In(r)), o = i.parent, e.connection.co || delete i.parent, [ 4 /*yield*/ , e._o("RunAggregationQuery", o, i, /*expectedResponseCount=*/ 1) ];
  16362. case 1:
  16363. return [ 2 /*return*/ , n.sent().filter((function(t) {
  16364. return !!t.result;
  16365. })).map((function(t) {
  16366. return t.result.aggregateFields;
  16367. })) ];
  16368. }
  16369. }));
  16370. }));
  16371. }(this.datastore, this.query._query).then((function(e) {
  16372. U(void 0 !== e[0]);
  16373. var n = Object.entries(e[0]).filter((function(t) {
  16374. var e = t[0];
  16375. return t[1], "count_alias" === e;
  16376. })).map((function(e) {
  16377. e[0];
  16378. var n = e[1];
  16379. return t.userDataWriter.convertValue(n);
  16380. }))[0];
  16381. return U("number" == typeof n), Promise.resolve(new _c(t.query, {
  16382. count: n
  16383. }));
  16384. }));
  16385. }, t;
  16386. }(), xc = /** @class */ function() {
  16387. function t(t) {
  16388. this.datastore = t,
  16389. // The version of each document that was read during this transaction.
  16390. this.readVersions = new Map, this.mutations = [], this.committed = !1,
  16391. /**
  16392. * A deferred usage error that occurred previously in this transaction that
  16393. * will cause the transaction to fail once it actually commits.
  16394. */
  16395. this.lastWriteError = null,
  16396. /**
  16397. * Set of documents that have been written in the transaction.
  16398. *
  16399. * When there's more than one write to the same key in a transaction, any
  16400. * writes after the first are handled differently.
  16401. */
  16402. this.writtenDocs = new Set;
  16403. }
  16404. return t.prototype.lookup = function(t) {
  16405. return e(this, void 0, void 0, (function() {
  16406. var r, i = this;
  16407. return n(this, (function(o) {
  16408. switch (o.label) {
  16409. case 0:
  16410. if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new j(K.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes.");
  16411. return [ 4 /*yield*/ , function(t, r) {
  16412. return e(this, void 0, void 0, (function() {
  16413. var e, i, o, u, a, s;
  16414. return n(this, (function(n) {
  16415. switch (n.label) {
  16416. case 0:
  16417. return e = G(t), i = Zr(e.yt) + "/documents", o = {
  16418. documents: r.map((function(t) {
  16419. return Wr(e.yt, t);
  16420. }))
  16421. }, [ 4 /*yield*/ , e._o("BatchGetDocuments", i, o, r.length) ];
  16422. case 1:
  16423. return u = n.sent(), a = new Map, u.forEach((function(t) {
  16424. var n = function(t, e) {
  16425. return "found" in e ? function(t, e) {
  16426. U(!!e.found), e.found.name, e.found.updateTime;
  16427. var n = Hr(t, e.found.name), r = jr(e.found.updateTime), i = e.found.createTime ? jr(e.found.createTime) : at.min(), o = new en({
  16428. mapValue: {
  16429. fields: e.found.fields
  16430. }
  16431. });
  16432. return rn.newFoundDocument(n, r, i, o);
  16433. }(t, e) : "missing" in e ? function(t, e) {
  16434. U(!!e.missing), U(!!e.readTime);
  16435. var n = Hr(t, e.missing), r = jr(e.readTime);
  16436. return rn.newNoDocument(n, r);
  16437. }(t, e) : q();
  16438. }(e.yt, t);
  16439. a.set(n.key.toString(), n);
  16440. })), s = [], [ 2 /*return*/ , (r.forEach((function(t) {
  16441. var e = a.get(t.toString());
  16442. U(!!e), s.push(e);
  16443. })), s) ];
  16444. }
  16445. }));
  16446. }));
  16447. }(this.datastore, t) ];
  16448. case 1:
  16449. return [ 2 /*return*/ , ((r = o.sent()).forEach((function(t) {
  16450. return i.recordVersion(t);
  16451. })), r) ];
  16452. }
  16453. }));
  16454. }));
  16455. }, t.prototype.set = function(t, e) {
  16456. this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  16457. }, t.prototype.update = function(t, e) {
  16458. try {
  16459. this.write(e.toMutation(t, this.preconditionForUpdate(t)));
  16460. } catch (t) {
  16461. this.lastWriteError = t;
  16462. }
  16463. this.writtenDocs.add(t.toString());
  16464. }, t.prototype.delete = function(t) {
  16465. this.write(new cr(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  16466. }, t.prototype.commit = function() {
  16467. return e(this, void 0, void 0, (function() {
  16468. var t, r = this;
  16469. return n(this, (function(i) {
  16470. switch (i.label) {
  16471. case 0:
  16472. if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError;
  16473. return t = this.readVersions,
  16474. // For each mutation, note that the doc was written.
  16475. this.mutations.forEach((function(e) {
  16476. t.delete(e.key.toString());
  16477. })),
  16478. // For each document that was read but not written to, we want to perform
  16479. // a `verify` operation.
  16480. t.forEach((function(t, e) {
  16481. var n = ft.fromPath(e);
  16482. r.mutations.push(new lr(n, r.precondition(n)));
  16483. })), [ 4 /*yield*/ , function(t, r) {
  16484. return e(this, void 0, void 0, (function() {
  16485. var e, i, o;
  16486. return n(this, (function(n) {
  16487. switch (n.label) {
  16488. case 0:
  16489. return e = G(t), i = Zr(e.yt) + "/documents", o = {
  16490. writes: r.map((function(t) {
  16491. return ei(e.yt, t);
  16492. }))
  16493. }, [ 4 /*yield*/ , e.ao("Commit", i, o) ];
  16494. case 1:
  16495. return n.sent(), [ 2 /*return*/ ];
  16496. }
  16497. }));
  16498. }));
  16499. }(this.datastore, this.mutations) ];
  16500. case 1:
  16501. // For each mutation, note that the doc was written.
  16502. return i.sent(), this.committed = !0, [ 2 /*return*/ ];
  16503. }
  16504. }));
  16505. }));
  16506. }, t.prototype.recordVersion = function(t) {
  16507. var e;
  16508. if (t.isFoundDocument()) e = t.version; else {
  16509. if (!t.isNoDocument()) throw q();
  16510. // Represent a deleted doc using SnapshotVersion.min().
  16511. e = at.min();
  16512. }
  16513. var n = this.readVersions.get(t.key.toString());
  16514. if (n) {
  16515. if (!e.isEqual(n))
  16516. // This transaction will fail no matter what.
  16517. throw new j(K.ABORTED, "Document version changed between two reads.");
  16518. } else this.readVersions.set(t.key.toString(), e);
  16519. },
  16520. /**
  16521. * Returns the version of this document when it was read in this transaction,
  16522. * as a precondition, or no precondition if it was not read.
  16523. */
  16524. t.prototype.precondition = function(t) {
  16525. var e = this.readVersions.get(t.toString());
  16526. return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(at.min()) ? Hn.exists(!1) : Hn.updateTime(e) : Hn.none();
  16527. },
  16528. /**
  16529. * Returns the precondition for a document if the operation is an update.
  16530. */
  16531. t.prototype.preconditionForUpdate = function(t) {
  16532. var e = this.readVersions.get(t.toString());
  16533. // The first time a document is written, we want to take into account the
  16534. // read time and existence
  16535. if (!this.writtenDocs.has(t.toString()) && e) {
  16536. if (e.isEqual(at.min()))
  16537. // The document doesn't exist, so fail the transaction.
  16538. // This has to be validated locally because you can't send a
  16539. // precondition that a document does not exist without changing the
  16540. // semantics of the backend write to be an insert. This is the reverse
  16541. // of what we want, since we want to assert that the document doesn't
  16542. // exist but then send the update and have it fail. Since we can't
  16543. // express that to the backend, we have to validate locally.
  16544. // Note: this can change once we can send separate verify writes in the
  16545. // transaction.
  16546. throw new j(K.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
  16547. // Document exists, base precondition on document update time.
  16548. return Hn.updateTime(e);
  16549. }
  16550. // Document was not read, so we just use the preconditions for a blind
  16551. // update.
  16552. return Hn.exists(!0);
  16553. }, t.prototype.write = function(t) {
  16554. this.ensureCommitNotCalled(), this.mutations.push(t);
  16555. }, t.prototype.ensureCommitNotCalled = function() {}, t;
  16556. }(), Ac = /** @class */ function() {
  16557. function t(t, e, n, r, i) {
  16558. this.asyncQueue = t, this.datastore = e, this.options = n, this.updateFunction = r,
  16559. this.deferred = i, this.kc = n.maxAttempts, this.xo = new ga(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */)
  16560. /** Runs the transaction and sets the result on deferred. */;
  16561. }
  16562. return t.prototype.run = function() {
  16563. this.kc -= 1, this.Oc();
  16564. }, t.prototype.Oc = function() {
  16565. var t = this;
  16566. this.xo.Ro((function() {
  16567. return e(t, void 0, void 0, (function() {
  16568. var t, e, r = this;
  16569. return n(this, (function(n) {
  16570. return t = new xc(this.datastore), (e = this.Mc(t)) && e.then((function(e) {
  16571. r.asyncQueue.enqueueAndForget((function() {
  16572. return t.commit().then((function() {
  16573. r.deferred.resolve(e);
  16574. })).catch((function(t) {
  16575. r.Fc(t);
  16576. }));
  16577. }));
  16578. })).catch((function(t) {
  16579. r.Fc(t);
  16580. })), [ 2 /*return*/ ];
  16581. }));
  16582. }));
  16583. }));
  16584. }, t.prototype.Mc = function(t) {
  16585. try {
  16586. var e = this.updateFunction(t);
  16587. return !Qt(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")),
  16588. null);
  16589. } catch (t) {
  16590. // Do not retry errors thrown by user provided updateFunction.
  16591. return this.deferred.reject(t), null;
  16592. }
  16593. }, t.prototype.Fc = function(t) {
  16594. var e = this;
  16595. this.kc > 0 && this.$c(t) ? (this.kc -= 1, this.asyncQueue.enqueueAndForget((function() {
  16596. return e.Oc(), Promise.resolve();
  16597. }))) : this.deferred.reject(t);
  16598. }, t.prototype.$c = function(t) {
  16599. if ("FirebaseError" === t.name) {
  16600. // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and
  16601. // non-matching document versions with ABORTED. These errors should be retried.
  16602. var e = t.code;
  16603. return "aborted" === e || "failed-precondition" === e || "already-exists" === e || !fr(e);
  16604. }
  16605. return !1;
  16606. }, t;
  16607. }(), Cc = /** @class */ function() {
  16608. function t(t, r,
  16609. /**
  16610. * Asynchronous queue responsible for all of our internal processing. When
  16611. * we get incoming work from the user (via public API) or the network
  16612. * (incoming GRPC messages), we should always schedule onto this queue.
  16613. * This ensures all of our work is properly serialized (e.g. we don't
  16614. * start processing a new operation while the previous one is waiting for
  16615. * an async I/O to complete).
  16616. */
  16617. i, o) {
  16618. var u = this;
  16619. this.authCredentials = t, this.appCheckCredentials = r, this.asyncQueue = i, this.databaseInfo = o,
  16620. this.user = N.UNAUTHENTICATED, this.clientId = nt.R(), this.authCredentialListener = function() {
  16621. return Promise.resolve();
  16622. }, this.appCheckCredentialListener = function() {
  16623. return Promise.resolve();
  16624. }, this.authCredentials.start(i, (function(t) {
  16625. return e(u, void 0, void 0, (function() {
  16626. return n(this, (function(e) {
  16627. switch (e.label) {
  16628. case 0:
  16629. return V("FirestoreClient", "Received user=", t.uid), [ 4 /*yield*/ , this.authCredentialListener(t) ];
  16630. case 1:
  16631. return e.sent(), this.user = t, [ 2 /*return*/ ];
  16632. }
  16633. }));
  16634. }));
  16635. })), this.appCheckCredentials.start(i, (function(t) {
  16636. return V("FirestoreClient", "Received new app check token=", t), u.appCheckCredentialListener(t, u.user);
  16637. }));
  16638. }
  16639. return t.prototype.getConfiguration = function() {
  16640. return e(this, void 0, void 0, (function() {
  16641. return n(this, (function(t) {
  16642. return [ 2 /*return*/ , {
  16643. asyncQueue: this.asyncQueue,
  16644. databaseInfo: this.databaseInfo,
  16645. clientId: this.clientId,
  16646. authCredentials: this.authCredentials,
  16647. appCheckCredentials: this.appCheckCredentials,
  16648. initialUser: this.user,
  16649. maxConcurrentLimboResolutions: 100
  16650. } ];
  16651. }));
  16652. }));
  16653. }, t.prototype.setCredentialChangeListener = function(t) {
  16654. this.authCredentialListener = t;
  16655. }, t.prototype.setAppCheckTokenChangeListener = function(t) {
  16656. this.appCheckCredentialListener = t;
  16657. },
  16658. /**
  16659. * Checks that the client has not been terminated. Ensures that other methods on
  16660. * this class cannot be called after the client is terminated.
  16661. */
  16662. t.prototype.verifyNotTerminated = function() {
  16663. if (this.asyncQueue.isShuttingDown) throw new j(K.FAILED_PRECONDITION, "The client has already been terminated.");
  16664. }, t.prototype.terminate = function() {
  16665. var t = this;
  16666. this.asyncQueue.enterRestrictedMode();
  16667. var r = new Q;
  16668. return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((function() {
  16669. return e(t, void 0, void 0, (function() {
  16670. var t, e;
  16671. return n(this, (function(n) {
  16672. switch (n.label) {
  16673. case 0:
  16674. return n.trys.push([ 0, 5, , 6 ]), this.onlineComponents ? [ 4 /*yield*/ , this.onlineComponents.terminate() ] : [ 3 /*break*/ , 2 ];
  16675. case 1:
  16676. n.sent(), n.label = 2;
  16677. case 2:
  16678. return this.offlineComponents ? [ 4 /*yield*/ , this.offlineComponents.terminate() ] : [ 3 /*break*/ , 4 ];
  16679. case 3:
  16680. n.sent(), n.label = 4;
  16681. case 4:
  16682. // The credentials provider must be terminated after shutting down the
  16683. // RemoteStore as it will prevent the RemoteStore from retrieving auth
  16684. // tokens.
  16685. return this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), r.resolve(),
  16686. [ 3 /*break*/ , 6 ];
  16687. case 5:
  16688. return t = n.sent(), e = Ja(t, "Failed to shutdown persistence"), r.reject(e), [ 3 /*break*/ , 6 ];
  16689. case 6:
  16690. return [ 2 /*return*/ ];
  16691. }
  16692. }));
  16693. }));
  16694. })), r.promise;
  16695. }, t;
  16696. }();
  16697. /**
  16698. * @license
  16699. * Copyright 2020 Google LLC
  16700. *
  16701. * Licensed under the Apache License, Version 2.0 (the "License");
  16702. * you may not use this file except in compliance with the License.
  16703. * You may obtain a copy of the License at
  16704. *
  16705. * http://www.apache.org/licenses/LICENSE-2.0
  16706. *
  16707. * Unless required by applicable law or agreed to in writing, software
  16708. * distributed under the License is distributed on an "AS IS" BASIS,
  16709. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16710. * See the License for the specific language governing permissions and
  16711. * limitations under the License.
  16712. */
  16713. /**
  16714. * A class representing a bundle.
  16715. *
  16716. * Takes a bundle stream or buffer, and presents abstractions to read bundled
  16717. * elements out of the underlying content.
  16718. */ function Nc(t, r) {
  16719. return e(this, void 0, void 0, (function() {
  16720. var i, o, u = this;
  16721. return n(this, (function(a) {
  16722. switch (a.label) {
  16723. case 0:
  16724. return t.asyncQueue.verifyOperationInProgress(), V("FirestoreClient", "Initializing OfflineComponentProvider"),
  16725. [ 4 /*yield*/ , t.getConfiguration() ];
  16726. case 1:
  16727. return i = a.sent(), [ 4 /*yield*/ , r.initialize(i) ];
  16728. case 2:
  16729. return a.sent(), o = i.initialUser, t.setCredentialChangeListener((function(t) {
  16730. return e(u, void 0, void 0, (function() {
  16731. return n(this, (function(e) {
  16732. switch (e.label) {
  16733. case 0:
  16734. return o.isEqual(t) ? [ 3 /*break*/ , 2 ] : [ 4 /*yield*/ , Uu(r.localStore, t) ];
  16735. case 1:
  16736. e.sent(), o = t, e.label = 2;
  16737. case 2:
  16738. return [ 2 /*return*/ ];
  16739. }
  16740. }));
  16741. }));
  16742. })),
  16743. // When a user calls clearPersistence() in one client, all other clients
  16744. // need to be terminated to allow the delete to succeed.
  16745. r.persistence.setDatabaseDeletedListener((function() {
  16746. return t.terminate();
  16747. })), t.offlineComponents = r, [ 2 /*return*/ ];
  16748. }
  16749. }));
  16750. }));
  16751. }
  16752. function kc(t, r) {
  16753. return e(this, void 0, void 0, (function() {
  16754. var e, i;
  16755. return n(this, (function(n) {
  16756. switch (n.label) {
  16757. case 0:
  16758. return t.asyncQueue.verifyOperationInProgress(), [ 4 /*yield*/ , Fc(t) ];
  16759. case 1:
  16760. return e = n.sent(), V("FirestoreClient", "Initializing OnlineComponentProvider"),
  16761. [ 4 /*yield*/ , t.getConfiguration() ];
  16762. case 2:
  16763. return i = n.sent(), [ 4 /*yield*/ , r.initialize(e, i) ];
  16764. case 3:
  16765. return n.sent(),
  16766. // The CredentialChangeListener of the online component provider takes
  16767. // precedence over the offline component provider.
  16768. t.setCredentialChangeListener((function(t) {
  16769. return Wa(r.remoteStore, t);
  16770. })), t.setAppCheckTokenChangeListener((function(t, e) {
  16771. return Wa(r.remoteStore, e);
  16772. })), t.onlineComponents = r, [ 2 /*return*/ ];
  16773. }
  16774. }));
  16775. }));
  16776. }
  16777. function Fc(t) {
  16778. return e(this, void 0, void 0, (function() {
  16779. return n(this, (function(e) {
  16780. switch (e.label) {
  16781. case 0:
  16782. return t.offlineComponents ? [ 3 /*break*/ , 2 ] : (V("FirestoreClient", "Using default OfflineComponentProvider"),
  16783. [ 4 /*yield*/ , Nc(t, new Js) ]);
  16784. case 1:
  16785. e.sent(), e.label = 2;
  16786. case 2:
  16787. return [ 2 /*return*/ , t.offlineComponents ];
  16788. }
  16789. }));
  16790. }));
  16791. }
  16792. function Oc(t) {
  16793. return e(this, void 0, void 0, (function() {
  16794. return n(this, (function(e) {
  16795. switch (e.label) {
  16796. case 0:
  16797. return t.onlineComponents ? [ 3 /*break*/ , 2 ] : (V("FirestoreClient", "Using default OnlineComponentProvider"),
  16798. [ 4 /*yield*/ , kc(t, new ec) ]);
  16799. case 1:
  16800. e.sent(), e.label = 2;
  16801. case 2:
  16802. return [ 2 /*return*/ , t.onlineComponents ];
  16803. }
  16804. }));
  16805. }));
  16806. }
  16807. function Rc(t) {
  16808. return Fc(t).then((function(t) {
  16809. return t.persistence;
  16810. }));
  16811. }
  16812. function Vc(t) {
  16813. return Fc(t).then((function(t) {
  16814. return t.localStore;
  16815. }));
  16816. }
  16817. function Mc(t) {
  16818. return Oc(t).then((function(t) {
  16819. return t.remoteStore;
  16820. }));
  16821. }
  16822. function Lc(t) {
  16823. return Oc(t).then((function(t) {
  16824. return t.syncEngine;
  16825. }));
  16826. }
  16827. function Pc(t) {
  16828. return Oc(t).then((function(t) {
  16829. return t.datastore;
  16830. }));
  16831. }
  16832. function qc(t) {
  16833. return e(this, void 0, void 0, (function() {
  16834. var e, r;
  16835. return n(this, (function(n) {
  16836. switch (n.label) {
  16837. case 0:
  16838. return [ 4 /*yield*/ , Oc(t) ];
  16839. case 1:
  16840. return e = n.sent(), [ 2 /*return*/ , ((r = e.eventManager).onListen = bs.bind(null, e.syncEngine),
  16841. r.onUnlisten = Ts.bind(null, e.syncEngine), r) ];
  16842. }
  16843. }));
  16844. }));
  16845. }
  16846. /** Enables the network connection and re-enqueues all pending operations. */ function Uc(t, r, i) {
  16847. var o = this;
  16848. void 0 === i && (i = {});
  16849. var u = new Q;
  16850. return t.asyncQueue.enqueueAndForget((function() {
  16851. return e(o, void 0, void 0, (function() {
  16852. var e;
  16853. return n(this, (function(n) {
  16854. switch (n.label) {
  16855. case 0:
  16856. return e = function(t, e, n, r, i) {
  16857. var o = new Tc({
  16858. next: function(o) {
  16859. // Remove query first before passing event to user to avoid
  16860. // user actions affecting the now stale query.
  16861. e.enqueueAndForget((function() {
  16862. return os(t, u);
  16863. }));
  16864. var a = o.docs.has(n);
  16865. !a && o.fromCache ?
  16866. // TODO(dimond): If we're online and the document doesn't
  16867. // exist then we resolve with a doc.exists set to false. If
  16868. // we're offline however, we reject the Promise in this
  16869. // case. Two options: 1) Cache the negative response from
  16870. // the server so we can deliver that even when you're
  16871. // offline 2) Actually reject the Promise in the online case
  16872. // if the document doesn't exist.
  16873. i.reject(new j(K.UNAVAILABLE, "Failed to get document because the client is offline.")) : a && o.fromCache && r && "server" === r.source ? i.reject(new j(K.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')) : i.resolve(o);
  16874. },
  16875. error: function(t) {
  16876. return i.reject(t);
  16877. }
  16878. }), u = new cs(yn(n.path), o, {
  16879. includeMetadataChanges: !0,
  16880. Nu: !0
  16881. });
  16882. return is(t, u);
  16883. }, [ 4 /*yield*/ , qc(t) ];
  16884. case 1:
  16885. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), t.asyncQueue, r, i, u ]) ];
  16886. }
  16887. }));
  16888. }));
  16889. })), u.promise;
  16890. }
  16891. function Bc(t, r, i) {
  16892. var o = this;
  16893. void 0 === i && (i = {});
  16894. var u = new Q;
  16895. return t.asyncQueue.enqueueAndForget((function() {
  16896. return e(o, void 0, void 0, (function() {
  16897. var e;
  16898. return n(this, (function(n) {
  16899. switch (n.label) {
  16900. case 0:
  16901. return e = function(t, e, n, r, i) {
  16902. var o = new Tc({
  16903. next: function(n) {
  16904. // Remove query first before passing event to user to avoid
  16905. // user actions affecting the now stale query.
  16906. e.enqueueAndForget((function() {
  16907. return os(t, u);
  16908. })), n.fromCache && "server" === r.source ? i.reject(new j(K.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')) : i.resolve(n);
  16909. },
  16910. error: function(t) {
  16911. return i.reject(t);
  16912. }
  16913. }), u = new cs(n, o, {
  16914. includeMetadataChanges: !0,
  16915. Nu: !0
  16916. });
  16917. return is(t, u);
  16918. }, [ 4 /*yield*/ , qc(t) ];
  16919. case 1:
  16920. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), t.asyncQueue, r, i, u ]) ];
  16921. }
  16922. }));
  16923. }));
  16924. })), u.promise;
  16925. }
  16926. var Gc = /** @class */ function() {
  16927. function t() {
  16928. var t = this;
  16929. // The last promise in the queue.
  16930. this.Bc = Promise.resolve(),
  16931. // A list of retryable operations. Retryable operations are run in order and
  16932. // retried with backoff.
  16933. this.Lc = [],
  16934. // Is this AsyncQueue being shut down? Once it is set to true, it will not
  16935. // be changed again.
  16936. this.qc = !1,
  16937. // Operations scheduled to be queued in the future. Operations are
  16938. // automatically removed after they are run or canceled.
  16939. this.Uc = [],
  16940. // visible for testing
  16941. this.Kc = null,
  16942. // Flag set while there's an outstanding AsyncQueue operation, used for
  16943. // assertion sanity-checks.
  16944. this.Gc = !1,
  16945. // Enabled during shutdown on Safari to prevent future access to IndexedDB.
  16946. this.Qc = !1,
  16947. // List of TimerIds to fast-forward delays for.
  16948. this.jc = [],
  16949. // Backoff timer used to schedule retries for retryable operations
  16950. this.xo = new ga(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */),
  16951. // Visibility handler that triggers an immediate retry of all retryable
  16952. // operations. Meant to speed up recovery when we regain file system access
  16953. // after page comes into foreground.
  16954. this.Wc = function() {
  16955. var e = va();
  16956. e && V("AsyncQueue", "Visibility state changed to " + e.visibilityState), t.xo.Po();
  16957. };
  16958. var e = va();
  16959. e && "function" == typeof e.addEventListener && e.addEventListener("visibilitychange", this.Wc);
  16960. }
  16961. return Object.defineProperty(t.prototype, "isShuttingDown", {
  16962. get: function() {
  16963. return this.qc;
  16964. },
  16965. enumerable: !1,
  16966. configurable: !0
  16967. }),
  16968. /**
  16969. * Adds a new operation to the queue without waiting for it to complete (i.e.
  16970. * we ignore the Promise result).
  16971. */
  16972. t.prototype.enqueueAndForget = function(t) {
  16973. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  16974. this.enqueue(t);
  16975. }, t.prototype.enqueueAndForgetEvenWhileRestricted = function(t) {
  16976. this.zc(),
  16977. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  16978. this.Hc(t);
  16979. }, t.prototype.enterRestrictedMode = function(t) {
  16980. if (!this.qc) {
  16981. this.qc = !0, this.Qc = t || !1;
  16982. var e = va();
  16983. e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Wc);
  16984. }
  16985. }, t.prototype.enqueue = function(t) {
  16986. var e = this;
  16987. if (this.zc(), this.qc)
  16988. // Return a Promise which never resolves.
  16989. return new Promise((function() {}));
  16990. // Create a deferred Promise that we can return to the callee. This
  16991. // allows us to return a "hanging Promise" only to the callee and still
  16992. // advance the queue even when the operation is not run.
  16993. var n = new Q;
  16994. return this.Hc((function() {
  16995. return e.qc && e.Qc ? Promise.resolve() : (t().then(n.resolve, n.reject), n.promise);
  16996. })).then((function() {
  16997. return n.promise;
  16998. }));
  16999. }, t.prototype.enqueueRetryable = function(t) {
  17000. var e = this;
  17001. this.enqueueAndForget((function() {
  17002. return e.Lc.push(t), e.Jc();
  17003. }));
  17004. },
  17005. /**
  17006. * Runs the next operation from the retryable queue. If the operation fails,
  17007. * reschedules with backoff.
  17008. */
  17009. t.prototype.Jc = function() {
  17010. return e(this, void 0, void 0, (function() {
  17011. var t, e = this;
  17012. return n(this, (function(n) {
  17013. switch (n.label) {
  17014. case 0:
  17015. if (0 === this.Lc.length) return [ 3 /*break*/ , 5 ];
  17016. n.label = 1;
  17017. case 1:
  17018. return n.trys.push([ 1, 3, , 4 ]), [ 4 /*yield*/ , this.Lc[0]() ];
  17019. case 2:
  17020. return n.sent(), this.Lc.shift(), this.xo.reset(), [ 3 /*break*/ , 4 ];
  17021. case 3:
  17022. if (!Ft(t = n.sent())) throw t;
  17023. // Failure will be handled by AsyncQueue
  17024. return V("AsyncQueue", "Operation failed with retryable error: " + t),
  17025. [ 3 /*break*/ , 4 ];
  17026. case 4:
  17027. this.Lc.length > 0 &&
  17028. // If there are additional operations, we re-schedule `retryNextOp()`.
  17029. // This is necessary to run retryable operations that failed during
  17030. // their initial attempt since we don't know whether they are already
  17031. // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
  17032. // needs to be re-run, we will run `op1`, `op1`, `op2` using the
  17033. // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
  17034. // call scheduled here.
  17035. // Since `backoffAndRun()` cancels an existing backoff and schedules a
  17036. // new backoff on every call, there is only ever a single additional
  17037. // operation in the queue.
  17038. this.xo.Ro((function() {
  17039. return e.Jc();
  17040. })), n.label = 5;
  17041. case 5:
  17042. return [ 2 /*return*/ ];
  17043. }
  17044. }));
  17045. }));
  17046. }, t.prototype.Hc = function(t) {
  17047. var e = this, n = this.Bc.then((function() {
  17048. return e.Gc = !0, t().catch((function(t) {
  17049. e.Kc = t, e.Gc = !1;
  17050. var n =
  17051. /**
  17052. * Chrome includes Error.message in Error.stack. Other browsers do not.
  17053. * This returns expected output of message + stack when available.
  17054. * @param error - Error or FirestoreError
  17055. */
  17056. function(t) {
  17057. var e = t.message || "";
  17058. return t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack),
  17059. e;
  17060. }(t);
  17061. // Re-throw the error so that this.tail becomes a rejected Promise and
  17062. // all further attempts to chain (via .then) will just short-circuit
  17063. // and return the rejected Promise.
  17064. throw M("INTERNAL UNHANDLED ERROR: ", n), t;
  17065. })).then((function(t) {
  17066. return e.Gc = !1, t;
  17067. }));
  17068. }));
  17069. return this.Bc = n, n;
  17070. }, t.prototype.enqueueAfterDelay = function(t, e, n) {
  17071. var r = this;
  17072. this.zc(),
  17073. // Fast-forward delays for timerIds that have been overriden.
  17074. this.jc.indexOf(t) > -1 && (e = 0);
  17075. var i = Za.createAndSchedule(this, t, e, n, (function(t) {
  17076. return r.Yc(t);
  17077. }));
  17078. return this.Uc.push(i), i;
  17079. }, t.prototype.zc = function() {
  17080. this.Kc && q();
  17081. }, t.prototype.verifyOperationInProgress = function() {},
  17082. /**
  17083. * Waits until all currently queued tasks are finished executing. Delayed
  17084. * operations are not run.
  17085. */
  17086. t.prototype.Xc = function() {
  17087. return e(this, void 0, void 0, (function() {
  17088. var t;
  17089. return n(this, (function(e) {
  17090. switch (e.label) {
  17091. case 0:
  17092. return [ 4 /*yield*/ , t = this.Bc ];
  17093. case 1:
  17094. e.sent(), e.label = 2;
  17095. case 2:
  17096. if (t !== this.Bc) return [ 3 /*break*/ , 0 ];
  17097. e.label = 3;
  17098. case 3:
  17099. return [ 2 /*return*/ ];
  17100. }
  17101. }));
  17102. }));
  17103. },
  17104. /**
  17105. * For Tests: Determine if a delayed operation with a particular TimerId
  17106. * exists.
  17107. */
  17108. t.prototype.Zc = function(t) {
  17109. for (var e = 0, n = this.Uc; e < n.length; e++) {
  17110. if (n[e].timerId === t) return !0;
  17111. }
  17112. return !1;
  17113. },
  17114. /**
  17115. * For Tests: Runs some or all delayed operations early.
  17116. *
  17117. * @param lastTimerId - Delayed operations up to and including this TimerId
  17118. * will be drained. Pass TimerId.All to run all delayed operations.
  17119. * @returns a Promise that resolves once all operations have been run.
  17120. */
  17121. t.prototype.ta = function(t) {
  17122. var e = this;
  17123. // Note that draining may generate more delayed ops, so we do that first.
  17124. return this.Xc().then((function() {
  17125. // Run ops in the same order they'd run if they ran naturally.
  17126. e.Uc.sort((function(t, e) {
  17127. return t.targetTimeMs - e.targetTimeMs;
  17128. }));
  17129. for (var n = 0, r = e.Uc; n < r.length; n++) {
  17130. var i = r[n];
  17131. if (i.skipDelay(), "all" /* TimerId.All */ !== t && i.timerId === t) break;
  17132. }
  17133. return e.Xc();
  17134. }));
  17135. },
  17136. /**
  17137. * For Tests: Skip all subsequent delays for a timer id.
  17138. */
  17139. t.prototype.ea = function(t) {
  17140. this.jc.push(t);
  17141. },
  17142. /** Called once a DelayedOperation is run or canceled. */ t.prototype.Yc = function(t) {
  17143. // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
  17144. var e = this.Uc.indexOf(t);
  17145. this.Uc.splice(e, 1);
  17146. }, t;
  17147. }();
  17148. function Kc(t) {
  17149. /**
  17150. * Returns true if obj is an object and contains at least one of the specified
  17151. * methods.
  17152. */
  17153. return function(t, e) {
  17154. if ("object" != typeof t || null === t) return !1;
  17155. for (var n = t, r = 0, i = [ "next", "error", "complete" ]; r < i.length; r++) {
  17156. var o = i[r];
  17157. if (o in n && "function" == typeof n[o]) return !0;
  17158. }
  17159. return !1;
  17160. }(t);
  17161. }
  17162. var jc = /** @class */ function() {
  17163. function t() {
  17164. this._progressObserver = {}, this._taskCompletionResolver = new Q, this._lastProgress = {
  17165. taskState: "Running",
  17166. totalBytes: 0,
  17167. totalDocuments: 0,
  17168. bytesLoaded: 0,
  17169. documentsLoaded: 0
  17170. }
  17171. /**
  17172. * Registers functions to listen to bundle loading progress events.
  17173. * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur
  17174. * each time a Firestore document is loaded from the bundle.
  17175. * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the
  17176. * error, and there should be no more updates after this.
  17177. * @param complete - Called when the loading task is complete.
  17178. */;
  17179. }
  17180. return t.prototype.onProgress = function(t, e, n) {
  17181. this._progressObserver = {
  17182. next: t,
  17183. error: e,
  17184. complete: n
  17185. };
  17186. },
  17187. /**
  17188. * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.
  17189. *
  17190. * @param onRejected - Called when an error occurs during bundle loading.
  17191. */
  17192. t.prototype.catch = function(t) {
  17193. return this._taskCompletionResolver.promise.catch(t);
  17194. },
  17195. /**
  17196. * Implements the `Promise<LoadBundleTaskProgress>.then` interface.
  17197. *
  17198. * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.
  17199. * The update will always have its `taskState` set to `"Success"`.
  17200. * @param onRejected - Called when an error occurs during bundle loading.
  17201. */
  17202. t.prototype.then = function(t, e) {
  17203. return this._taskCompletionResolver.promise.then(t, e);
  17204. },
  17205. /**
  17206. * Notifies all observers that bundle loading has completed, with a provided
  17207. * `LoadBundleTaskProgress` object.
  17208. *
  17209. * @private
  17210. */
  17211. t.prototype._completeWith = function(t) {
  17212. this._updateProgress(t), this._progressObserver.complete && this._progressObserver.complete(),
  17213. this._taskCompletionResolver.resolve(t);
  17214. },
  17215. /**
  17216. * Notifies all observers that bundle loading has failed, with a provided
  17217. * `Error` as the reason.
  17218. *
  17219. * @private
  17220. */
  17221. t.prototype._failWith = function(t) {
  17222. this._lastProgress.taskState = "Error", this._progressObserver.next && this._progressObserver.next(this._lastProgress),
  17223. this._progressObserver.error && this._progressObserver.error(t), this._taskCompletionResolver.reject(t);
  17224. },
  17225. /**
  17226. * Notifies a progress update of loading a bundle.
  17227. * @param progress - The new progress.
  17228. *
  17229. * @private
  17230. */
  17231. t.prototype._updateProgress = function(t) {
  17232. this._lastProgress = t, this._progressObserver.next && this._progressObserver.next(t);
  17233. }, t;
  17234. }(), Qc = -1, zc = /** @class */ function(e) {
  17235. /** @hideconstructor */
  17236. function n(t, n, r, i) {
  17237. var o = this;
  17238. /**
  17239. * Whether it's a {@link Firestore} or Firestore Lite instance.
  17240. */
  17241. return (o = e.call(this, t, n, r, i) || this).type = "firestore", o._queue = new Gc,
  17242. o._persistenceKey = (null == i ? void 0 : i.name) || "[DEFAULT]", o;
  17243. }
  17244. return t(n, e), n.prototype._terminate = function() {
  17245. return this._firestoreClient ||
  17246. // The client must be initialized to ensure that all subsequent API
  17247. // usage throws an exception.
  17248. Xc(this), this._firestoreClient.terminate();
  17249. }, n;
  17250. }(hc);
  17251. /**
  17252. * @license
  17253. * Copyright 2020 Google LLC
  17254. *
  17255. * Licensed under the Apache License, Version 2.0 (the "License");
  17256. * you may not use this file except in compliance with the License.
  17257. * You may obtain a copy of the License at
  17258. *
  17259. * http://www.apache.org/licenses/LICENSE-2.0
  17260. *
  17261. * Unless required by applicable law or agreed to in writing, software
  17262. * distributed under the License is distributed on an "AS IS" BASIS,
  17263. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17264. * See the License for the specific language governing permissions and
  17265. * limitations under the License.
  17266. */
  17267. /** DOMException error code constants. */
  17268. /**
  17269. * Initializes a new instance of {@link Firestore} with the provided settings.
  17270. * Can only be called before any other function, including
  17271. * {@link (getFirestore:1)}. If the custom settings are empty, this function is
  17272. * equivalent to calling {@link (getFirestore:1)}.
  17273. *
  17274. * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will
  17275. * be associated.
  17276. * @param settings - A settings object to configure the {@link Firestore} instance.
  17277. * @param databaseId - The name of database.
  17278. * @returns A newly initialized {@link Firestore} instance.
  17279. */
  17280. function Wc(t, e, n) {
  17281. n || (n = "(default)");
  17282. var r = _getProvider(t, "firestore");
  17283. if (r.isInitialized(n)) {
  17284. var i = r.getImmediate({
  17285. identifier: n
  17286. }), o = r.getOptions(n);
  17287. if (g(o, e)) return i;
  17288. throw new j(K.FAILED_PRECONDITION, "initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.");
  17289. }
  17290. if (void 0 !== e.cacheSizeBytes && -1 !== e.cacheSizeBytes && e.cacheSizeBytes < 1048576) throw new j(K.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  17291. return r.initialize({
  17292. options: e,
  17293. instanceIdentifier: n
  17294. });
  17295. }
  17296. function Hc(t, e) {
  17297. var n = "object" == typeof t ? t : a(), i = "string" == typeof t ? t : e || "(default)", o = _getProvider(n, "firestore").getImmediate({
  17298. identifier: i
  17299. });
  17300. if (!o._initialized) {
  17301. var u = w("firestore");
  17302. u && fc.apply(void 0, r([ o ], u, !1));
  17303. }
  17304. return o;
  17305. }
  17306. /**
  17307. * @internal
  17308. */ function Yc(t) {
  17309. return t._firestoreClient || Xc(t), t._firestoreClient.verifyNotTerminated(), t._firestoreClient;
  17310. }
  17311. function Xc(t) {
  17312. var e, n = t._freezeSettings(), r = function(t, e, n, r) {
  17313. return new Ut(t, e, n, r.host, r.ssl, r.experimentalForceLongPolling, r.experimentalAutoDetectLongPolling, r.useFetchStreams);
  17314. }(t._databaseId, (null === (e = t._app) || void 0 === e ? void 0 : e.options.appId) || "", t._persistenceKey, n);
  17315. t._firestoreClient = new Cc(t._authCredentials, t._appCheckCredentials, t._queue, r);
  17316. }
  17317. /**
  17318. * Attempts to enable persistent storage, if possible.
  17319. *
  17320. * Must be called before any other functions (other than
  17321. * {@link initializeFirestore}, {@link (getFirestore:1)} or
  17322. * {@link clearIndexedDbPersistence}.
  17323. *
  17324. * If this fails, `enableIndexedDbPersistence()` will reject the promise it
  17325. * returns. Note that even after this failure, the {@link Firestore} instance will
  17326. * remain usable, however offline persistence will be disabled.
  17327. *
  17328. * There are several reasons why this can fail, which can be identified by
  17329. * the `code` on the error.
  17330. *
  17331. * * failed-precondition: The app is already open in another browser tab.
  17332. * * unimplemented: The browser is incompatible with the offline
  17333. * persistence implementation.
  17334. *
  17335. * @param firestore - The {@link Firestore} instance to enable persistence for.
  17336. * @param persistenceSettings - Optional settings object to configure
  17337. * persistence.
  17338. * @returns A `Promise` that represents successfully enabling persistent storage.
  17339. */ function Zc(t, e) {
  17340. al(t = ac(t, zc));
  17341. var n = Yc(t), r = t._freezeSettings(), i = new ec;
  17342. return $c(n, i, new $s(i, r.cacheSizeBytes, null == e ? void 0 : e.forceOwnership));
  17343. }
  17344. /**
  17345. * Attempts to enable multi-tab persistent storage, if possible. If enabled
  17346. * across all tabs, all operations share access to local persistence, including
  17347. * shared execution of queries and latency-compensated local document updates
  17348. * across all connected instances.
  17349. *
  17350. * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise
  17351. * it returns. Note that even after this failure, the {@link Firestore} instance will
  17352. * remain usable, however offline persistence will be disabled.
  17353. *
  17354. * There are several reasons why this can fail, which can be identified by
  17355. * the `code` on the error.
  17356. *
  17357. * * failed-precondition: The app is already open in another browser tab and
  17358. * multi-tab is not enabled.
  17359. * * unimplemented: The browser is incompatible with the offline
  17360. * persistence implementation.
  17361. *
  17362. * @param firestore - The {@link Firestore} instance to enable persistence for.
  17363. * @returns A `Promise` that represents successfully enabling persistent
  17364. * storage.
  17365. */ function Jc(t) {
  17366. al(t = ac(t, zc));
  17367. var e = Yc(t), n = t._freezeSettings(), r = new ec;
  17368. return $c(e, r, new tc(r, n.cacheSizeBytes));
  17369. }
  17370. /**
  17371. * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.
  17372. * If the operation fails with a recoverable error (see
  17373. * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected
  17374. * but the client remains usable.
  17375. */ function $c(t, r, i) {
  17376. var o = this, u = new Q;
  17377. return t.asyncQueue.enqueue((function() {
  17378. return e(o, void 0, void 0, (function() {
  17379. var e, o;
  17380. return n(this, (function(n) {
  17381. switch (n.label) {
  17382. case 0:
  17383. return n.trys.push([ 0, 3, , 4 ]), [ 4 /*yield*/ , Nc(t, i) ];
  17384. case 1:
  17385. return n.sent(), [ 4 /*yield*/ , kc(t, r) ];
  17386. case 2:
  17387. return n.sent(), u.resolve(), [ 3 /*break*/ , 4 ];
  17388. case 3:
  17389. if (e = n.sent(), !
  17390. /**
  17391. * Decides whether the provided error allows us to gracefully disable
  17392. * persistence (as opposed to crashing the client).
  17393. */
  17394. function(t) {
  17395. return "FirebaseError" === t.name ? t.code === K.FAILED_PRECONDITION || t.code === K.UNIMPLEMENTED : !("undefined" != typeof DOMException && t instanceof DOMException) || (22 === t.code || 20 === t.code ||
  17396. // Firefox Private Browsing mode disables IndexedDb and returns
  17397. // INVALID_STATE for any usage.
  17398. 11 === t.code);
  17399. }(o = e)) throw o;
  17400. return L("Error enabling offline persistence. Falling back to persistence disabled: " + o),
  17401. u.reject(o), [ 3 /*break*/ , 4 ];
  17402. case 4:
  17403. return [ 2 /*return*/ ];
  17404. }
  17405. }));
  17406. }));
  17407. })).then((function() {
  17408. return u.promise;
  17409. }));
  17410. }
  17411. function tl(t) {
  17412. var r = this;
  17413. if (t._initialized && !t._terminated) throw new j(K.FAILED_PRECONDITION, "Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");
  17414. var i = new Q;
  17415. return t._queue.enqueueAndForgetEvenWhileRestricted((function() {
  17416. return e(r, void 0, void 0, (function() {
  17417. var r;
  17418. return n(this, (function(o) {
  17419. switch (o.label) {
  17420. case 0:
  17421. return o.trys.push([ 0, 2, , 3 ]), [ 4 /*yield*/ , function(t) {
  17422. return e(this, void 0, void 0, (function() {
  17423. var e;
  17424. return n(this, (function(n) {
  17425. switch (n.label) {
  17426. case 0:
  17427. return Ct.C() ? (e = t + "main", [ 4 /*yield*/ , Ct.delete(e) ]) : [ 2 /*return*/ , Promise.resolve() ];
  17428. case 1:
  17429. return n.sent(), [ 2 /*return*/ ];
  17430. }
  17431. }));
  17432. }));
  17433. }(Vu(t._databaseId, t._persistenceKey)) ];
  17434. case 1:
  17435. return o.sent(), i.resolve(), [ 3 /*break*/ , 3 ];
  17436. case 2:
  17437. return r = o.sent(), i.reject(r), [ 3 /*break*/ , 3 ];
  17438. case 3:
  17439. return [ 2 /*return*/ ];
  17440. }
  17441. }));
  17442. }));
  17443. })), i.promise
  17444. /**
  17445. * Waits until all currently pending writes for the active user have been
  17446. * acknowledged by the backend.
  17447. *
  17448. * The returned promise resolves immediately if there are no outstanding writes.
  17449. * Otherwise, the promise waits for all previously issued writes (including
  17450. * those written in a previous app session), but it does not wait for writes
  17451. * that were added after the function is called. If you want to wait for
  17452. * additional writes, call `waitForPendingWrites()` again.
  17453. *
  17454. * Any outstanding `waitForPendingWrites()` promises are rejected during user
  17455. * changes.
  17456. *
  17457. * @returns A `Promise` which resolves when all currently pending writes have been
  17458. * acknowledged by the backend.
  17459. */;
  17460. }
  17461. function el(t) {
  17462. return function(t) {
  17463. var r = this, i = new Q;
  17464. return t.asyncQueue.enqueueAndForget((function() {
  17465. return e(r, void 0, void 0, (function() {
  17466. var e;
  17467. return n(this, (function(n) {
  17468. switch (n.label) {
  17469. case 0:
  17470. return e = Cs, [ 4 /*yield*/ , Lc(t) ];
  17471. case 1:
  17472. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), i ]) ];
  17473. }
  17474. }));
  17475. }));
  17476. })), i.promise;
  17477. }(Yc(t = ac(t, zc)));
  17478. }
  17479. /**
  17480. * Re-enables use of the network for this {@link Firestore} instance after a prior
  17481. * call to {@link disableNetwork}.
  17482. *
  17483. * @returns A `Promise` that is resolved once the network has been enabled.
  17484. */ function nl(t) {
  17485. return function(t) {
  17486. var r = this;
  17487. return t.asyncQueue.enqueue((function() {
  17488. return e(r, void 0, void 0, (function() {
  17489. var e, r;
  17490. return n(this, (function(n) {
  17491. switch (n.label) {
  17492. case 0:
  17493. return [ 4 /*yield*/ , Rc(t) ];
  17494. case 1:
  17495. return e = n.sent(), [ 4 /*yield*/ , Mc(t) ];
  17496. case 2:
  17497. return r = n.sent(), [ 2 /*return*/ , (e.setNetworkEnabled(!0), function(t) {
  17498. var e = G(t);
  17499. return e._u.delete(0 /* OfflineCause.UserDisabled */), _a(e);
  17500. }(r)) ];
  17501. }
  17502. }));
  17503. }));
  17504. }));
  17505. }
  17506. /** Disables the network connection. Pending operations will not complete. */ (Yc(t = ac(t, zc)));
  17507. }
  17508. /**
  17509. * Disables network usage for this instance. It can be re-enabled via {@link
  17510. * enableNetwork}. While the network is disabled, any snapshot listeners,
  17511. * `getDoc()` or `getDocs()` calls will return results from cache, and any write
  17512. * operations will be queued until the network is restored.
  17513. *
  17514. * @returns A `Promise` that is resolved once the network has been disabled.
  17515. */ function rl(t) {
  17516. return function(t) {
  17517. var r = this;
  17518. return t.asyncQueue.enqueue((function() {
  17519. return e(r, void 0, void 0, (function() {
  17520. var r, i;
  17521. return n(this, (function(o) {
  17522. switch (o.label) {
  17523. case 0:
  17524. return [ 4 /*yield*/ , Rc(t) ];
  17525. case 1:
  17526. return r = o.sent(), [ 4 /*yield*/ , Mc(t) ];
  17527. case 2:
  17528. return i = o.sent(), [ 2 /*return*/ , (r.setNetworkEnabled(!1), function(t) {
  17529. return e(this, void 0, void 0, (function() {
  17530. var e;
  17531. return n(this, (function(n) {
  17532. switch (n.label) {
  17533. case 0:
  17534. return (e = G(t))._u.add(0 /* OfflineCause.UserDisabled */), [ 4 /*yield*/ , Da(e) ];
  17535. case 1:
  17536. return n.sent(),
  17537. // Set the OnlineState to Offline so get()s return from cache, etc.
  17538. e.gu.set("Offline" /* OnlineState.Offline */), [ 2 /*return*/ ];
  17539. }
  17540. }));
  17541. }));
  17542. }(i)) ];
  17543. }
  17544. }));
  17545. }));
  17546. }));
  17547. }
  17548. /**
  17549. * Returns a Promise that resolves when all writes that were pending at the time
  17550. * this method was called received server acknowledgement. An acknowledgement
  17551. * can be either acceptance or rejection.
  17552. */ (Yc(t = ac(t, zc)));
  17553. }
  17554. /**
  17555. * Terminates the provided {@link Firestore} instance.
  17556. *
  17557. * After calling `terminate()` only the `clearIndexedDbPersistence()` function
  17558. * may be used. Any other function will throw a `FirestoreError`.
  17559. *
  17560. * To restart after termination, create a new instance of FirebaseFirestore with
  17561. * {@link (getFirestore:1)}.
  17562. *
  17563. * Termination does not cancel any pending writes, and any promises that are
  17564. * awaiting a response from the server will not be resolved. If you have
  17565. * persistence enabled, the next time you start this instance, it will resume
  17566. * sending these writes to the server.
  17567. *
  17568. * Note: Under normal circumstances, calling `terminate()` is not required. This
  17569. * function is useful only when you want to force this instance to release all
  17570. * of its resources or in combination with `clearIndexedDbPersistence()` to
  17571. * ensure that all local state is destroyed between test runs.
  17572. *
  17573. * @returns A `Promise` that is resolved when the instance has been successfully
  17574. * terminated.
  17575. */ function il(t) {
  17576. return s(t.app, "firestore", t._databaseId.database), t._delete()
  17577. /**
  17578. * Loads a Firestore bundle into the local cache.
  17579. *
  17580. * @param firestore - The {@link Firestore} instance to load bundles for.
  17581. * @param bundleData - An object representing the bundle to be loaded. Valid
  17582. * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.
  17583. *
  17584. * @returns A `LoadBundleTask` object, which notifies callers with progress
  17585. * updates, and completion or error events. It can be used as a
  17586. * `Promise<LoadBundleTaskProgress>`.
  17587. */;
  17588. }
  17589. function ol(t, r) {
  17590. var i = Yc(t = ac(t, zc)), o = new jc;
  17591. /**
  17592. * Takes an updateFunction in which a set of reads and writes can be performed
  17593. * atomically. In the updateFunction, the client can read and write values
  17594. * using the supplied transaction object. After the updateFunction, all
  17595. * changes will be committed. If a retryable error occurs (ex: some other
  17596. * client has changed any of the data referenced), then the updateFunction
  17597. * will be called again after a backoff. If the updateFunction still fails
  17598. * after all retries, then the transaction will be rejected.
  17599. *
  17600. * The transaction object passed to the updateFunction contains methods for
  17601. * accessing documents and collections. Unlike other datastore access, data
  17602. * accessed with the transaction will not reflect local changes that have not
  17603. * been committed. For this reason, it is required that all reads are
  17604. * performed before any writes. Transactions must be performed while online.
  17605. */
  17606. return function(t, r, i, o) {
  17607. var u = this, a = function(t, e) {
  17608. return function(t, e) {
  17609. return new Ec(t, e);
  17610. }(function(t, e) {
  17611. if (t instanceof Uint8Array) return Ic(t, e);
  17612. if (t instanceof ArrayBuffer) return Ic(new Uint8Array(t), e);
  17613. if (t instanceof ReadableStream) return t.getReader();
  17614. throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream");
  17615. }("string" == typeof t ? (new TextEncoder).encode(t) : t), e);
  17616. }(i, ma(r));
  17617. t.asyncQueue.enqueueAndForget((function() {
  17618. return e(u, void 0, void 0, (function() {
  17619. var e;
  17620. return n(this, (function(n) {
  17621. switch (n.label) {
  17622. case 0:
  17623. return e = Zs, [ 4 /*yield*/ , Lc(t) ];
  17624. case 1:
  17625. return e.apply(void 0, [ n.sent(), a, o ]), [ 2 /*return*/ ];
  17626. }
  17627. }));
  17628. }));
  17629. }));
  17630. }(i, t._databaseId, r, o), o
  17631. /**
  17632. * Reads a Firestore {@link Query} from local cache, identified by the given
  17633. * name.
  17634. *
  17635. * The named queries are packaged into bundles on the server side (along
  17636. * with resulting documents), and loaded to local cache using `loadBundle`. Once
  17637. * in local cache, use this method to extract a {@link Query} by name.
  17638. *
  17639. * @param firestore - The {@link Firestore} instance to read the query from.
  17640. * @param name - The name of the query.
  17641. * @returns A `Promise` that is resolved with the Query or `null`.
  17642. */;
  17643. }
  17644. function ul(t, r) {
  17645. return function(t, r) {
  17646. var i = this;
  17647. return t.asyncQueue.enqueue((function() {
  17648. return e(i, void 0, void 0, (function() {
  17649. var e;
  17650. return n(this, (function(n) {
  17651. switch (n.label) {
  17652. case 0:
  17653. return e = function(t, e) {
  17654. var n = G(t);
  17655. return n.persistence.runTransaction("Get named query", "readonly", (function(t) {
  17656. return n.Ns.getNamedQuery(t, e);
  17657. }));
  17658. }, [ 4 /*yield*/ , Vc(t) ];
  17659. case 1:
  17660. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), r ]) ];
  17661. }
  17662. }));
  17663. }));
  17664. }));
  17665. }(Yc(t = ac(t, zc)), r).then((function(e) {
  17666. return e ? new pc(t, null, e.query) : null;
  17667. }));
  17668. }
  17669. function al(t) {
  17670. if (t._initialized || t._terminated) throw new j(K.FAILED_PRECONDITION, "Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");
  17671. }
  17672. /**
  17673. * @license
  17674. * Copyright 2020 Google LLC
  17675. *
  17676. * Licensed under the Apache License, Version 2.0 (the "License");
  17677. * you may not use this file except in compliance with the License.
  17678. * You may obtain a copy of the License at
  17679. *
  17680. * http://www.apache.org/licenses/LICENSE-2.0
  17681. *
  17682. * Unless required by applicable law or agreed to in writing, software
  17683. * distributed under the License is distributed on an "AS IS" BASIS,
  17684. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17685. * See the License for the specific language governing permissions and
  17686. * limitations under the License.
  17687. */
  17688. /**
  17689. * @license
  17690. * Copyright 2020 Google LLC
  17691. *
  17692. * Licensed under the Apache License, Version 2.0 (the "License");
  17693. * you may not use this file except in compliance with the License.
  17694. * You may obtain a copy of the License at
  17695. *
  17696. * http://www.apache.org/licenses/LICENSE-2.0
  17697. *
  17698. * Unless required by applicable law or agreed to in writing, software
  17699. * distributed under the License is distributed on an "AS IS" BASIS,
  17700. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17701. * See the License for the specific language governing permissions and
  17702. * limitations under the License.
  17703. */
  17704. /**
  17705. * An immutable object representing an array of bytes.
  17706. */ var sl = /** @class */ function() {
  17707. /** @hideconstructor */
  17708. function t(t) {
  17709. this._byteString = t;
  17710. }
  17711. /**
  17712. * Creates a new `Bytes` object from the given Base64 string, converting it to
  17713. * bytes.
  17714. *
  17715. * @param base64 - The Base64 string used to create the `Bytes` object.
  17716. */ return t.fromBase64String = function(e) {
  17717. try {
  17718. return new t(Yt.fromBase64String(e));
  17719. } catch (e) {
  17720. throw new j(K.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + e);
  17721. }
  17722. },
  17723. /**
  17724. * Creates a new `Bytes` object from the given Uint8Array.
  17725. *
  17726. * @param array - The Uint8Array used to create the `Bytes` object.
  17727. */
  17728. t.fromUint8Array = function(e) {
  17729. return new t(Yt.fromUint8Array(e));
  17730. },
  17731. /**
  17732. * Returns the underlying bytes as a Base64-encoded string.
  17733. *
  17734. * @returns The Base64-encoded string created from the `Bytes` object.
  17735. */
  17736. t.prototype.toBase64 = function() {
  17737. return this._byteString.toBase64();
  17738. },
  17739. /**
  17740. * Returns the underlying bytes in a new `Uint8Array`.
  17741. *
  17742. * @returns The Uint8Array created from the `Bytes` object.
  17743. */
  17744. t.prototype.toUint8Array = function() {
  17745. return this._byteString.toUint8Array();
  17746. },
  17747. /**
  17748. * Returns a string representation of the `Bytes` object.
  17749. *
  17750. * @returns A string representation of the `Bytes` object.
  17751. */
  17752. t.prototype.toString = function() {
  17753. return "Bytes(base64: " + this.toBase64() + ")";
  17754. },
  17755. /**
  17756. * Returns true if this `Bytes` object is equal to the provided one.
  17757. *
  17758. * @param other - The `Bytes` object to compare against.
  17759. * @returns true if this `Bytes` object is equal to the provided one.
  17760. */
  17761. t.prototype.isEqual = function(t) {
  17762. return this._byteString.isEqual(t._byteString);
  17763. }, t;
  17764. }(), cl = /** @class */ function() {
  17765. /**
  17766. * Creates a `FieldPath` from the provided field names. If more than one field
  17767. * name is provided, the path will point to a nested field in a document.
  17768. *
  17769. * @param fieldNames - A list of field names.
  17770. */
  17771. function t() {
  17772. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  17773. for (var n = 0; n < t.length; ++n) if (0 === t[n].length) throw new j(K.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty.");
  17774. this._internalPath = new ht(t);
  17775. }
  17776. /**
  17777. * Returns true if this `FieldPath` is equal to the provided one.
  17778. *
  17779. * @param other - The `FieldPath` to compare against.
  17780. * @returns true if this `FieldPath` is equal to the provided one.
  17781. */ return t.prototype.isEqual = function(t) {
  17782. return this._internalPath.isEqual(t._internalPath);
  17783. }, t;
  17784. }();
  17785. /**
  17786. * @license
  17787. * Copyright 2020 Google LLC
  17788. *
  17789. * Licensed under the Apache License, Version 2.0 (the "License");
  17790. * you may not use this file except in compliance with the License.
  17791. * You may obtain a copy of the License at
  17792. *
  17793. * http://www.apache.org/licenses/LICENSE-2.0
  17794. *
  17795. * Unless required by applicable law or agreed to in writing, software
  17796. * distributed under the License is distributed on an "AS IS" BASIS,
  17797. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17798. * See the License for the specific language governing permissions and
  17799. * limitations under the License.
  17800. */
  17801. /**
  17802. * A `FieldPath` refers to a field in a document. The path may consist of a
  17803. * single field name (referring to a top-level field in the document), or a
  17804. * list of field names (referring to a nested field in the document).
  17805. *
  17806. * Create a `FieldPath` by providing field names. If more than one field
  17807. * name is provided, the path will point to a nested field in a document.
  17808. */
  17809. /**
  17810. * Returns a special sentinel `FieldPath` to refer to the ID of a document.
  17811. * It can be used in queries to sort or filter by the document ID.
  17812. */
  17813. function ll() {
  17814. return new cl("__name__");
  17815. }
  17816. /**
  17817. * @license
  17818. * Copyright 2020 Google LLC
  17819. *
  17820. * Licensed under the Apache License, Version 2.0 (the "License");
  17821. * you may not use this file except in compliance with the License.
  17822. * You may obtain a copy of the License at
  17823. *
  17824. * http://www.apache.org/licenses/LICENSE-2.0
  17825. *
  17826. * Unless required by applicable law or agreed to in writing, software
  17827. * distributed under the License is distributed on an "AS IS" BASIS,
  17828. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17829. * See the License for the specific language governing permissions and
  17830. * limitations under the License.
  17831. */
  17832. /**
  17833. * Sentinel values that can be used when writing document fields with `set()`
  17834. * or `update()`.
  17835. */ var hl =
  17836. /**
  17837. * @param _methodName - The public API endpoint that returns this class.
  17838. * @hideconstructor
  17839. */
  17840. function(t) {
  17841. this._methodName = t;
  17842. }, fl = /** @class */ function() {
  17843. /**
  17844. * Creates a new immutable `GeoPoint` object with the provided latitude and
  17845. * longitude values.
  17846. * @param latitude - The latitude as number between -90 and 90.
  17847. * @param longitude - The longitude as number between -180 and 180.
  17848. */
  17849. function t(t, e) {
  17850. if (!isFinite(t) || t < -90 || t > 90) throw new j(K.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + t);
  17851. if (!isFinite(e) || e < -180 || e > 180) throw new j(K.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + e);
  17852. this._lat = t, this._long = e;
  17853. }
  17854. return Object.defineProperty(t.prototype, "latitude", {
  17855. /**
  17856. * The latitude of this `GeoPoint` instance.
  17857. */
  17858. get: function() {
  17859. return this._lat;
  17860. },
  17861. enumerable: !1,
  17862. configurable: !0
  17863. }), Object.defineProperty(t.prototype, "longitude", {
  17864. /**
  17865. * The longitude of this `GeoPoint` instance.
  17866. */
  17867. get: function() {
  17868. return this._long;
  17869. },
  17870. enumerable: !1,
  17871. configurable: !0
  17872. }),
  17873. /**
  17874. * Returns true if this `GeoPoint` is equal to the provided one.
  17875. *
  17876. * @param other - The `GeoPoint` to compare against.
  17877. * @returns true if this `GeoPoint` is equal to the provided one.
  17878. */
  17879. t.prototype.isEqual = function(t) {
  17880. return this._lat === t._lat && this._long === t._long;
  17881. },
  17882. /** Returns a JSON-serializable representation of this GeoPoint. */ t.prototype.toJSON = function() {
  17883. return {
  17884. latitude: this._lat,
  17885. longitude: this._long
  17886. };
  17887. },
  17888. /**
  17889. * Actually private to JS consumers of our API, so this function is prefixed
  17890. * with an underscore.
  17891. */
  17892. t.prototype._compareTo = function(t) {
  17893. return rt(this._lat, t._lat) || rt(this._long, t._long);
  17894. }, t;
  17895. }(), dl = /^__.*__$/, pl = /** @class */ function() {
  17896. function t(t, e, n) {
  17897. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  17898. }
  17899. return t.prototype.toMutation = function(t, e) {
  17900. return null !== this.fieldMask ? new rr(t, this.data, this.fieldMask, e, this.fieldTransforms) : new nr(t, this.data, e, this.fieldTransforms);
  17901. }, t;
  17902. }(), yl = /** @class */ function() {
  17903. function t(t,
  17904. // The fieldMask does not include document transforms.
  17905. e, n) {
  17906. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  17907. }
  17908. return t.prototype.toMutation = function(t, e) {
  17909. return new rr(t, this.data, this.fieldMask, e, this.fieldTransforms);
  17910. }, t;
  17911. }();
  17912. /**
  17913. * @license
  17914. * Copyright 2017 Google LLC
  17915. *
  17916. * Licensed under the Apache License, Version 2.0 (the "License");
  17917. * you may not use this file except in compliance with the License.
  17918. * You may obtain a copy of the License at
  17919. *
  17920. * http://www.apache.org/licenses/LICENSE-2.0
  17921. *
  17922. * Unless required by applicable law or agreed to in writing, software
  17923. * distributed under the License is distributed on an "AS IS" BASIS,
  17924. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17925. * See the License for the specific language governing permissions and
  17926. * limitations under the License.
  17927. */
  17928. /**
  17929. * An immutable object representing a geographic location in Firestore. The
  17930. * location is represented as latitude/longitude pair.
  17931. *
  17932. * Latitude values are in the range of [-90, 90].
  17933. * Longitude values are in the range of [-180, 180].
  17934. */ function vl(t) {
  17935. switch (t) {
  17936. case 0 /* UserDataSource.Set */ :
  17937. // fall through
  17938. case 2 /* UserDataSource.MergeSet */ :
  17939. // fall through
  17940. case 1 /* UserDataSource.Update */ :
  17941. return !0;
  17942. case 3 /* UserDataSource.Argument */ :
  17943. case 4 /* UserDataSource.ArrayArgument */ :
  17944. return !1;
  17945. default:
  17946. throw q();
  17947. }
  17948. }
  17949. /** A "context" object passed around while parsing user data. */ var ml = /** @class */ function() {
  17950. /**
  17951. * Initializes a ParseContext with the given source and path.
  17952. *
  17953. * @param settings - The settings for the parser.
  17954. * @param databaseId - The database ID of the Firestore instance.
  17955. * @param serializer - The serializer to use to generate the Value proto.
  17956. * @param ignoreUndefinedProperties - Whether to ignore undefined properties
  17957. * rather than throw.
  17958. * @param fieldTransforms - A mutable list of field transforms encountered
  17959. * while parsing the data.
  17960. * @param fieldMask - A mutable list of field paths encountered while parsing
  17961. * the data.
  17962. *
  17963. * TODO(b/34871131): We don't support array paths right now, so path can be
  17964. * null to indicate the context represents any location within an array (in
  17965. * which case certain features will not work and errors will be somewhat
  17966. * compromised).
  17967. */
  17968. function t(t, e, n, r, i, o) {
  17969. this.settings = t, this.databaseId = e, this.yt = n, this.ignoreUndefinedProperties = r,
  17970. // Minor hack: If fieldTransforms is undefined, we assume this is an
  17971. // external call and we need to validate the entire path.
  17972. void 0 === i && this.na(), this.fieldTransforms = i || [], this.fieldMask = o || [];
  17973. }
  17974. return Object.defineProperty(t.prototype, "path", {
  17975. get: function() {
  17976. return this.settings.path;
  17977. },
  17978. enumerable: !1,
  17979. configurable: !0
  17980. }), Object.defineProperty(t.prototype, "sa", {
  17981. get: function() {
  17982. return this.settings.sa;
  17983. },
  17984. enumerable: !1,
  17985. configurable: !0
  17986. }),
  17987. /** Returns a new context with the specified settings overwritten. */ t.prototype.ia = function(e) {
  17988. return new t(Object.assign(Object.assign({}, this.settings), e), this.databaseId, this.yt, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);
  17989. }, t.prototype.ra = function(t) {
  17990. var e, n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), r = this.ia({
  17991. path: n,
  17992. oa: !1
  17993. });
  17994. return r.ua(t), r;
  17995. }, t.prototype.ca = function(t) {
  17996. var e, n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), r = this.ia({
  17997. path: n,
  17998. oa: !1
  17999. });
  18000. return r.na(), r;
  18001. }, t.prototype.aa = function(t) {
  18002. // TODO(b/34871131): We don't support array paths right now; so make path
  18003. // undefined.
  18004. return this.ia({
  18005. path: void 0,
  18006. oa: !0
  18007. });
  18008. }, t.prototype.ha = function(t) {
  18009. return Ll(t, this.settings.methodName, this.settings.la || !1, this.path, this.settings.fa);
  18010. },
  18011. /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ t.prototype.contains = function(t) {
  18012. return void 0 !== this.fieldMask.find((function(e) {
  18013. return t.isPrefixOf(e);
  18014. })) || void 0 !== this.fieldTransforms.find((function(e) {
  18015. return t.isPrefixOf(e.field);
  18016. }));
  18017. }, t.prototype.na = function() {
  18018. // TODO(b/34871131): Remove null check once we have proper paths for fields
  18019. // within arrays.
  18020. if (this.path) for (var t = 0; t < this.path.length; t++) this.ua(this.path.get(t));
  18021. }, t.prototype.ua = function(t) {
  18022. if (0 === t.length) throw this.ha("Document fields must not be empty");
  18023. if (vl(this.sa) && dl.test(t)) throw this.ha('Document fields cannot begin and end with "__"');
  18024. }, t;
  18025. }(), gl = /** @class */ function() {
  18026. function t(t, e, n) {
  18027. this.databaseId = t, this.ignoreUndefinedProperties = e, this.yt = n || ma(t)
  18028. /** Creates a new top-level parse context. */;
  18029. }
  18030. return t.prototype.da = function(t, e, n, r) {
  18031. return void 0 === r && (r = !1), new ml({
  18032. sa: t,
  18033. methodName: e,
  18034. fa: n,
  18035. path: ht.emptyPath(),
  18036. oa: !1,
  18037. la: r
  18038. }, this.databaseId, this.yt, this.ignoreUndefinedProperties);
  18039. }, t;
  18040. }();
  18041. /**
  18042. * Helper for parsing raw user input (provided via the API) into internal model
  18043. * classes.
  18044. */ function wl(t) {
  18045. var e = t._freezeSettings(), n = ma(t._databaseId);
  18046. return new gl(t._databaseId, !!e.ignoreUndefinedProperties, n);
  18047. }
  18048. /** Parse document data from a set() call. */ function bl(t, e, n, r, i, o) {
  18049. void 0 === o && (o = {});
  18050. var u = t.da(o.merge || o.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, n, i);
  18051. Ol("Data must be an object, but it was:", u, r);
  18052. var a, s, c = kl(r, u);
  18053. if (o.merge) a = new tn(u.fieldMask), s = u.fieldTransforms; else if (o.mergeFields) {
  18054. for (var l = [], h = 0, f = o.mergeFields; h < f.length; h++) {
  18055. var d = Rl(e, f[h], n);
  18056. if (!u.contains(d)) throw new j(K.INVALID_ARGUMENT, "Field '".concat(d, "' is specified in your field mask but missing from your input data."));
  18057. Pl(l, d) || l.push(d);
  18058. }
  18059. a = new tn(l), s = u.fieldTransforms.filter((function(t) {
  18060. return a.covers(t.field);
  18061. }));
  18062. } else a = null, s = u.fieldTransforms;
  18063. return new pl(new en(c), a, s);
  18064. }
  18065. var Il = /** @class */ function(e) {
  18066. function n() {
  18067. return null !== e && e.apply(this, arguments) || this;
  18068. }
  18069. return t(n, e), n.prototype._toFieldTransform = function(t) {
  18070. if (2 /* UserDataSource.MergeSet */ !== t.sa) throw 1 /* UserDataSource.Update */ === t.sa ? t.ha("".concat(this._methodName, "() can only appear at the top level of your update data")) : t.ha("".concat(this._methodName, "() cannot be used with set() unless you pass {merge:true}"));
  18071. // No transform to add for a delete, but we need to add it to our
  18072. // fieldMask so it gets deleted.
  18073. return t.fieldMask.push(t.path), null;
  18074. }, n.prototype.isEqual = function(t) {
  18075. return t instanceof n;
  18076. }, n;
  18077. }(hl);
  18078. /**
  18079. * Creates a child context for parsing SerializableFieldValues.
  18080. *
  18081. * This is different than calling `ParseContext.contextWith` because it keeps
  18082. * the fieldTransforms and fieldMask separate.
  18083. *
  18084. * The created context has its `dataSource` set to `UserDataSource.Argument`.
  18085. * Although these values are used with writes, any elements in these FieldValues
  18086. * are not considered writes since they cannot contain any FieldValue sentinels,
  18087. * etc.
  18088. *
  18089. * @param fieldValue - The sentinel FieldValue for which to create a child
  18090. * context.
  18091. * @param context - The parent context.
  18092. * @param arrayElement - Whether or not the FieldValue has an array.
  18093. */ function Tl(t, e, n) {
  18094. return new ml({
  18095. sa: 3 /* UserDataSource.Argument */ ,
  18096. fa: e.settings.fa,
  18097. methodName: t._methodName,
  18098. oa: n
  18099. }, e.databaseId, e.yt, e.ignoreUndefinedProperties);
  18100. }
  18101. var El = /** @class */ function(e) {
  18102. function n() {
  18103. return null !== e && e.apply(this, arguments) || this;
  18104. }
  18105. return t(n, e), n.prototype._toFieldTransform = function(t) {
  18106. return new zn(t.path, new Pn);
  18107. }, n.prototype.isEqual = function(t) {
  18108. return t instanceof n;
  18109. }, n;
  18110. }(hl), Sl = /** @class */ function(e) {
  18111. function n(t, n) {
  18112. var r = this;
  18113. return (r = e.call(this, t) || this)._a = n, r;
  18114. }
  18115. return t(n, e), n.prototype._toFieldTransform = function(t) {
  18116. var e = Tl(this, t,
  18117. /*array=*/ !0), n = this._a.map((function(t) {
  18118. return Nl(t, e);
  18119. })), r = new qn(n);
  18120. return new zn(t.path, r);
  18121. }, n.prototype.isEqual = function(t) {
  18122. // TODO(mrschmidt): Implement isEquals
  18123. return this === t;
  18124. }, n;
  18125. }(hl), _l = /** @class */ function(e) {
  18126. function n(t, n) {
  18127. var r = this;
  18128. return (r = e.call(this, t) || this)._a = n, r;
  18129. }
  18130. return t(n, e), n.prototype._toFieldTransform = function(t) {
  18131. var e = Tl(this, t,
  18132. /*array=*/ !0), n = this._a.map((function(t) {
  18133. return Nl(t, e);
  18134. })), r = new Bn(n);
  18135. return new zn(t.path, r);
  18136. }, n.prototype.isEqual = function(t) {
  18137. // TODO(mrschmidt): Implement isEquals
  18138. return this === t;
  18139. }, n;
  18140. }(hl), Dl = /** @class */ function(e) {
  18141. function n(t, n) {
  18142. var r = this;
  18143. return (r = e.call(this, t) || this).wa = n, r;
  18144. }
  18145. return t(n, e), n.prototype._toFieldTransform = function(t) {
  18146. var e = new Kn(t.yt, On(t.yt, this.wa));
  18147. return new zn(t.path, e);
  18148. }, n.prototype.isEqual = function(t) {
  18149. // TODO(mrschmidt): Implement isEquals
  18150. return this === t;
  18151. }, n;
  18152. }(hl);
  18153. /** Parse update data from an update() call. */ function xl(t, e, n, r) {
  18154. var i = t.da(1 /* UserDataSource.Update */ , e, n);
  18155. Ol("Data must be an object, but it was:", i, r);
  18156. var o = [], u = en.empty();
  18157. Kt(r, (function(t, r) {
  18158. var a = Ml(e, t, n);
  18159. // For Compat types, we have to "extract" the underlying types before
  18160. // performing validation.
  18161. r = y(r);
  18162. var s = i.ca(a);
  18163. if (r instanceof Il)
  18164. // Add it to the field mask, but don't add anything to updateData.
  18165. o.push(a); else {
  18166. var c = Nl(r, s);
  18167. null != c && (o.push(a), u.set(a, c));
  18168. }
  18169. }));
  18170. var a = new tn(o);
  18171. return new yl(u, a, i.fieldTransforms);
  18172. }
  18173. /** Parse update data from a list of field/value arguments. */ function Al(t, e, n, r, i, o) {
  18174. var u = t.da(1 /* UserDataSource.Update */ , e, n), a = [ Rl(e, r, n) ], s = [ i ];
  18175. if (o.length % 2 != 0) throw new j(K.INVALID_ARGUMENT, "Function ".concat(e, "() needs to be called with an even number of arguments that alternate between field names and values."));
  18176. for (var c = 0; c < o.length; c += 2) a.push(Rl(e, o[c])), s.push(o[c + 1]);
  18177. // We iterate in reverse order to pick the last value for a field if the
  18178. // user specified the field multiple times.
  18179. for (var l = [], h = en.empty(), f = a.length - 1; f >= 0; --f) if (!Pl(l, a[f])) {
  18180. var d = a[f], p = s[f];
  18181. // For Compat types, we have to "extract" the underlying types before
  18182. // performing validation.
  18183. p = y(p);
  18184. var v = u.ca(d);
  18185. if (p instanceof Il)
  18186. // Add it to the field mask, but don't add anything to updateData.
  18187. l.push(d); else {
  18188. var m = Nl(p, v);
  18189. null != m && (l.push(d), h.set(d, m));
  18190. }
  18191. }
  18192. var g = new tn(l);
  18193. return new yl(h, g, u.fieldTransforms);
  18194. }
  18195. /**
  18196. * Parse a "query value" (e.g. value in a where filter or a value in a cursor
  18197. * bound).
  18198. *
  18199. * @param allowArrays - Whether the query value is an array that may directly
  18200. * contain additional arrays (e.g. the operand of an `in` query).
  18201. */ function Cl(t, e, n, r) {
  18202. return void 0 === r && (r = !1), Nl(n, t.da(r ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e));
  18203. }
  18204. /**
  18205. * Parses user data to Protobuf Values.
  18206. *
  18207. * @param input - Data to be parsed.
  18208. * @param context - A context object representing the current path being parsed,
  18209. * the source of the data being parsed, etc.
  18210. * @returns The parsed value, or null if the value was a FieldValue sentinel
  18211. * that should not be included in the resulting parsed data.
  18212. */ function Nl(t, e) {
  18213. if (Fl(
  18214. // Unwrap the API type from the Compat SDK. This will return the API type
  18215. // from firestore-exp.
  18216. t = y(t))) return Ol("Unsupported field value:", e, t), kl(t, e);
  18217. if (t instanceof hl)
  18218. // FieldValues usually parse into transforms (except deleteField())
  18219. // in which case we do not want to include this field in our parsed data
  18220. // (as doing so will overwrite the field directly prior to the transform
  18221. // trying to transform it). So we don't add this location to
  18222. // context.fieldMask and we return null as our parsing result.
  18223. /**
  18224. * "Parses" the provided FieldValueImpl, adding any necessary transforms to
  18225. * context.fieldTransforms.
  18226. */
  18227. return function(t, e) {
  18228. // Sentinels are only supported with writes, and not within arrays.
  18229. if (!vl(e.sa)) throw e.ha("".concat(t._methodName, "() can only be used with update() and set()"));
  18230. if (!e.path) throw e.ha("".concat(t._methodName, "() is not currently supported inside arrays"));
  18231. var n = t._toFieldTransform(e);
  18232. n && e.fieldTransforms.push(n);
  18233. }(t, e), null;
  18234. if (void 0 === t && e.ignoreUndefinedProperties)
  18235. // If the input is undefined it can never participate in the fieldMask, so
  18236. // don't handle this below. If `ignoreUndefinedProperties` is false,
  18237. // `parseScalarValue` will reject an undefined value.
  18238. return null;
  18239. if (
  18240. // If context.path is null we are inside an array and we don't support
  18241. // field mask paths more granular than the top-level array.
  18242. e.path && e.fieldMask.push(e.path), t instanceof Array) {
  18243. // TODO(b/34871131): Include the path containing the array in the error
  18244. // message.
  18245. // In the case of IN queries, the parsed data is an array (representing
  18246. // the set of values to be included for the IN query) that may directly
  18247. // contain additional arrays (each representing an individual field
  18248. // value), so we disable this validation.
  18249. if (e.settings.oa && 4 /* UserDataSource.ArrayArgument */ !== e.sa) throw e.ha("Nested arrays are not supported");
  18250. return function(t, e) {
  18251. for (var n = [], r = 0, i = 0, o = t; i < o.length; i++) {
  18252. var u = Nl(o[i], e.aa(r));
  18253. null == u && (
  18254. // Just include nulls in the array for fields being replaced with a
  18255. // sentinel.
  18256. u = {
  18257. nullValue: "NULL_VALUE"
  18258. }), n.push(u), r++;
  18259. }
  18260. return {
  18261. arrayValue: {
  18262. values: n
  18263. }
  18264. };
  18265. }(t, e);
  18266. }
  18267. return function(t, e) {
  18268. if (null === (t = y(t))) return {
  18269. nullValue: "NULL_VALUE"
  18270. };
  18271. if ("number" == typeof t) return On(e.yt, t);
  18272. if ("boolean" == typeof t) return {
  18273. booleanValue: t
  18274. };
  18275. if ("string" == typeof t) return {
  18276. stringValue: t
  18277. };
  18278. if (t instanceof Date) {
  18279. var n = ut.fromDate(t);
  18280. return {
  18281. timestampValue: Br(e.yt, n)
  18282. };
  18283. }
  18284. if (t instanceof ut) {
  18285. // Firestore backend truncates precision down to microseconds. To ensure
  18286. // offline mode works the same with regards to truncation, perform the
  18287. // truncation immediately without waiting for the backend to do that.
  18288. var r = new ut(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));
  18289. return {
  18290. timestampValue: Br(e.yt, r)
  18291. };
  18292. }
  18293. if (t instanceof fl) return {
  18294. geoPointValue: {
  18295. latitude: t.latitude,
  18296. longitude: t.longitude
  18297. }
  18298. };
  18299. if (t instanceof sl) return {
  18300. bytesValue: Gr(e.yt, t._byteString)
  18301. };
  18302. if (t instanceof dc) {
  18303. var i = e.databaseId, o = t.firestore._databaseId;
  18304. if (!o.isEqual(i)) throw e.ha("Document reference is for database ".concat(o.projectId, "/").concat(o.database, " but should be for database ").concat(i.projectId, "/").concat(i.database));
  18305. return {
  18306. referenceValue: Qr(t.firestore._databaseId || e.databaseId, t._key.path)
  18307. };
  18308. }
  18309. throw e.ha("Unsupported field value: ".concat(uc(t)));
  18310. }(t, e);
  18311. }
  18312. function kl(t, e) {
  18313. var n = {};
  18314. return jt(t) ?
  18315. // If we encounter an empty object, we explicitly add it to the update
  18316. // mask to ensure that the server creates a map entry.
  18317. e.path && e.path.length > 0 && e.fieldMask.push(e.path) : Kt(t, (function(t, r) {
  18318. var i = Nl(r, e.ra(t));
  18319. null != i && (n[t] = i);
  18320. })), {
  18321. mapValue: {
  18322. fields: n
  18323. }
  18324. };
  18325. }
  18326. function Fl(t) {
  18327. return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof ut || t instanceof fl || t instanceof sl || t instanceof dc || t instanceof hl);
  18328. }
  18329. function Ol(t, e, n) {
  18330. if (!Fl(n) || !function(t) {
  18331. return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));
  18332. }(n)) {
  18333. var r = uc(n);
  18334. throw "an object" === r ? e.ha(t + " a custom object") : e.ha(t + " " + r);
  18335. }
  18336. }
  18337. /**
  18338. * Helper that calls fromDotSeparatedString() but wraps any error thrown.
  18339. */ function Rl(t, e, n) {
  18340. if (
  18341. // If required, replace the FieldPath Compat class with with the firestore-exp
  18342. // FieldPath.
  18343. (e = y(e)) instanceof cl) return e._internalPath;
  18344. if ("string" == typeof e) return Ml(t, e);
  18345. throw Ll("Field path arguments must be of type string or ", t,
  18346. /* hasConverter= */ !1,
  18347. /* path= */ void 0, n);
  18348. }
  18349. /**
  18350. * Matches any characters in a field path string that are reserved.
  18351. */ var Vl = new RegExp("[~\\*/\\[\\]]");
  18352. /**
  18353. * Wraps fromDotSeparatedString with an error message about the method that
  18354. * was thrown.
  18355. * @param methodName - The publicly visible method name
  18356. * @param path - The dot-separated string form of a field path which will be
  18357. * split on dots.
  18358. * @param targetDoc - The document against which the field path will be
  18359. * evaluated.
  18360. */ function Ml(t, e, n) {
  18361. if (e.search(Vl) >= 0) throw Ll("Invalid field path (".concat(e, "). Paths must not contain '~', '*', '/', '[', or ']'"), t,
  18362. /* hasConverter= */ !1,
  18363. /* path= */ void 0, n);
  18364. try {
  18365. return (new (cl.bind.apply(cl, r([ void 0 ], e.split("."), !1))))._internalPath;
  18366. } catch (r) {
  18367. throw Ll("Invalid field path (".concat(e, "). Paths must not be empty, begin with '.', end with '.', or contain '..'"), t,
  18368. /* hasConverter= */ !1,
  18369. /* path= */ void 0, n);
  18370. }
  18371. }
  18372. function Ll(t, e, n, r, i) {
  18373. var o = r && !r.isEmpty(), u = void 0 !== i, a = "Function ".concat(e, "() called with invalid data");
  18374. n && (a += " (via `toFirestore()`)"), a += ". ";
  18375. var s = "";
  18376. return (o || u) && (s += " (found", o && (s += " in field ".concat(r)), u && (s += " in document ".concat(i)),
  18377. s += ")"), new j(K.INVALID_ARGUMENT, a + t + s)
  18378. /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */;
  18379. }
  18380. function Pl(t, e) {
  18381. return t.some((function(t) {
  18382. return t.isEqual(e);
  18383. }));
  18384. }
  18385. /**
  18386. * @license
  18387. * Copyright 2020 Google LLC
  18388. *
  18389. * Licensed under the Apache License, Version 2.0 (the "License");
  18390. * you may not use this file except in compliance with the License.
  18391. * You may obtain a copy of the License at
  18392. *
  18393. * http://www.apache.org/licenses/LICENSE-2.0
  18394. *
  18395. * Unless required by applicable law or agreed to in writing, software
  18396. * distributed under the License is distributed on an "AS IS" BASIS,
  18397. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18398. * See the License for the specific language governing permissions and
  18399. * limitations under the License.
  18400. */
  18401. /**
  18402. * A `DocumentSnapshot` contains data read from a document in your Firestore
  18403. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  18404. * get a specific field.
  18405. *
  18406. * For a `DocumentSnapshot` that points to a non-existing document, any data
  18407. * access will return 'undefined'. You can use the `exists()` method to
  18408. * explicitly verify a document's existence.
  18409. */ var ql = /** @class */ function() {
  18410. // Note: This class is stripped down version of the DocumentSnapshot in
  18411. // the legacy SDK. The changes are:
  18412. // - No support for SnapshotMetadata.
  18413. // - No support for SnapshotOptions.
  18414. /** @hideconstructor protected */
  18415. function t(t, e, n, r, i) {
  18416. this._firestore = t, this._userDataWriter = e, this._key = n, this._document = r,
  18417. this._converter = i;
  18418. }
  18419. return Object.defineProperty(t.prototype, "id", {
  18420. /** Property of the `DocumentSnapshot` that provides the document's ID. */ get: function() {
  18421. return this._key.path.lastSegment();
  18422. },
  18423. enumerable: !1,
  18424. configurable: !0
  18425. }), Object.defineProperty(t.prototype, "ref", {
  18426. /**
  18427. * The `DocumentReference` for the document included in the `DocumentSnapshot`.
  18428. */
  18429. get: function() {
  18430. return new dc(this._firestore, this._converter, this._key);
  18431. },
  18432. enumerable: !1,
  18433. configurable: !0
  18434. }),
  18435. /**
  18436. * Signals whether or not the document at the snapshot's location exists.
  18437. *
  18438. * @returns true if the document exists.
  18439. */
  18440. t.prototype.exists = function() {
  18441. return null !== this._document;
  18442. },
  18443. /**
  18444. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  18445. * the document doesn't exist.
  18446. *
  18447. * @returns An `Object` containing all fields in the document or `undefined`
  18448. * if the document doesn't exist.
  18449. */
  18450. t.prototype.data = function() {
  18451. if (this._document) {
  18452. if (this._converter) {
  18453. // We only want to use the converter and create a new DocumentSnapshot
  18454. // if a converter has been provided.
  18455. var t = new Ul(this._firestore, this._userDataWriter, this._key, this._document,
  18456. /* converter= */ null);
  18457. return this._converter.fromFirestore(t);
  18458. }
  18459. return this._userDataWriter.convertValue(this._document.data.value);
  18460. }
  18461. },
  18462. /**
  18463. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  18464. * document or field doesn't exist.
  18465. *
  18466. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  18467. * field.
  18468. * @returns The data at the specified field location or undefined if no such
  18469. * field exists in the document.
  18470. */
  18471. // We are using `any` here to avoid an explicit cast by our users.
  18472. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  18473. t.prototype.get = function(t) {
  18474. if (this._document) {
  18475. var e = this._document.data.field(Bl("DocumentSnapshot.get", t));
  18476. if (null !== e) return this._userDataWriter.convertValue(e);
  18477. }
  18478. }, t;
  18479. }(), Ul = /** @class */ function(e) {
  18480. function n() {
  18481. return null !== e && e.apply(this, arguments) || this;
  18482. }
  18483. /**
  18484. * Retrieves all fields in the document as an `Object`.
  18485. *
  18486. * @override
  18487. * @returns An `Object` containing all fields in the document.
  18488. */ return t(n, e), n.prototype.data = function() {
  18489. return e.prototype.data.call(this);
  18490. }, n;
  18491. }(ql);
  18492. /**
  18493. * A `QueryDocumentSnapshot` contains data read from a document in your
  18494. * Firestore database as part of a query. The document is guaranteed to exist
  18495. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  18496. * specific field.
  18497. *
  18498. * A `QueryDocumentSnapshot` offers the same API surface as a
  18499. * `DocumentSnapshot`. Since query results contain only existing documents, the
  18500. * `exists` property will always be true and `data()` will never return
  18501. * 'undefined'.
  18502. */
  18503. /**
  18504. * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.
  18505. */
  18506. function Bl(t, e) {
  18507. return "string" == typeof e ? Ml(t, e) : e instanceof cl ? e._internalPath : e._delegate._internalPath;
  18508. }
  18509. /**
  18510. * @license
  18511. * Copyright 2020 Google LLC
  18512. *
  18513. * Licensed under the Apache License, Version 2.0 (the "License");
  18514. * you may not use this file except in compliance with the License.
  18515. * You may obtain a copy of the License at
  18516. *
  18517. * http://www.apache.org/licenses/LICENSE-2.0
  18518. *
  18519. * Unless required by applicable law or agreed to in writing, software
  18520. * distributed under the License is distributed on an "AS IS" BASIS,
  18521. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18522. * See the License for the specific language governing permissions and
  18523. * limitations under the License.
  18524. */ function Gl(t) {
  18525. if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new j(K.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause");
  18526. }
  18527. /**
  18528. * An `AppliableConstraint` is an abstraction of a constraint that can be applied
  18529. * to a Firestore query.
  18530. */ var Kl = function() {}, jl = /** @class */ function(e) {
  18531. function n() {
  18532. return null !== e && e.apply(this, arguments) || this;
  18533. }
  18534. return t(n, e), n;
  18535. }(Kl);
  18536. /**
  18537. * A `QueryConstraint` is used to narrow the set of documents returned by a
  18538. * Firestore query. `QueryConstraint`s are created by invoking {@link where},
  18539. * {@link orderBy}, {@link startAt}, {@link startAfter}, {@link
  18540. * endBefore}, {@link endAt}, {@link limit}, {@link limitToLast} and
  18541. * can then be passed to {@link query} to create a new query instance that
  18542. * also contains this `QueryConstraint`.
  18543. */ function Ql(t, e) {
  18544. for (var n = [], r = 2; r < arguments.length; r++) n[r - 2] = arguments[r];
  18545. var i = [];
  18546. e instanceof Kl && i.push(e), function(t) {
  18547. var e = t.filter((function(t) {
  18548. return t instanceof Hl;
  18549. })).length, n = t.filter((function(t) {
  18550. return t instanceof zl;
  18551. })).length;
  18552. if (e > 1 || e > 0 && n > 0) throw new j(K.INVALID_ARGUMENT, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.");
  18553. }(i = i.concat(n));
  18554. for (var o = 0, u = i; o < u.length; o++) {
  18555. var a = u[o];
  18556. t = a._apply(t);
  18557. }
  18558. return t;
  18559. }
  18560. /**
  18561. * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
  18562. * a Firestore query by filtering on one or more document fields.
  18563. * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
  18564. * be passed to {@link query} to create a new query instance that also contains
  18565. * this `QueryFieldFilterConstraint`.
  18566. */ var zl = /** @class */ function(e) {
  18567. /**
  18568. * @internal
  18569. */
  18570. function n(t, n, r) {
  18571. var i = this;
  18572. return (i = e.call(this) || this)._field = t, i._op = n, i._value = r,
  18573. /** The type of this query constraint */
  18574. i.type = "where", i;
  18575. }
  18576. return t(n, e), n._create = function(t, e, r) {
  18577. return new n(t, e, r);
  18578. }, n.prototype._apply = function(t) {
  18579. var e = this._parse(t);
  18580. return hh(t._query, e), new pc(t.firestore, t.converter, Tn(t._query, e));
  18581. }, n.prototype._parse = function(t) {
  18582. var e = wl(t.firestore), n = function(t, e, n, r, i, o, u) {
  18583. var a;
  18584. if (i.isKeyField()) {
  18585. if ("array-contains" /* Operator.ARRAY_CONTAINS */ === o || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === o) throw new j(K.INVALID_ARGUMENT, "Invalid Query. You can't perform '".concat(o, "' queries on documentId()."));
  18586. if ("in" /* Operator.IN */ === o || "not-in" /* Operator.NOT_IN */ === o) {
  18587. lh(u, o);
  18588. for (var s = [], c = 0, l = u; c < l.length; c++) {
  18589. var h = l[c];
  18590. s.push(ch(r, t, h));
  18591. }
  18592. a = {
  18593. arrayValue: {
  18594. values: s
  18595. }
  18596. };
  18597. } else a = ch(r, t, u);
  18598. } else "in" /* Operator.IN */ !== o && "not-in" /* Operator.NOT_IN */ !== o && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== o || lh(u, o),
  18599. a = Cl(n, "where", u,
  18600. /* allowArrays= */ "in" /* Operator.IN */ === o || "not-in" /* Operator.NOT_IN */ === o);
  18601. return Ae.create(i, o, a);
  18602. }(t._query, 0, e, t.firestore._databaseId, this._field, this._op, this._value);
  18603. return n;
  18604. }, n;
  18605. }(jl);
  18606. /**
  18607. * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
  18608. * must contain the specified field and that the value should satisfy the
  18609. * relation constraint provided.
  18610. *
  18611. * @param fieldPath - The path to compare
  18612. * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
  18613. * "&lt;=", "!=").
  18614. * @param value - The value for comparison
  18615. * @returns The created {@link QueryFieldFilterConstraint}.
  18616. */ function Wl(t, e, n) {
  18617. var r = e, i = Bl("where", t);
  18618. return zl._create(i, r, n);
  18619. }
  18620. /**
  18621. * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
  18622. * returned by a Firestore query by performing the logical OR or AND of multiple
  18623. * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
  18624. * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
  18625. * {@link and} and can then be passed to {@link query} to create a new query
  18626. * instance that also contains the `QueryCompositeFilterConstraint`.
  18627. * @internal TODO remove this internal tag with OR Query support in the server
  18628. */ var Hl = /** @class */ function(e) {
  18629. /**
  18630. * @internal
  18631. */
  18632. function n(
  18633. /** The type of this query constraint */
  18634. t, n) {
  18635. var r = this;
  18636. return (r = e.call(this) || this).type = t, r._queryConstraints = n, r;
  18637. }
  18638. return t(n, e), n._create = function(t, e) {
  18639. return new n(t, e);
  18640. }, n.prototype._parse = function(t) {
  18641. var e = this._queryConstraints.map((function(e) {
  18642. return e._parse(t);
  18643. })).filter((function(t) {
  18644. return t.getFilters().length > 0;
  18645. }));
  18646. return 1 === e.length ? e[0] : Ce.create(e, this._getOperator());
  18647. }, n.prototype._apply = function(t) {
  18648. var e = this._parse(t);
  18649. return 0 === e.getFilters().length ? t : (function(t, e) {
  18650. for (var n = t, r = 0, i = e.getFlattenedFilters(); r < i.length; r++) {
  18651. var o = i[r];
  18652. hh(n, o), n = Tn(n, o);
  18653. }
  18654. }(t._query, e), new pc(t.firestore, t.converter, Tn(t._query, e)));
  18655. }, n.prototype._getQueryConstraints = function() {
  18656. return this._queryConstraints;
  18657. }, n.prototype._getOperator = function() {
  18658. return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */;
  18659. }, n;
  18660. }(Kl);
  18661. /**
  18662. * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of
  18663. * the given filter constraints. A disjunction filter includes a document if it
  18664. * satisfies any of the given filters.
  18665. *
  18666. * @param queryConstraints - Optional. The list of
  18667. * {@link QueryFilterConstraint}s to perform a disjunction for. These must be
  18668. * created with calls to {@link where}, {@link or}, or {@link and}.
  18669. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  18670. * @internal TODO remove this internal tag with OR Query support in the server
  18671. */ function Yl() {
  18672. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  18673. // Only support QueryFilterConstraints
  18674. return t.forEach((function(t) {
  18675. return dh("or", t);
  18676. })), Hl._create("or" /* CompositeOperator.OR */ , t)
  18677. /**
  18678. * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of
  18679. * the given filter constraints. A conjunction filter includes a document if it
  18680. * satisfies all of the given filters.
  18681. *
  18682. * @param queryConstraints - Optional. The list of
  18683. * {@link QueryFilterConstraint}s to perform a conjunction for. These must be
  18684. * created with calls to {@link where}, {@link or}, or {@link and}.
  18685. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  18686. * @internal TODO remove this internal tag with OR Query support in the server
  18687. */;
  18688. }
  18689. function Xl() {
  18690. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  18691. // Only support QueryFilterConstraints
  18692. return t.forEach((function(t) {
  18693. return dh("and", t);
  18694. })), Hl._create("and" /* CompositeOperator.AND */ , t)
  18695. /**
  18696. * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
  18697. * Firestore query. `QueryOrderByConstraint`s are created by invoking
  18698. * {@link orderBy} and can then be passed to {@link query} to create a new query
  18699. * instance that also contains this `QueryOrderByConstraint`.
  18700. *
  18701. * Note: Documents that do not contain the orderBy field will not be present in
  18702. * the query result.
  18703. */;
  18704. }
  18705. var Zl = /** @class */ function(e) {
  18706. /**
  18707. * @internal
  18708. */
  18709. function n(t, n) {
  18710. var r = this;
  18711. return (r = e.call(this) || this)._field = t, r._direction = n,
  18712. /** The type of this query constraint */
  18713. r.type = "orderBy", r;
  18714. }
  18715. return t(n, e), n._create = function(t, e) {
  18716. return new n(t, e);
  18717. }, n.prototype._apply = function(t) {
  18718. var e = function(t, e, n) {
  18719. if (null !== t.startAt) throw new j(K.INVALID_ARGUMENT, "Invalid query. You must not call startAt() or startAfter() before calling orderBy().");
  18720. if (null !== t.endAt) throw new j(K.INVALID_ARGUMENT, "Invalid query. You must not call endAt() or endBefore() before calling orderBy().");
  18721. var r = new ze(e, n);
  18722. return function(t, e) {
  18723. if (null === mn(t)) {
  18724. // This is the first order by. It must match any inequality.
  18725. var n = gn(t);
  18726. null !== n && fh(t, n, e.field);
  18727. }
  18728. }(t, r), r;
  18729. }(t._query, this._field, this._direction);
  18730. return new pc(t.firestore, t.converter, function(t, e) {
  18731. // TODO(dimond): validate that orderBy does not list the same key twice.
  18732. var n = t.explicitOrderBy.concat([ e ]);
  18733. return new dn(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  18734. }(t._query, e));
  18735. }, n;
  18736. }(jl);
  18737. /**
  18738. * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
  18739. * specified field, optionally in descending order instead of ascending.
  18740. *
  18741. * Note: Documents that do not contain the specified field will not be present
  18742. * in the query result.
  18743. *
  18744. * @param fieldPath - The field to sort by.
  18745. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
  18746. * not specified, order will be ascending.
  18747. * @returns The created {@link QueryOrderByConstraint}.
  18748. */ function Jl(t, e) {
  18749. void 0 === e && (e = "asc");
  18750. var n = e, r = Bl("orderBy", t);
  18751. return Zl._create(r, n);
  18752. }
  18753. /**
  18754. * A `QueryLimitConstraint` is used to limit the number of documents returned by
  18755. * a Firestore query.
  18756. * `QueryLimitConstraint`s are created by invoking {@link limit} or
  18757. * {@link limitToLast} and can then be passed to {@link query} to create a new
  18758. * query instance that also contains this `QueryLimitConstraint`.
  18759. */ var $l = /** @class */ function(e) {
  18760. /**
  18761. * @internal
  18762. */
  18763. function n(
  18764. /** The type of this query constraint */
  18765. t, n, r) {
  18766. var i = this;
  18767. return (i = e.call(this) || this).type = t, i._limit = n, i._limitType = r, i;
  18768. }
  18769. return t(n, e), n._create = function(t, e, r) {
  18770. return new n(t, e, r);
  18771. }, n.prototype._apply = function(t) {
  18772. return new pc(t.firestore, t.converter, En(t._query, this._limit, this._limitType));
  18773. }, n;
  18774. }(jl);
  18775. /**
  18776. * Creates a {@link QueryLimitConstraint} that only returns the first matching
  18777. * documents.
  18778. *
  18779. * @param limit - The maximum number of items to return.
  18780. * @returns The created {@link QueryLimitConstraint}.
  18781. */ function th(t) {
  18782. return sc("limit", t), $l._create("limit", t, "F" /* LimitType.First */)
  18783. /**
  18784. * Creates a {@link QueryLimitConstraint} that only returns the last matching
  18785. * documents.
  18786. *
  18787. * You must specify at least one `orderBy` clause for `limitToLast` queries,
  18788. * otherwise an exception will be thrown during execution.
  18789. *
  18790. * @param limit - The maximum number of items to return.
  18791. * @returns The created {@link QueryLimitConstraint}.
  18792. */;
  18793. }
  18794. function eh(t) {
  18795. return sc("limitToLast", t), $l._create("limitToLast", t, "L" /* LimitType.Last */)
  18796. /**
  18797. * A `QueryStartAtConstraint` is used to exclude documents from the start of a
  18798. * result set returned by a Firestore query.
  18799. * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
  18800. * {@link (startAfter:1)} and can then be passed to {@link query} to create a
  18801. * new query instance that also contains this `QueryStartAtConstraint`.
  18802. */;
  18803. }
  18804. var nh = /** @class */ function(e) {
  18805. /**
  18806. * @internal
  18807. */
  18808. function n(
  18809. /** The type of this query constraint */
  18810. t, n, r) {
  18811. var i = this;
  18812. return (i = e.call(this) || this).type = t, i._docOrFields = n, i._inclusive = r,
  18813. i;
  18814. }
  18815. return t(n, e), n._create = function(t, e, r) {
  18816. return new n(t, e, r);
  18817. }, n.prototype._apply = function(t) {
  18818. var e = sh(t, this.type, this._docOrFields, this._inclusive);
  18819. return new pc(t.firestore, t.converter, function(t, e) {
  18820. return new dn(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt);
  18821. }(t._query, e));
  18822. }, n;
  18823. }(jl);
  18824. function rh() {
  18825. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  18826. return nh._create("startAt", t,
  18827. /*inclusive=*/ !0);
  18828. }
  18829. function ih() {
  18830. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  18831. return nh._create("startAfter", t,
  18832. /*inclusive=*/ !1);
  18833. }
  18834. /**
  18835. * A `QueryEndAtConstraint` is used to exclude documents from the end of a
  18836. * result set returned by a Firestore query.
  18837. * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
  18838. * {@link (endBefore:1)} and can then be passed to {@link query} to create a new
  18839. * query instance that also contains this `QueryEndAtConstraint`.
  18840. */ var oh = /** @class */ function(e) {
  18841. /**
  18842. * @internal
  18843. */
  18844. function n(
  18845. /** The type of this query constraint */
  18846. t, n, r) {
  18847. var i = this;
  18848. return (i = e.call(this) || this).type = t, i._docOrFields = n, i._inclusive = r,
  18849. i;
  18850. }
  18851. return t(n, e), n._create = function(t, e, r) {
  18852. return new n(t, e, r);
  18853. }, n.prototype._apply = function(t) {
  18854. var e = sh(t, this.type, this._docOrFields, this._inclusive);
  18855. return new pc(t.firestore, t.converter, function(t, e) {
  18856. return new dn(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e);
  18857. }(t._query, e));
  18858. }, n;
  18859. }(jl);
  18860. function uh() {
  18861. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  18862. return oh._create("endBefore", t,
  18863. /*inclusive=*/ !1);
  18864. }
  18865. function ah() {
  18866. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  18867. return oh._create("endAt", t,
  18868. /*inclusive=*/ !0);
  18869. }
  18870. /** Helper function to create a bound from a document or fields */ function sh(t, e, n, r) {
  18871. if (n[0] = y(n[0]), n[0] instanceof ql) return function(t, e, n, r, i) {
  18872. if (!r) throw new j(K.NOT_FOUND, "Can't use a DocumentSnapshot that doesn't exist for ".concat(n, "()."));
  18873. // Because people expect to continue/end a query at the exact document
  18874. // provided, we need to use the implicit sort order rather than the explicit
  18875. // sort order, because it's guaranteed to contain the document key. That way
  18876. // the position becomes unambiguous and the query continues/ends exactly at
  18877. // the provided document. Without the key (by using the explicit sort
  18878. // orders), multiple documents could match the position, yielding duplicate
  18879. // results.
  18880. for (var o = [], u = 0, a = bn(t); u < a.length; u++) {
  18881. var s = a[u];
  18882. if (s.field.isKeyField()) o.push(fe(e, r.key)); else {
  18883. var c = r.data.field(s.field);
  18884. if (te(c)) throw new j(K.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + s.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');
  18885. if (null === c) {
  18886. var l = s.field.canonicalString();
  18887. throw new j(K.INVALID_ARGUMENT, "Invalid query. You are trying to start or end a query using a document for which the field '".concat(l, "' (used as the orderBy) does not exist."));
  18888. }
  18889. o.push(c);
  18890. }
  18891. }
  18892. return new Se(o, i);
  18893. }(t._query, t.firestore._databaseId, e, n[0]._document, r);
  18894. var i = wl(t.firestore);
  18895. return function(t, e, n, r, i, o) {
  18896. // Use explicit order by's because it has to match the query the user made
  18897. var u = t.explicitOrderBy;
  18898. if (i.length > u.length) throw new j(K.INVALID_ARGUMENT, "Too many arguments provided to ".concat(r, "(). The number of arguments must be less than or equal to the number of orderBy() clauses"));
  18899. for (var a = [], s = 0; s < i.length; s++) {
  18900. var c = i[s];
  18901. if (u[s].field.isKeyField()) {
  18902. if ("string" != typeof c) throw new j(K.INVALID_ARGUMENT, "Invalid query. Expected a string for document ID in ".concat(r, "(), but got a ").concat(typeof c));
  18903. if (!wn(t) && -1 !== c.indexOf("/")) throw new j(K.INVALID_ARGUMENT, "Invalid query. When querying a collection and ordering by documentId(), the value passed to ".concat(r, "() must be a plain document ID, but '").concat(c, "' contains a slash."));
  18904. var l = t.path.child(ct.fromString(c));
  18905. if (!ft.isDocumentKey(l)) throw new j(K.INVALID_ARGUMENT, "Invalid query. When querying a collection group and ordering by documentId(), the value passed to ".concat(r, "() must result in a valid document path, but '").concat(l, "' is not because it contains an odd number of segments."));
  18906. var h = new ft(l);
  18907. a.push(fe(e, h));
  18908. } else {
  18909. var f = Cl(n, r, c);
  18910. a.push(f);
  18911. }
  18912. }
  18913. return new Se(a, o);
  18914. }(t._query, t.firestore._databaseId, i, e, n, r);
  18915. }
  18916. function ch(t, e, n) {
  18917. if ("string" == typeof (n = y(n))) {
  18918. if ("" === n) throw new j(K.INVALID_ARGUMENT, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");
  18919. if (!wn(e) && -1 !== n.indexOf("/")) throw new j(K.INVALID_ARGUMENT, "Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '".concat(n, "' contains a '/' character."));
  18920. var r = e.path.child(ct.fromString(n));
  18921. if (!ft.isDocumentKey(r)) throw new j(K.INVALID_ARGUMENT, "Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '".concat(r, "' is not because it has an odd number of segments (").concat(r.length, ")."));
  18922. return fe(t, new ft(r));
  18923. }
  18924. if (n instanceof dc) return fe(t, n._key);
  18925. throw new j(K.INVALID_ARGUMENT, "Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ".concat(uc(n), "."));
  18926. }
  18927. /**
  18928. * Validates that the value passed into a disjunctive filter satisfies all
  18929. * array requirements.
  18930. */ function lh(t, e) {
  18931. if (!Array.isArray(t) || 0 === t.length) throw new j(K.INVALID_ARGUMENT, "Invalid Query. A non-empty array is required for '".concat(e.toString(), "' filters."));
  18932. if (t.length > 10) throw new j(K.INVALID_ARGUMENT, "Invalid Query. '".concat(e.toString(), "' filters support a maximum of 10 elements in the value array."));
  18933. }
  18934. /**
  18935. * Given an operator, returns the set of operators that cannot be used with it.
  18936. *
  18937. * Operators in a query must adhere to the following set of rules:
  18938. * 1. Only one array operator is allowed.
  18939. * 2. Only one disjunctive operator is allowed.
  18940. * 3. `NOT_EQUAL` cannot be used with another `NOT_EQUAL` operator.
  18941. * 4. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.
  18942. *
  18943. * Array operators: `ARRAY_CONTAINS`, `ARRAY_CONTAINS_ANY`
  18944. * Disjunctive operators: `IN`, `ARRAY_CONTAINS_ANY`, `NOT_IN`
  18945. */ function hh(t, e) {
  18946. if (e.isInequality()) {
  18947. var n = gn(t), r = e.field;
  18948. if (null !== n && !n.isEqual(r)) throw new j(K.INVALID_ARGUMENT, "Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '".concat(n.toString(), "' and '").concat(r.toString(), "'"));
  18949. var i = mn(t);
  18950. null !== i && fh(t, r, i);
  18951. }
  18952. var o = function(t, e) {
  18953. for (var n = 0, r = t; n < r.length; n++) for (var i = 0, o = r[n].getFlattenedFilters(); i < o.length; i++) {
  18954. var u = o[i];
  18955. if (e.indexOf(u.op) >= 0) return u.op;
  18956. }
  18957. return null;
  18958. }(t.filters, function(t) {
  18959. switch (t) {
  18960. case "!=" /* Operator.NOT_EQUAL */ :
  18961. return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ];
  18962. case "array-contains" /* Operator.ARRAY_CONTAINS */ :
  18963. return [ "array-contains" /* Operator.ARRAY_CONTAINS */ , "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "not-in" /* Operator.NOT_IN */ ];
  18964. case "in" /* Operator.IN */ :
  18965. return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ ];
  18966. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  18967. return [ "array-contains" /* Operator.ARRAY_CONTAINS */ , "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ ];
  18968. case "not-in" /* Operator.NOT_IN */ :
  18969. return [ "array-contains" /* Operator.ARRAY_CONTAINS */ , "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ];
  18970. default:
  18971. return [];
  18972. }
  18973. }(e.op));
  18974. if (null !== o)
  18975. // Special case when it's a duplicate op to give a slightly clearer error message.
  18976. throw o === e.op ? new j(K.INVALID_ARGUMENT, "Invalid query. You cannot use more than one '".concat(e.op.toString(), "' filter.")) : new j(K.INVALID_ARGUMENT, "Invalid query. You cannot use '".concat(e.op.toString(), "' filters with '").concat(o.toString(), "' filters."));
  18977. }
  18978. function fh(t, e, n) {
  18979. if (!n.isEqual(e)) throw new j(K.INVALID_ARGUMENT, "Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '".concat(e.toString(), "' and so you must also use '").concat(e.toString(), "' as your first argument to orderBy(), but your first orderBy() is on field '").concat(n.toString(), "' instead."));
  18980. }
  18981. function dh(t, e) {
  18982. if (!(e instanceof zl || e instanceof Hl)) throw new j(K.INVALID_ARGUMENT, "Function ".concat(t, "() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'."));
  18983. }
  18984. var ph = /** @class */ function() {
  18985. function t() {}
  18986. return t.prototype.convertValue = function(t, e) {
  18987. switch (void 0 === e && (e = "none"), oe(t)) {
  18988. case 0 /* TypeOrder.NullValue */ :
  18989. return null;
  18990. case 1 /* TypeOrder.BooleanValue */ :
  18991. return t.booleanValue;
  18992. case 2 /* TypeOrder.NumberValue */ :
  18993. return Jt(t.integerValue || t.doubleValue);
  18994. case 3 /* TypeOrder.TimestampValue */ :
  18995. return this.convertTimestamp(t.timestampValue);
  18996. case 4 /* TypeOrder.ServerTimestampValue */ :
  18997. return this.convertServerTimestamp(t, e);
  18998. case 5 /* TypeOrder.StringValue */ :
  18999. return t.stringValue;
  19000. case 6 /* TypeOrder.BlobValue */ :
  19001. return this.convertBytes($t(t.bytesValue));
  19002. case 7 /* TypeOrder.RefValue */ :
  19003. return this.convertReference(t.referenceValue);
  19004. case 8 /* TypeOrder.GeoPointValue */ :
  19005. return this.convertGeoPoint(t.geoPointValue);
  19006. case 9 /* TypeOrder.ArrayValue */ :
  19007. return this.convertArray(t.arrayValue, e);
  19008. case 10 /* TypeOrder.ObjectValue */ :
  19009. return this.convertObject(t.mapValue, e);
  19010. default:
  19011. throw q();
  19012. }
  19013. }, t.prototype.convertObject = function(t, e) {
  19014. var n = this, r = {};
  19015. return Kt(t.fields, (function(t, i) {
  19016. r[t] = n.convertValue(i, e);
  19017. })), r;
  19018. }, t.prototype.convertGeoPoint = function(t) {
  19019. return new fl(Jt(t.latitude), Jt(t.longitude));
  19020. }, t.prototype.convertArray = function(t, e) {
  19021. var n = this;
  19022. return (t.values || []).map((function(t) {
  19023. return n.convertValue(t, e);
  19024. }));
  19025. }, t.prototype.convertServerTimestamp = function(t, e) {
  19026. switch (e) {
  19027. case "previous":
  19028. var n = ee(t);
  19029. return null == n ? null : this.convertValue(n, e);
  19030. case "estimate":
  19031. return this.convertTimestamp(ne(t));
  19032. default:
  19033. return null;
  19034. }
  19035. }, t.prototype.convertTimestamp = function(t) {
  19036. var e = Zt(t);
  19037. return new ut(e.seconds, e.nanos);
  19038. }, t.prototype.convertDocumentKey = function(t, e) {
  19039. var n = ct.fromString(t);
  19040. U(pi(n));
  19041. var r = new Bt(n.get(1), n.get(3)), i = new ft(n.popFirst(5));
  19042. return r.isEqual(e) ||
  19043. // TODO(b/64130202): Somehow support foreign references.
  19044. M("Document ".concat(i, " contains a document reference within a different database (").concat(r.projectId, "/").concat(r.database, ") which is not supported. It will be treated as a reference in the current database (").concat(e.projectId, "/").concat(e.database, ") instead.")),
  19045. i;
  19046. }, t;
  19047. }();
  19048. /**
  19049. * @license
  19050. * Copyright 2020 Google LLC
  19051. *
  19052. * Licensed under the Apache License, Version 2.0 (the "License");
  19053. * you may not use this file except in compliance with the License.
  19054. * You may obtain a copy of the License at
  19055. *
  19056. * http://www.apache.org/licenses/LICENSE-2.0
  19057. *
  19058. * Unless required by applicable law or agreed to in writing, software
  19059. * distributed under the License is distributed on an "AS IS" BASIS,
  19060. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19061. * See the License for the specific language governing permissions and
  19062. * limitations under the License.
  19063. */
  19064. /**
  19065. * Converts custom model object of type T into `DocumentData` by applying the
  19066. * converter if it exists.
  19067. *
  19068. * This function is used when converting user objects to `DocumentData`
  19069. * because we want to provide the user with a more specific error message if
  19070. * their `set()` or fails due to invalid data originating from a `toFirestore()`
  19071. * call.
  19072. */ function yh(t, e, n) {
  19073. // Cast to `any` in order to satisfy the union type constraint on
  19074. // toFirestore().
  19075. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  19076. return t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e;
  19077. }
  19078. var vh = /** @class */ function(e) {
  19079. function n(t) {
  19080. var n = this;
  19081. return (n = e.call(this) || this).firestore = t, n;
  19082. }
  19083. return t(n, e), n.prototype.convertBytes = function(t) {
  19084. return new sl(t);
  19085. }, n.prototype.convertReference = function(t) {
  19086. var e = this.convertDocumentKey(t, this.firestore._databaseId);
  19087. return new dc(this.firestore, /* converter= */ null, e);
  19088. }, n;
  19089. }(ph), mh = /** @class */ function() {
  19090. /** @hideconstructor */
  19091. function t(t, e) {
  19092. this.hasPendingWrites = t, this.fromCache = e
  19093. /**
  19094. * Returns true if this `SnapshotMetadata` is equal to the provided one.
  19095. *
  19096. * @param other - The `SnapshotMetadata` to compare against.
  19097. * @returns true if this `SnapshotMetadata` is equal to the provided one.
  19098. */;
  19099. }
  19100. return t.prototype.isEqual = function(t) {
  19101. return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;
  19102. }, t;
  19103. }(), gh = /** @class */ function(e) {
  19104. /** @hideconstructor protected */
  19105. function n(t, n, r, i, o, u) {
  19106. var a = this;
  19107. return (a = e.call(this, t, n, r, i, u) || this)._firestore = t, a._firestoreImpl = t,
  19108. a.metadata = o, a;
  19109. }
  19110. /**
  19111. * Returns whether or not the data exists. True if the document exists.
  19112. */ return t(n, e), n.prototype.exists = function() {
  19113. return e.prototype.exists.call(this);
  19114. },
  19115. /**
  19116. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  19117. * the document doesn't exist.
  19118. *
  19119. * By default, `serverTimestamp()` values that have not yet been
  19120. * set to their final value will be returned as `null`. You can override
  19121. * this by passing an options object.
  19122. *
  19123. * @param options - An options object to configure how data is retrieved from
  19124. * the snapshot (for example the desired behavior for server timestamps that
  19125. * have not yet been set to their final value).
  19126. * @returns An `Object` containing all fields in the document or `undefined` if
  19127. * the document doesn't exist.
  19128. */
  19129. n.prototype.data = function(t) {
  19130. if (void 0 === t && (t = {}), this._document) {
  19131. if (this._converter) {
  19132. // We only want to use the converter and create a new DocumentSnapshot
  19133. // if a converter has been provided.
  19134. var e = new wh(this._firestore, this._userDataWriter, this._key, this._document, this.metadata,
  19135. /* converter= */ null);
  19136. return this._converter.fromFirestore(e, t);
  19137. }
  19138. return this._userDataWriter.convertValue(this._document.data.value, t.serverTimestamps);
  19139. }
  19140. },
  19141. /**
  19142. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  19143. * document or field doesn't exist.
  19144. *
  19145. * By default, a `serverTimestamp()` that has not yet been set to
  19146. * its final value will be returned as `null`. You can override this by
  19147. * passing an options object.
  19148. *
  19149. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  19150. * field.
  19151. * @param options - An options object to configure how the field is retrieved
  19152. * from the snapshot (for example the desired behavior for server timestamps
  19153. * that have not yet been set to their final value).
  19154. * @returns The data at the specified field location or undefined if no such
  19155. * field exists in the document.
  19156. */
  19157. // We are using `any` here to avoid an explicit cast by our users.
  19158. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  19159. n.prototype.get = function(t, e) {
  19160. if (void 0 === e && (e = {}), this._document) {
  19161. var n = this._document.data.field(Bl("DocumentSnapshot.get", t));
  19162. if (null !== n) return this._userDataWriter.convertValue(n, e.serverTimestamps);
  19163. }
  19164. }, n;
  19165. }(ql), wh = /** @class */ function(e) {
  19166. function n() {
  19167. return null !== e && e.apply(this, arguments) || this;
  19168. }
  19169. /**
  19170. * Retrieves all fields in the document as an `Object`.
  19171. *
  19172. * By default, `serverTimestamp()` values that have not yet been
  19173. * set to their final value will be returned as `null`. You can override
  19174. * this by passing an options object.
  19175. *
  19176. * @override
  19177. * @param options - An options object to configure how data is retrieved from
  19178. * the snapshot (for example the desired behavior for server timestamps that
  19179. * have not yet been set to their final value).
  19180. * @returns An `Object` containing all fields in the document.
  19181. */ return t(n, e), n.prototype.data = function(t) {
  19182. return void 0 === t && (t = {}), e.prototype.data.call(this, t);
  19183. }, n;
  19184. }(gh), bh = /** @class */ function() {
  19185. /** @hideconstructor */
  19186. function t(t, e, n, r) {
  19187. this._firestore = t, this._userDataWriter = e, this._snapshot = r, this.metadata = new mh(r.hasPendingWrites, r.fromCache),
  19188. this.query = n;
  19189. }
  19190. return Object.defineProperty(t.prototype, "docs", {
  19191. /** An array of all the documents in the `QuerySnapshot`. */ get: function() {
  19192. var t = [];
  19193. return this.forEach((function(e) {
  19194. return t.push(e);
  19195. })), t;
  19196. },
  19197. enumerable: !1,
  19198. configurable: !0
  19199. }), Object.defineProperty(t.prototype, "size", {
  19200. /** The number of documents in the `QuerySnapshot`. */ get: function() {
  19201. return this._snapshot.docs.size;
  19202. },
  19203. enumerable: !1,
  19204. configurable: !0
  19205. }), Object.defineProperty(t.prototype, "empty", {
  19206. /** True if there are no documents in the `QuerySnapshot`. */ get: function() {
  19207. return 0 === this.size;
  19208. },
  19209. enumerable: !1,
  19210. configurable: !0
  19211. }),
  19212. /**
  19213. * Enumerates all of the documents in the `QuerySnapshot`.
  19214. *
  19215. * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
  19216. * each document in the snapshot.
  19217. * @param thisArg - The `this` binding for the callback.
  19218. */
  19219. t.prototype.forEach = function(t, e) {
  19220. var n = this;
  19221. this._snapshot.docs.forEach((function(r) {
  19222. t.call(e, new wh(n._firestore, n._userDataWriter, r.key, r, new mh(n._snapshot.mutatedKeys.has(r.key), n._snapshot.fromCache), n.query.converter));
  19223. }));
  19224. },
  19225. /**
  19226. * Returns an array of the documents changes since the last snapshot. If this
  19227. * is the first snapshot, all documents will be in the list as 'added'
  19228. * changes.
  19229. *
  19230. * @param options - `SnapshotListenOptions` that control whether metadata-only
  19231. * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
  19232. * snapshot events.
  19233. */
  19234. t.prototype.docChanges = function(t) {
  19235. void 0 === t && (t = {});
  19236. var e = !!t.includeMetadataChanges;
  19237. if (e && this._snapshot.excludesMetadataChanges) throw new j(K.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");
  19238. return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === e || (this._cachedChanges =
  19239. /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */
  19240. function(t, e) {
  19241. if (t._snapshot.oldDocs.isEmpty()) {
  19242. var n = 0;
  19243. return t._snapshot.docChanges.map((function(e) {
  19244. var r = new wh(t._firestore, t._userDataWriter, e.doc.key, e.doc, new mh(t._snapshot.mutatedKeys.has(e.doc.key), t._snapshot.fromCache), t.query.converter);
  19245. return e.doc, {
  19246. type: "added",
  19247. doc: r,
  19248. oldIndex: -1,
  19249. newIndex: n++
  19250. };
  19251. }));
  19252. }
  19253. // A `DocumentSet` that is updated incrementally as changes are applied to use
  19254. // to lookup the index of a document.
  19255. var r = t._snapshot.oldDocs;
  19256. return t._snapshot.docChanges.filter((function(t) {
  19257. return e || 3 /* ChangeType.Metadata */ !== t.type;
  19258. })).map((function(e) {
  19259. var n = new wh(t._firestore, t._userDataWriter, e.doc.key, e.doc, new mh(t._snapshot.mutatedKeys.has(e.doc.key), t._snapshot.fromCache), t.query.converter), i = -1, o = -1;
  19260. return 0 /* ChangeType.Added */ !== e.type && (i = r.indexOf(e.doc.key), r = r.delete(e.doc.key)),
  19261. 1 /* ChangeType.Removed */ !== e.type && (o = (r = r.add(e.doc)).indexOf(e.doc.key)),
  19262. {
  19263. type: Ih(e.type),
  19264. doc: n,
  19265. oldIndex: i,
  19266. newIndex: o
  19267. };
  19268. }));
  19269. }(this, e), this._cachedChangesIncludeMetadataChanges = e), this._cachedChanges;
  19270. }, t;
  19271. }();
  19272. /**
  19273. * @license
  19274. * Copyright 2020 Google LLC
  19275. *
  19276. * Licensed under the Apache License, Version 2.0 (the "License");
  19277. * you may not use this file except in compliance with the License.
  19278. * You may obtain a copy of the License at
  19279. *
  19280. * http://www.apache.org/licenses/LICENSE-2.0
  19281. *
  19282. * Unless required by applicable law or agreed to in writing, software
  19283. * distributed under the License is distributed on an "AS IS" BASIS,
  19284. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19285. * See the License for the specific language governing permissions and
  19286. * limitations under the License.
  19287. */
  19288. /**
  19289. * Metadata about a snapshot, describing the state of the snapshot.
  19290. */ function Ih(t) {
  19291. switch (t) {
  19292. case 0 /* ChangeType.Added */ :
  19293. return "added";
  19294. case 2 /* ChangeType.Modified */ :
  19295. case 3 /* ChangeType.Metadata */ :
  19296. return "modified";
  19297. case 1 /* ChangeType.Removed */ :
  19298. return "removed";
  19299. default:
  19300. return q();
  19301. }
  19302. }
  19303. // TODO(firestoreexp): Add tests for snapshotEqual with different snapshot
  19304. // metadata
  19305. /**
  19306. * Returns true if the provided snapshots are equal.
  19307. *
  19308. * @param left - A snapshot to compare.
  19309. * @param right - A snapshot to compare.
  19310. * @returns true if the snapshots are equal.
  19311. */ function Th(t, e) {
  19312. return t instanceof gh && e instanceof gh ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof bh && e instanceof bh && t._firestore === e._firestore && bc(t.query, e.query) && t.metadata.isEqual(e.metadata) && t._snapshot.isEqual(e._snapshot);
  19313. }
  19314. /**
  19315. * @license
  19316. * Copyright 2020 Google LLC
  19317. *
  19318. * Licensed under the Apache License, Version 2.0 (the "License");
  19319. * you may not use this file except in compliance with the License.
  19320. * You may obtain a copy of the License at
  19321. *
  19322. * http://www.apache.org/licenses/LICENSE-2.0
  19323. *
  19324. * Unless required by applicable law or agreed to in writing, software
  19325. * distributed under the License is distributed on an "AS IS" BASIS,
  19326. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19327. * See the License for the specific language governing permissions and
  19328. * limitations under the License.
  19329. */
  19330. /**
  19331. * Reads the document referred to by this `DocumentReference`.
  19332. *
  19333. * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting
  19334. * for data from the server, but it may return cached data or fail if you are
  19335. * offline and the server cannot be reached. To specify this behavior, invoke
  19336. * {@link getDocFromCache} or {@link getDocFromServer}.
  19337. *
  19338. * @param reference - The reference of the document to fetch.
  19339. * @returns A Promise resolved with a `DocumentSnapshot` containing the
  19340. * current document contents.
  19341. */ function Eh(t) {
  19342. t = ac(t, dc);
  19343. var e = ac(t.firestore, zc);
  19344. return Uc(Yc(e), t._key).then((function(n) {
  19345. return Lh(e, t, n);
  19346. }));
  19347. }
  19348. var Sh = /** @class */ function(e) {
  19349. function n(t) {
  19350. var n = this;
  19351. return (n = e.call(this) || this).firestore = t, n;
  19352. }
  19353. return t(n, e), n.prototype.convertBytes = function(t) {
  19354. return new sl(t);
  19355. }, n.prototype.convertReference = function(t) {
  19356. var e = this.convertDocumentKey(t, this.firestore._databaseId);
  19357. return new dc(this.firestore, /* converter= */ null, e);
  19358. }, n;
  19359. }(ph);
  19360. /**
  19361. * Reads the document referred to by this `DocumentReference` from cache.
  19362. * Returns an error if the document is not currently cached.
  19363. *
  19364. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  19365. * current document contents.
  19366. */ function _h(t) {
  19367. t = ac(t, dc);
  19368. var r = ac(t.firestore, zc), i = Yc(r), o = new Sh(r);
  19369. return function(t, r) {
  19370. var i = this, o = new Q;
  19371. return t.asyncQueue.enqueueAndForget((function() {
  19372. return e(i, void 0, void 0, (function() {
  19373. var i;
  19374. return n(this, (function(u) {
  19375. switch (u.label) {
  19376. case 0:
  19377. return i = function(t, r, i) {
  19378. return e(this, void 0, void 0, (function() {
  19379. var e, o, u;
  19380. return n(this, (function(n) {
  19381. switch (n.label) {
  19382. case 0:
  19383. return n.trys.push([ 0, 2, , 3 ]), [ 4 /*yield*/ , function(t, e) {
  19384. var n = G(t);
  19385. return n.persistence.runTransaction("read document", "readonly", (function(t) {
  19386. return n.localDocuments.getDocument(t, e);
  19387. }));
  19388. }(t, r) ];
  19389. case 1:
  19390. return (e = n.sent()).isFoundDocument() ? i.resolve(e) : e.isNoDocument() ? i.resolve(null) : i.reject(new j(K.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.)")),
  19391. [ 3 /*break*/ , 3 ];
  19392. case 2:
  19393. return o = n.sent(), u = Ja(o, "Failed to get document '".concat(r, " from cache")),
  19394. i.reject(u), [ 3 /*break*/ , 3 ];
  19395. case 3:
  19396. return [ 2 /*return*/ ];
  19397. }
  19398. }));
  19399. }));
  19400. }, [ 4 /*yield*/ , Vc(t) ];
  19401. case 1:
  19402. return [ 2 /*return*/ , i.apply(void 0, [ u.sent(), r, o ]) ];
  19403. }
  19404. }));
  19405. }));
  19406. })), o.promise;
  19407. }(i, t._key).then((function(e) {
  19408. return new gh(r, o, t._key, e, new mh(null !== e && e.hasLocalMutations,
  19409. /* fromCache= */ !0), t.converter);
  19410. }));
  19411. }
  19412. /**
  19413. * Reads the document referred to by this `DocumentReference` from the server.
  19414. * Returns an error if the network is not available.
  19415. *
  19416. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  19417. * current document contents.
  19418. */ function Dh(t) {
  19419. t = ac(t, dc);
  19420. var e = ac(t.firestore, zc);
  19421. return Uc(Yc(e), t._key, {
  19422. source: "server"
  19423. }).then((function(n) {
  19424. return Lh(e, t, n);
  19425. }));
  19426. }
  19427. /**
  19428. * Executes the query and returns the results as a `QuerySnapshot`.
  19429. *
  19430. * Note: `getDocs()` attempts to provide up-to-date data when possible by
  19431. * waiting for data from the server, but it may return cached data or fail if
  19432. * you are offline and the server cannot be reached. To specify this behavior,
  19433. * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.
  19434. *
  19435. * @returns A `Promise` that will be resolved with the results of the query.
  19436. */ function xh(t) {
  19437. t = ac(t, pc);
  19438. var e = ac(t.firestore, zc), n = Yc(e), r = new Sh(e);
  19439. return Gl(t._query), Bc(n, t._query).then((function(n) {
  19440. return new bh(e, r, t, n);
  19441. }))
  19442. /**
  19443. * Executes the query and returns the results as a `QuerySnapshot` from cache.
  19444. * Returns an empty result set if no documents matching the query are currently
  19445. * cached.
  19446. *
  19447. * @returns A `Promise` that will be resolved with the results of the query.
  19448. */;
  19449. }
  19450. function Ah(t) {
  19451. t = ac(t, pc);
  19452. var r = ac(t.firestore, zc), i = Yc(r), o = new Sh(r);
  19453. return function(t, r) {
  19454. var i = this, o = new Q;
  19455. return t.asyncQueue.enqueueAndForget((function() {
  19456. return e(i, void 0, void 0, (function() {
  19457. var i;
  19458. return n(this, (function(u) {
  19459. switch (u.label) {
  19460. case 0:
  19461. return i = function(t, r, i) {
  19462. return e(this, void 0, void 0, (function() {
  19463. var e, o, u, a, s, c;
  19464. return n(this, (function(n) {
  19465. switch (n.label) {
  19466. case 0:
  19467. return n.trys.push([ 0, 2, , 3 ]), [ 4 /*yield*/ , Hu(t, r,
  19468. /* usePreviousResults= */ !0) ];
  19469. case 1:
  19470. return e = n.sent(), o = new vs(r, e.Hi), u = o.Wu(e.documents), a = o.applyChanges(u,
  19471. /* updateLimboDocuments= */ !1), i.resolve(a.snapshot), [ 3 /*break*/ , 3 ];
  19472. case 2:
  19473. return s = n.sent(), c = Ja(s, "Failed to execute query '".concat(r, " against cache")),
  19474. i.reject(c), [ 3 /*break*/ , 3 ];
  19475. case 3:
  19476. return [ 2 /*return*/ ];
  19477. }
  19478. }));
  19479. }));
  19480. }, [ 4 /*yield*/ , Vc(t) ];
  19481. case 1:
  19482. return [ 2 /*return*/ , i.apply(void 0, [ u.sent(), r, o ]) ];
  19483. }
  19484. }));
  19485. }));
  19486. })), o.promise;
  19487. }(i, t._query).then((function(e) {
  19488. return new bh(r, o, t, e);
  19489. }));
  19490. }
  19491. /**
  19492. * Executes the query and returns the results as a `QuerySnapshot` from the
  19493. * server. Returns an error if the network is not available.
  19494. *
  19495. * @returns A `Promise` that will be resolved with the results of the query.
  19496. */ function Ch(t) {
  19497. t = ac(t, pc);
  19498. var e = ac(t.firestore, zc), n = Yc(e), r = new Sh(e);
  19499. return Bc(n, t._query, {
  19500. source: "server"
  19501. }).then((function(n) {
  19502. return new bh(e, r, t, n);
  19503. }));
  19504. }
  19505. function Nh(t, e, n) {
  19506. t = ac(t, dc);
  19507. var r = ac(t.firestore, zc), i = yh(t.converter, e, n);
  19508. return Mh(r, [ bl(wl(r), "setDoc", t._key, i, null !== t.converter, n).toMutation(t._key, Hn.none()) ]);
  19509. }
  19510. function kh(t, e, n) {
  19511. for (var r = [], i = 3; i < arguments.length; i++) r[i - 3] = arguments[i];
  19512. t = ac(t, dc);
  19513. var o = ac(t.firestore, zc), u = wl(o);
  19514. return Mh(o, [ ("string" == typeof (
  19515. // For Compat types, we have to "extract" the underlying types before
  19516. // performing validation.
  19517. e = y(e)) || e instanceof cl ? Al(u, "updateDoc", t._key, e, n, r) : xl(u, "updateDoc", t._key, e)).toMutation(t._key, Hn.exists(!0)) ]);
  19518. }
  19519. /**
  19520. * Deletes the document referred to by the specified `DocumentReference`.
  19521. *
  19522. * @param reference - A reference to the document to delete.
  19523. * @returns A Promise resolved once the document has been successfully
  19524. * deleted from the backend (note that it won't resolve while you're offline).
  19525. */ function Fh(t) {
  19526. return Mh(ac(t.firestore, zc), [ new cr(t._key, Hn.none()) ]);
  19527. }
  19528. /**
  19529. * Add a new document to specified `CollectionReference` with the given data,
  19530. * assigning it a document ID automatically.
  19531. *
  19532. * @param reference - A reference to the collection to add this document to.
  19533. * @param data - An Object containing the data for the new document.
  19534. * @returns A `Promise` resolved with a `DocumentReference` pointing to the
  19535. * newly created document after it has been written to the backend (Note that it
  19536. * won't resolve while you're offline).
  19537. */ function Oh(t, e) {
  19538. var n = ac(t.firestore, zc), r = gc(t), i = yh(t.converter, e);
  19539. return Mh(n, [ bl(wl(t.firestore), "addDoc", r._key, i, null !== t.converter, {}).toMutation(r._key, Hn.exists(!1)) ]).then((function() {
  19540. return r;
  19541. }));
  19542. }
  19543. function Rh(t) {
  19544. for (var r, i, o, u = [], a = 1; a < arguments.length; a++) u[a - 1] = arguments[a];
  19545. t = y(t);
  19546. var s = {
  19547. includeMetadataChanges: !1
  19548. }, c = 0;
  19549. "object" != typeof u[c] || Kc(u[c]) || (s = u[c], c++);
  19550. var l, h, f, d = {
  19551. includeMetadataChanges: s.includeMetadataChanges
  19552. };
  19553. if (Kc(u[c])) {
  19554. var p = u[c];
  19555. u[c] = null === (r = p.next) || void 0 === r ? void 0 : r.bind(p), u[c + 1] = null === (i = p.error) || void 0 === i ? void 0 : i.bind(p),
  19556. u[c + 2] = null === (o = p.complete) || void 0 === o ? void 0 : o.bind(p);
  19557. }
  19558. if (t instanceof dc) h = ac(t.firestore, zc), f = yn(t._key.path), l = {
  19559. next: function(e) {
  19560. u[c] && u[c](Lh(h, t, e));
  19561. },
  19562. error: u[c + 1],
  19563. complete: u[c + 2]
  19564. }; else {
  19565. var v = ac(t, pc);
  19566. h = ac(v.firestore, zc), f = v._query;
  19567. var m = new Sh(h);
  19568. l = {
  19569. next: function(t) {
  19570. u[c] && u[c](new bh(h, m, v, t));
  19571. },
  19572. error: u[c + 1],
  19573. complete: u[c + 2]
  19574. }, Gl(t._query);
  19575. }
  19576. return function(t, r, i, o) {
  19577. var u = this, a = new Tc(o), s = new cs(r, a, i);
  19578. return t.asyncQueue.enqueueAndForget((function() {
  19579. return e(u, void 0, void 0, (function() {
  19580. var e;
  19581. return n(this, (function(n) {
  19582. switch (n.label) {
  19583. case 0:
  19584. return e = is, [ 4 /*yield*/ , qc(t) ];
  19585. case 1:
  19586. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), s ]) ];
  19587. }
  19588. }));
  19589. }));
  19590. })), function() {
  19591. a.bc(), t.asyncQueue.enqueueAndForget((function() {
  19592. return e(u, void 0, void 0, (function() {
  19593. var e;
  19594. return n(this, (function(n) {
  19595. switch (n.label) {
  19596. case 0:
  19597. return e = os, [ 4 /*yield*/ , qc(t) ];
  19598. case 1:
  19599. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), s ]) ];
  19600. }
  19601. }));
  19602. }));
  19603. }));
  19604. };
  19605. }(Yc(h), f, d, l);
  19606. }
  19607. function Vh(t, r) {
  19608. return function(t, r) {
  19609. var i = this, o = new Tc(r);
  19610. return t.asyncQueue.enqueueAndForget((function() {
  19611. return e(i, void 0, void 0, (function() {
  19612. var e;
  19613. return n(this, (function(n) {
  19614. switch (n.label) {
  19615. case 0:
  19616. return e = function(t, e) {
  19617. G(t).Ru.add(e),
  19618. // Immediately fire an initial event, indicating all existing listeners
  19619. // are in-sync.
  19620. e.next();
  19621. }, [ 4 /*yield*/ , qc(t) ];
  19622. case 1:
  19623. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), o ]) ];
  19624. }
  19625. }));
  19626. }));
  19627. })), function() {
  19628. o.bc(), t.asyncQueue.enqueueAndForget((function() {
  19629. return e(i, void 0, void 0, (function() {
  19630. var e;
  19631. return n(this, (function(n) {
  19632. switch (n.label) {
  19633. case 0:
  19634. return e = function(t, e) {
  19635. G(t).Ru.delete(e);
  19636. }, [ 4 /*yield*/ , qc(t) ];
  19637. case 1:
  19638. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), o ]) ];
  19639. }
  19640. }));
  19641. }));
  19642. }));
  19643. };
  19644. }(Yc(t = ac(t, zc)), Kc(r) ? r : {
  19645. next: r
  19646. });
  19647. }
  19648. /**
  19649. * Locally writes `mutations` on the async queue.
  19650. * @internal
  19651. */ function Mh(t, r) {
  19652. return function(t, r) {
  19653. var i = this, o = new Q;
  19654. return t.asyncQueue.enqueueAndForget((function() {
  19655. return e(i, void 0, void 0, (function() {
  19656. var e;
  19657. return n(this, (function(n) {
  19658. switch (n.label) {
  19659. case 0:
  19660. return e = Es, [ 4 /*yield*/ , Lc(t) ];
  19661. case 1:
  19662. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), r, o ]) ];
  19663. }
  19664. }));
  19665. }));
  19666. })), o.promise;
  19667. }(Yc(t), r);
  19668. }
  19669. /**
  19670. * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`
  19671. * to a {@link DocumentSnapshot}.
  19672. */ function Lh(t, e, n) {
  19673. var r = n.docs.get(e._key), i = new Sh(t);
  19674. return new gh(t, i, e._key, r, new mh(n.hasPendingWrites, n.fromCache), e.converter);
  19675. }
  19676. /**
  19677. * @license
  19678. * Copyright 2022 Google LLC
  19679. *
  19680. * Licensed under the Apache License, Version 2.0 (the "License");
  19681. * you may not use this file except in compliance with the License.
  19682. * You may obtain a copy of the License at
  19683. *
  19684. * http://www.apache.org/licenses/LICENSE-2.0
  19685. *
  19686. * Unless required by applicable law or agreed to in writing, software
  19687. * distributed under the License is distributed on an "AS IS" BASIS,
  19688. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19689. * See the License for the specific language governing permissions and
  19690. * limitations under the License.
  19691. */
  19692. /**
  19693. * Compares two `AggregateQuerySnapshot` instances for equality.
  19694. *
  19695. * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
  19696. * underlying queries that compare equal, and the same data.
  19697. *
  19698. * @param left - The first `AggregateQuerySnapshot` to compare.
  19699. * @param right - The second `AggregateQuerySnapshot` to compare.
  19700. *
  19701. * @returns `true` if the objects are "equal", as defined above, or `false`
  19702. * otherwise.
  19703. */ function Ph(t, e) {
  19704. return bc(t.query, e.query) && g(t.data(), e.data());
  19705. }
  19706. /**
  19707. * @license
  19708. * Copyright 2022 Google LLC
  19709. *
  19710. * Licensed under the Apache License, Version 2.0 (the "License");
  19711. * you may not use this file except in compliance with the License.
  19712. * You may obtain a copy of the License at
  19713. *
  19714. * http://www.apache.org/licenses/LICENSE-2.0
  19715. *
  19716. * Unless required by applicable law or agreed to in writing, software
  19717. * distributed under the License is distributed on an "AS IS" BASIS,
  19718. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19719. * See the License for the specific language governing permissions and
  19720. * limitations under the License.
  19721. */
  19722. /**
  19723. * Calculates the number of documents in the result set of the given query,
  19724. * without actually downloading the documents.
  19725. *
  19726. * Using this function to count the documents is efficient because only the
  19727. * final count, not the documents' data, is downloaded. This function can even
  19728. * count the documents if the result set would be prohibitively large to
  19729. * download entirely (e.g. thousands of documents).
  19730. *
  19731. * The result received from the server is presented, unaltered, without
  19732. * considering any local state. That is, documents in the local cache are not
  19733. * taken into consideration, neither are local modifications not yet
  19734. * synchronized with the server. Previously-downloaded results, if any, are not
  19735. * used: every request using this source necessarily involves a round trip to
  19736. * the server.
  19737. *
  19738. * @param query - The query whose result set size to calculate.
  19739. * @returns A Promise that will be resolved with the count; the count can be
  19740. * retrieved from `snapshot.data().count`, where `snapshot` is the
  19741. * `AggregateQuerySnapshot` to which the returned Promise resolves.
  19742. */ function qh(t) {
  19743. var r = ac(t.firestore, zc);
  19744. return function(t, r, i) {
  19745. var o = this, u = new Q;
  19746. return t.asyncQueue.enqueueAndForget((function() {
  19747. return e(o, void 0, void 0, (function() {
  19748. var e, o, a, s;
  19749. return n(this, (function(n) {
  19750. switch (n.label) {
  19751. case 0:
  19752. return n.trys.push([ 0, 5, , 6 ]), e = Oa, [ 4 /*yield*/ , Mc(t) ];
  19753. case 1:
  19754. return e.apply(void 0, [ n.sent() ]) ? [ 4 /*yield*/ , Pc(t) ] : [ 3 /*break*/ , 3 ];
  19755. case 2:
  19756. return o = n.sent(), a = new Dc(r, o, i).run(), u.resolve(a), [ 3 /*break*/ , 4 ];
  19757. case 3:
  19758. u.reject(new j(K.UNAVAILABLE, "Failed to get count result because the client is offline.")),
  19759. n.label = 4;
  19760. case 4:
  19761. return [ 3 /*break*/ , 6 ];
  19762. case 5:
  19763. return s = n.sent(), u.reject(s), [ 3 /*break*/ , 6 ];
  19764. case 6:
  19765. return [ 2 /*return*/ ];
  19766. }
  19767. }));
  19768. }));
  19769. })), u.promise;
  19770. }(Yc(r), t, new Sh(r));
  19771. }
  19772. /**
  19773. * @license
  19774. * Copyright 2022 Google LLC
  19775. *
  19776. * Licensed under the Apache License, Version 2.0 (the "License");
  19777. * you may not use this file except in compliance with the License.
  19778. * You may obtain a copy of the License at
  19779. *
  19780. * http://www.apache.org/licenses/LICENSE-2.0
  19781. *
  19782. * Unless required by applicable law or agreed to in writing, software
  19783. * distributed under the License is distributed on an "AS IS" BASIS,
  19784. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19785. * See the License for the specific language governing permissions and
  19786. * limitations under the License.
  19787. */ var Uh = {
  19788. maxAttempts: 5
  19789. }, Bh = /** @class */ function() {
  19790. /** @hideconstructor */
  19791. function t(t, e) {
  19792. this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1,
  19793. this._dataReader = wl(t);
  19794. }
  19795. return t.prototype.set = function(t, e, n) {
  19796. this._verifyNotCommitted();
  19797. var r = Gh(t, this._firestore), i = yh(r.converter, e, n), o = bl(this._dataReader, "WriteBatch.set", r._key, i, null !== r.converter, n);
  19798. return this._mutations.push(o.toMutation(r._key, Hn.none())), this;
  19799. }, t.prototype.update = function(t, e, n) {
  19800. for (var r = [], i = 3; i < arguments.length; i++) r[i - 3] = arguments[i];
  19801. this._verifyNotCommitted();
  19802. var o, u = Gh(t, this._firestore);
  19803. // For Compat types, we have to "extract" the underlying types before
  19804. // performing validation.
  19805. return o = "string" == typeof (e = y(e)) || e instanceof cl ? Al(this._dataReader, "WriteBatch.update", u._key, e, n, r) : xl(this._dataReader, "WriteBatch.update", u._key, e),
  19806. this._mutations.push(o.toMutation(u._key, Hn.exists(!0))), this;
  19807. },
  19808. /**
  19809. * Deletes the document referred to by the provided {@link DocumentReference}.
  19810. *
  19811. * @param documentRef - A reference to the document to be deleted.
  19812. * @returns This `WriteBatch` instance. Used for chaining method calls.
  19813. */
  19814. t.prototype.delete = function(t) {
  19815. this._verifyNotCommitted();
  19816. var e = Gh(t, this._firestore);
  19817. return this._mutations = this._mutations.concat(new cr(e._key, Hn.none())), this;
  19818. },
  19819. /**
  19820. * Commits all of the writes in this write batch as a single atomic unit.
  19821. *
  19822. * The result of these writes will only be reflected in document reads that
  19823. * occur after the returned promise resolves. If the client is offline, the
  19824. * write fails. If you would like to see local modifications or buffer writes
  19825. * until the client is online, use the full Firestore SDK.
  19826. *
  19827. * @returns A `Promise` resolved once all of the writes in the batch have been
  19828. * successfully written to the backend as an atomic unit (note that it won't
  19829. * resolve while you're offline).
  19830. */
  19831. t.prototype.commit = function() {
  19832. return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();
  19833. }, t.prototype._verifyNotCommitted = function() {
  19834. if (this._committed) throw new j(K.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called.");
  19835. }, t;
  19836. }();
  19837. /**
  19838. * @license
  19839. * Copyright 2020 Google LLC
  19840. *
  19841. * Licensed under the Apache License, Version 2.0 (the "License");
  19842. * you may not use this file except in compliance with the License.
  19843. * You may obtain a copy of the License at
  19844. *
  19845. * http://www.apache.org/licenses/LICENSE-2.0
  19846. *
  19847. * Unless required by applicable law or agreed to in writing, software
  19848. * distributed under the License is distributed on an "AS IS" BASIS,
  19849. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19850. * See the License for the specific language governing permissions and
  19851. * limitations under the License.
  19852. */
  19853. /**
  19854. * A write batch, used to perform multiple writes as a single atomic unit.
  19855. *
  19856. * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
  19857. * provides methods for adding writes to the write batch. None of the writes
  19858. * will be committed (or visible locally) until {@link WriteBatch.commit} is
  19859. * called.
  19860. */ function Gh(t, e) {
  19861. if ((t = y(t)).firestore !== e) throw new j(K.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance.");
  19862. return t;
  19863. }
  19864. /**
  19865. * @license
  19866. * Copyright 2020 Google LLC
  19867. *
  19868. * Licensed under the Apache License, Version 2.0 (the "License");
  19869. * you may not use this file except in compliance with the License.
  19870. * You may obtain a copy of the License at
  19871. *
  19872. * http://www.apache.org/licenses/LICENSE-2.0
  19873. *
  19874. * Unless required by applicable law or agreed to in writing, software
  19875. * distributed under the License is distributed on an "AS IS" BASIS,
  19876. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19877. * See the License for the specific language governing permissions and
  19878. * limitations under the License.
  19879. */
  19880. // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the
  19881. // legacy SDK.
  19882. /**
  19883. * A reference to a transaction.
  19884. *
  19885. * The `Transaction` object passed to a transaction's `updateFunction` provides
  19886. * the methods to read and write data within the transaction context. See
  19887. * {@link runTransaction}.
  19888. */
  19889. /**
  19890. * @license
  19891. * Copyright 2020 Google LLC
  19892. *
  19893. * Licensed under the Apache License, Version 2.0 (the "License");
  19894. * you may not use this file except in compliance with the License.
  19895. * You may obtain a copy of the License at
  19896. *
  19897. * http://www.apache.org/licenses/LICENSE-2.0
  19898. *
  19899. * Unless required by applicable law or agreed to in writing, software
  19900. * distributed under the License is distributed on an "AS IS" BASIS,
  19901. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19902. * See the License for the specific language governing permissions and
  19903. * limitations under the License.
  19904. */
  19905. /**
  19906. * A reference to a transaction.
  19907. *
  19908. * The `Transaction` object passed to a transaction's `updateFunction` provides
  19909. * the methods to read and write data within the transaction context. See
  19910. * {@link runTransaction}.
  19911. */ var Kh, jh = /** @class */ function(e) {
  19912. // This class implements the same logic as the Transaction API in the Lite SDK
  19913. // but is subclassed in order to return its own DocumentSnapshot types.
  19914. /** @hideconstructor */
  19915. function n(t, n) {
  19916. var r = this;
  19917. return (r = e.call(this, t, n) || this)._firestore = t, r;
  19918. }
  19919. /**
  19920. * Reads the document referenced by the provided {@link DocumentReference}.
  19921. *
  19922. * @param documentRef - A reference to the document to be read.
  19923. * @returns A `DocumentSnapshot` with the read data.
  19924. */ return t(n, e), n.prototype.get = function(t) {
  19925. var n = this, r = Gh(t, this._firestore), i = new Sh(this._firestore);
  19926. return e.prototype.get.call(this, t).then((function(t) {
  19927. return new gh(n._firestore, i, r._key, t._document, new mh(
  19928. /* hasPendingWrites= */ !1,
  19929. /* fromCache= */ !1), r.converter);
  19930. }));
  19931. }, n;
  19932. }(/** @class */ function() {
  19933. /** @hideconstructor */
  19934. function t(t, e) {
  19935. this._firestore = t, this._transaction = e, this._dataReader = wl(t)
  19936. /**
  19937. * Reads the document referenced by the provided {@link DocumentReference}.
  19938. *
  19939. * @param documentRef - A reference to the document to be read.
  19940. * @returns A `DocumentSnapshot` with the read data.
  19941. */;
  19942. }
  19943. return t.prototype.get = function(t) {
  19944. var e = this, n = Gh(t, this._firestore), r = new vh(this._firestore);
  19945. return this._transaction.lookup([ n._key ]).then((function(t) {
  19946. if (!t || 1 !== t.length) return q();
  19947. var i = t[0];
  19948. if (i.isFoundDocument()) return new ql(e._firestore, r, i.key, i, n.converter);
  19949. if (i.isNoDocument()) return new ql(e._firestore, r, n._key, null, n.converter);
  19950. throw q();
  19951. }));
  19952. }, t.prototype.set = function(t, e, n) {
  19953. var r = Gh(t, this._firestore), i = yh(r.converter, e, n), o = bl(this._dataReader, "Transaction.set", r._key, i, null !== r.converter, n);
  19954. return this._transaction.set(r._key, o), this;
  19955. }, t.prototype.update = function(t, e, n) {
  19956. for (var r = [], i = 3; i < arguments.length; i++) r[i - 3] = arguments[i];
  19957. var o, u = Gh(t, this._firestore);
  19958. // For Compat types, we have to "extract" the underlying types before
  19959. // performing validation.
  19960. return o = "string" == typeof (e = y(e)) || e instanceof cl ? Al(this._dataReader, "Transaction.update", u._key, e, n, r) : xl(this._dataReader, "Transaction.update", u._key, e),
  19961. this._transaction.update(u._key, o), this;
  19962. },
  19963. /**
  19964. * Deletes the document referred to by the provided {@link DocumentReference}.
  19965. *
  19966. * @param documentRef - A reference to the document to be deleted.
  19967. * @returns This `Transaction` instance. Used for chaining method calls.
  19968. */
  19969. t.prototype.delete = function(t) {
  19970. var e = Gh(t, this._firestore);
  19971. return this._transaction.delete(e._key), this;
  19972. }, t;
  19973. }());
  19974. /**
  19975. * Executes the given `updateFunction` and then attempts to commit the changes
  19976. * applied within the transaction. If any document read within the transaction
  19977. * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
  19978. * commit after 5 attempts, the transaction fails.
  19979. *
  19980. * The maximum number of writes allowed in a single transaction is 500.
  19981. *
  19982. * @param firestore - A reference to the Firestore database to run this
  19983. * transaction against.
  19984. * @param updateFunction - The function to execute within the transaction
  19985. * context.
  19986. * @param options - An options object to configure maximum number of attempts to
  19987. * commit.
  19988. * @returns If the transaction completed successfully or was explicitly aborted
  19989. * (the `updateFunction` returned a failed promise), the promise returned by the
  19990. * `updateFunction `is returned here. Otherwise, if the transaction failed, a
  19991. * rejected promise with the corresponding failure error is returned.
  19992. */ function Qh(t, r, i) {
  19993. t = ac(t, zc);
  19994. var o = Object.assign(Object.assign({}, Uh), i);
  19995. return function(t) {
  19996. if (t.maxAttempts < 1) throw new j(K.INVALID_ARGUMENT, "Max attempts must be at least 1");
  19997. }(o), function(t, r, i) {
  19998. var o = this, u = new Q;
  19999. return t.asyncQueue.enqueueAndForget((function() {
  20000. return e(o, void 0, void 0, (function() {
  20001. var e;
  20002. return n(this, (function(n) {
  20003. switch (n.label) {
  20004. case 0:
  20005. return [ 4 /*yield*/ , Pc(t) ];
  20006. case 1:
  20007. return e = n.sent(), new Ac(t.asyncQueue, e, i, r, u).run(), [ 2 /*return*/ ];
  20008. }
  20009. }));
  20010. }));
  20011. })), u.promise;
  20012. }(Yc(t), (function(e) {
  20013. return r(new jh(t, e));
  20014. }), o);
  20015. }
  20016. /**
  20017. * @license
  20018. * Copyright 2020 Google LLC
  20019. *
  20020. * Licensed under the Apache License, Version 2.0 (the "License");
  20021. * you may not use this file except in compliance with the License.
  20022. * You may obtain a copy of the License at
  20023. *
  20024. * http://www.apache.org/licenses/LICENSE-2.0
  20025. *
  20026. * Unless required by applicable law or agreed to in writing, software
  20027. * distributed under the License is distributed on an "AS IS" BASIS,
  20028. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20029. * See the License for the specific language governing permissions and
  20030. * limitations under the License.
  20031. */
  20032. /**
  20033. * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
  20034. * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
  20035. */ function zh() {
  20036. return new Il("deleteField");
  20037. }
  20038. /**
  20039. * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
  20040. * include a server-generated timestamp in the written data.
  20041. */ function Wh() {
  20042. return new El("serverTimestamp");
  20043. }
  20044. /**
  20045. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  20046. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
  20047. * value that already exists on the server. Each specified element that doesn't
  20048. * already exist in the array will be added to the end. If the field being
  20049. * modified is not already an array it will be overwritten with an array
  20050. * containing exactly the specified elements.
  20051. *
  20052. * @param elements - The elements to union into the array.
  20053. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20054. * `updateDoc()`.
  20055. */ function Hh() {
  20056. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  20057. // NOTE: We don't actually parse the data until it's used in set() or
  20058. // update() since we'd need the Firestore instance to do this.
  20059. return new Sl("arrayUnion", t);
  20060. }
  20061. /**
  20062. * Returns a special value that can be used with {@link (setDoc:1)} or {@link
  20063. * updateDoc:1} that tells the server to remove the given elements from any
  20064. * array value that already exists on the server. All instances of each element
  20065. * specified will be removed from the array. If the field being modified is not
  20066. * already an array it will be overwritten with an empty array.
  20067. *
  20068. * @param elements - The elements to remove from the array.
  20069. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20070. * `updateDoc()`
  20071. */ function Yh() {
  20072. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  20073. // NOTE: We don't actually parse the data until it's used in set() or
  20074. // update() since we'd need the Firestore instance to do this.
  20075. return new _l("arrayRemove", t);
  20076. }
  20077. /**
  20078. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  20079. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
  20080. * the given value.
  20081. *
  20082. * If either the operand or the current field value uses floating point
  20083. * precision, all arithmetic follows IEEE 754 semantics. If both values are
  20084. * integers, values outside of JavaScript's safe number range
  20085. * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
  20086. * precision loss. Furthermore, once processed by the Firestore backend, all
  20087. * integer operations are capped between -2^63 and 2^63-1.
  20088. *
  20089. * If the current field value is not of type `number`, or if the field does not
  20090. * yet exist, the transformation sets the field to the given value.
  20091. *
  20092. * @param n - The value to increment by.
  20093. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20094. * `updateDoc()`
  20095. */ function Xh(t) {
  20096. return new Dl("increment", t);
  20097. }
  20098. /**
  20099. * @license
  20100. * Copyright 2020 Google LLC
  20101. *
  20102. * Licensed under the Apache License, Version 2.0 (the "License");
  20103. * you may not use this file except in compliance with the License.
  20104. * You may obtain a copy of the License at
  20105. *
  20106. * http://www.apache.org/licenses/LICENSE-2.0
  20107. *
  20108. * Unless required by applicable law or agreed to in writing, software
  20109. * distributed under the License is distributed on an "AS IS" BASIS,
  20110. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20111. * See the License for the specific language governing permissions and
  20112. * limitations under the License.
  20113. */
  20114. /**
  20115. * Creates a write batch, used for performing multiple writes as a single
  20116. * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}
  20117. * is 500.
  20118. *
  20119. * Unlike transactions, write batches are persisted offline and therefore are
  20120. * preferable when you don't need to condition your writes on read data.
  20121. *
  20122. * @returns A {@link WriteBatch} that can be used to atomically execute multiple
  20123. * writes.
  20124. */ function Zh(t) {
  20125. return Yc(t = ac(t, zc)), new Bh(t, (function(e) {
  20126. return Mh(t, e);
  20127. }))
  20128. /**
  20129. * @license
  20130. * Copyright 2021 Google LLC
  20131. *
  20132. * Licensed under the Apache License, Version 2.0 (the "License");
  20133. * you may not use this file except in compliance with the License.
  20134. * You may obtain a copy of the License at
  20135. *
  20136. * http://www.apache.org/licenses/LICENSE-2.0
  20137. *
  20138. * Unless required by applicable law or agreed to in writing, software
  20139. * distributed under the License is distributed on an "AS IS" BASIS,
  20140. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20141. * See the License for the specific language governing permissions and
  20142. * limitations under the License.
  20143. */;
  20144. }
  20145. function Jh(t, i) {
  20146. var o, u = Yc(t = ac(t, zc));
  20147. // PORTING NOTE: We don't return an error if the user has not enabled
  20148. // persistence since `enableIndexeddbPersistence()` can fail on the Web.
  20149. if (!(null === (o = u.offlineComponents) || void 0 === o ? void 0 : o.indexBackfillerScheduler)) return L("Cannot enable indexes when persistence is disabled"),
  20150. Promise.resolve();
  20151. var a = function(t) {
  20152. var e = "string" == typeof t ? function(t) {
  20153. try {
  20154. return JSON.parse(t);
  20155. } catch (t) {
  20156. throw new j(K.INVALID_ARGUMENT, "Failed to parse JSON: " + (null == t ? void 0 : t.message));
  20157. }
  20158. }(t) : t, n = [];
  20159. if (Array.isArray(e.indexes)) for (var r = 0, i = e.indexes; r < i.length; r++) {
  20160. var o = i[r], u = $h(o, "collectionGroup"), a = [];
  20161. if (Array.isArray(o.fields)) for (var s = 0, c = o.fields; s < c.length; s++) {
  20162. var l = c[s], h = Ml("setIndexConfiguration", $h(l, "fieldPath"));
  20163. "CONTAINS" === l.arrayConfig ? a.push(new mt(h, 2 /* IndexKind.CONTAINS */)) : "ASCENDING" === l.order ? a.push(new mt(h, 0 /* IndexKind.ASCENDING */)) : "DESCENDING" === l.order && a.push(new mt(h, 1 /* IndexKind.DESCENDING */));
  20164. }
  20165. n.push(new dt(dt.UNKNOWN_ID, u, a, wt.empty()));
  20166. }
  20167. return n;
  20168. }(i);
  20169. return Vc(u).then((function(t) {
  20170. return function(t, i) {
  20171. return e(this, void 0, void 0, (function() {
  20172. var e, o, u;
  20173. return n(this, (function(n) {
  20174. return e = G(t), o = e.indexManager, u = [], [ 2 /*return*/ , e.persistence.runTransaction("Configure indexes", "readwrite", (function(t) {
  20175. return o.getFieldIndexes(t).next((function(e) {
  20176. return function(t, e, n, i, o) {
  20177. t = r([], t, !0), e = r([], e, !0), t.sort(n), e.sort(n);
  20178. for (var u = t.length, a = e.length, s = 0, c = 0; s < a && c < u; ) {
  20179. var l = n(t[c], e[s]);
  20180. l < 0 ?
  20181. // The element was removed if the next element in our ordered
  20182. // walkthrough is only in `before`.
  20183. o(t[c++]) : l > 0 ?
  20184. // The element was added if the next element in our ordered walkthrough
  20185. // is only in `after`.
  20186. i(e[s++]) : (s++, c++);
  20187. }
  20188. for (;s < a; ) i(e[s++]);
  20189. for (;c < u; ) o(t[c++]);
  20190. }(e, i, vt, (function(e) {
  20191. u.push(o.addFieldIndex(t, e));
  20192. }), (function(e) {
  20193. u.push(o.deleteFieldIndex(t, e));
  20194. }));
  20195. })).next((function() {
  20196. return xt.waitFor(u);
  20197. }));
  20198. })) ];
  20199. }));
  20200. }));
  20201. }(t, a);
  20202. }));
  20203. }
  20204. function $h(t, e) {
  20205. if ("string" != typeof t[e]) throw new j(K.INVALID_ARGUMENT, "Missing string value for: " + e);
  20206. return t[e];
  20207. }
  20208. /**
  20209. * Cloud Firestore
  20210. *
  20211. * @packageDocumentation
  20212. */ void 0 === Kh && (Kh = !0), k = i, o(new c("firestore", (function(t, e) {
  20213. var n = e.instanceIdentifier, r = e.options, i = t.getProvider("app").getImmediate(), o = new zc(new Y(t.getProvider("auth-internal")), new $(t.getProvider("app-check-internal")), function(t, e) {
  20214. if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new j(K.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
  20215. return new Bt(t.options.projectId, e);
  20216. }(i, n), i);
  20217. return r = Object.assign({
  20218. useFetchStreams: Kh
  20219. }, r), o._setSettings(r), o;
  20220. }), "PUBLIC").setMultipleInstances(!0)), u(C, "3.8.1", void 0),
  20221. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  20222. u(C, "3.8.1", "esm5");
  20223. export { ph as AbstractUserDataWriter, Sc as AggregateField, _c as AggregateQuerySnapshot, sl as Bytes, Qc as CACHE_SIZE_UNLIMITED, yc as CollectionReference, dc as DocumentReference, gh as DocumentSnapshot, cl as FieldPath, hl as FieldValue, zc as Firestore, j as FirestoreError, fl as GeoPoint, jc as LoadBundleTask, pc as Query, Hl as QueryCompositeFilterConstraint, jl as QueryConstraint, wh as QueryDocumentSnapshot, oh as QueryEndAtConstraint, zl as QueryFieldFilterConstraint, $l as QueryLimitConstraint, Zl as QueryOrderByConstraint, bh as QuerySnapshot, nh as QueryStartAtConstraint, mh as SnapshotMetadata, ut as Timestamp, jh as Transaction, Bh as WriteBatch, Bt as _DatabaseId, ft as _DocumentKey, tt as _EmptyAppCheckTokenProvider, W as _EmptyAuthCredentialsProvider, ht as _FieldPath, ac as _cast, B as _debugAssert, Ht as _isBase64Available, L as _logWarn, rc as _validateIsNotUsedTogether, Oh as addDoc, Ph as aggregateQuerySnapshotEqual, Xl as and, Yh as arrayRemove, Hh as arrayUnion, tl as clearIndexedDbPersistence, vc as collection, mc as collectionGroup, fc as connectFirestoreEmulator, Fh as deleteDoc, zh as deleteField, rl as disableNetwork, gc as doc, ll as documentId, Zc as enableIndexedDbPersistence, Jc as enableMultiTabIndexedDbPersistence, nl as enableNetwork, ah as endAt, uh as endBefore, Yc as ensureFirestoreConfigured, Mh as executeWrite, qh as getCountFromServer, Eh as getDoc, _h as getDocFromCache, Dh as getDocFromServer, xh as getDocs, Ah as getDocsFromCache, Ch as getDocsFromServer, Hc as getFirestore, Xh as increment, Wc as initializeFirestore, th as limit, eh as limitToLast, ol as loadBundle, ul as namedQuery, Rh as onSnapshot, Vh as onSnapshotsInSync, Yl as or, Jl as orderBy, Ql as query, bc as queryEqual, wc as refEqual, Qh as runTransaction, Wh as serverTimestamp, Nh as setDoc, Jh as setIndexConfiguration, R as setLogLevel, Th as snapshotEqual, ih as startAfter, rh as startAt, il as terminate, kh as updateDoc, el as waitForPendingWrites, Wl as where, Zh as writeBatch };
  20224. //# sourceMappingURL=index.esm5.js.map